lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.8.4
/**
 * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
 * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
 * gas optimizations e.g. when performing a transfer operation (avoiding double writes).
 * This has O(1) time complexity, but alters the order of the _ownedTokens array.
 * @param from address representing the previous owner of the given token ID
 * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
 */
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
        // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
        uint256 tokenIndex = _ownedTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary
        if (tokenIndex != lastTokenIndex) {
            uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];

            _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
            _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
        }

        // This also deletes the contents at the last position of the array
        delete _ownedTokensIndex[tokenId];
        delete _ownedTokens[from][lastTokenIndex];
    }
// Solidity 0.8.4
/**
 * @dev Private function to remove a token from this extension's token tracking data structures.
 * This has O(1) time complexity, but alters the order of the _allTokens array.
 * @param tokenId uint256 ID of the token to be removed from the tokens list
 */
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
        // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint256 lastTokenIndex = _allTokens.length - 1;
        uint256 tokenIndex = _allTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
        // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
        // an 'if' statement (like in _removeTokenFromOwnerEnumeration)
        uint256 lastTokenId = _allTokens[lastTokenIndex];

        _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
        _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index

        // This also deletes the contents at the last position of the array
        delete _allTokensIndex[tokenId];
        _allTokens.pop();
    }
// Solidity 0.8.4
// internal minting function
function _mint(uint256 _numToMint, address receiver) internal {
    require(_numToMint <= MAX_MINTABLE_AT_ONCE, "Minting too many at once.");

    uint256 updatedNumAvailableTokens = _numAvailableTokens;
    for (uint256 i = 0; i < _numToMint; i++) {
      uint256 newTokenId = useRandomAvailableToken(_numToMint, i);
      _safeMint(receiver, newTokenId);
      updatedNumAvailableTokens--;
    }
    _numAvailableTokens = updatedNumAvailableTokens;
  }
// Solidity 0.5.17
/**
 * @dev Multiplies two numbers, reverts on overflow.
 */
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
    // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
    // benefit is lost if 'b' is also tested.
    // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
    if (a == 0) {
      return 0;
    }

    uint256 c = a * b;
    require(c / a == b);

    return c;
  }
// Solidity 0.5.17
/**
 * @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
 */
function div(uint256 a, uint256 b) internal pure returns (uint256) {
    require(b > 0); // Solidity only automatically asserts 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.17
/**
 * @dev Multiplies two int256 variables and fails on overflow.
 */
function mul(int256 a, int256 b)
        internal
        pure
        returns (int256)
    {
        int256 c = a * b;

        // Detect overflow when multiplying MIN_INT256 with -1
        require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
        require((b == 0) || (c / b == a));
        return c;
    }
// Solidity 0.5.17
/**
 * @dev Division of two int256 variables and fails on overflow.
 */
function div(int256 a, int256 b)
        internal
        pure
        returns (int256)
    {
        // Prevent overflow when dividing MIN_INT256 by -1
        require(b != -1 || a != MIN_INT256);

        // Solidity already throws when dividing by 0.
        return a / b;
    }
// Solidity 0.4.25
/**
 * @notice Set the fee period duration
 */
function setFeePeriodDuration(uint _feePeriodDuration)
        external
        optionalProxy_onlyOwner
    {
        require(_feePeriodDuration >= MIN_FEE_PERIOD_DURATION, "New fee period cannot be less than minimum fee period duration");
        require(_feePeriodDuration <= MAX_FEE_PERIOD_DURATION, "New fee period cannot be greater than maximum fee period duration");

        feePeriodDuration = _feePeriodDuration;

        emitFeePeriodDurationUpdated(_feePeriodDuration);
    }
// Solidity 0.5.17
/**
 * @dev Adds two int256 variables and fails on overflow.
 */
function add(int256 a, int256 b)
        internal
        pure
        returns (int256)
    {
        int256 c = a + b;
        require((b >= 0 && c >= a) || (b < 0 && c < a));
        return c;
    }
// Solidity 0.5.17
/**
 * @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
 *
 */
function rebase() external {

        require(tx.origin == msg.sender);
        require(canRebase(), "Rebase not allowed");

        lastRebaseTimestampSec = now;

        epoch = epoch.add(1);

        (uint256 exchangeRate, int256 supplyDelta) = getRebaseValues();
        
        uint256 supplyAfterRebase = cum.rebase(epoch, supplyDelta);
        
        assert(supplyAfterRebase <= MAX_SUPPLY);
        
        for (uint i = 0; i < transactions.length; i++) {
            Transaction storage t = transactions[i];
            if (t.enabled) {
                bool result =
                    externalCall(t.destination, t.data);
                if (!result) {
                    emit TransactionFailed(t.destination, i, t.data);
                    revert("Transaction Failed");
                }
            }
        }
        
        marketOracle.update();

        if (epoch < 80) {
            incrementTargetRate();
        } else {
            finalRate();
        }
        
        emit LogRebase(epoch, exchangeRate, supplyDelta, now);
    }
// Solidity 0.5.17
/**
 * @notice Calculates the supplyDelta and returns the current set of values for the rebase
 *
 * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag
 *      Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
 * 
 */
function getRebaseValues() public view returns (uint256, int256) {

        uint256 exchangeRate = marketOracle.getData();

        if (exchangeRate > MAX_RATE) {
            exchangeRate = MAX_RATE;
        }

        int256 supplyDelta = computeSupplyDelta(exchangeRate);

        // Apply the dampening factor.
        if (supplyDelta < 0) {
            supplyDelta = supplyDelta.div(2);
        } else {
            supplyDelta = supplyDelta.div(5);                   
        }

        if (supplyDelta > 0 && cum.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) {
            supplyDelta = (MAX_SUPPLY.sub(cum.totalSupply())).toInt256Safe();
        }

        return (exchangeRate, supplyDelta);
    }
// Solidity 0.5.17
/**
 * @param rate The current exchange rate, an 18 decimal fixed point number.
 * @return If the rate is within the deviation threshold from the target rate, returns true.
 *         Otherwise, returns false.
 */
function withinDeviationThreshold(uint256 rate)
        internal
        view
        returns (bool)
    {
        uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold)
            .div(10 ** DECIMALS);

        return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold)
            || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold);
    }
// Solidity 0.5.17
/**
 * @dev wrapper to call the encoded transactions on downstream consumers.
 * @param destination Address of destination contract.
 * @param data The encoded data payload.
 * @return True on success
 */
function externalCall(address destination, bytes memory data)
        internal
        returns (bool)
    {
        bool result;
        assembly {  // solhint-disable-line no-inline-assembly
            // "Allocate" memory for output
            // (0x40 is where "free memory" pointer is stored by convention)
            let outputAddress := mload(0x40)

            // First 32 bytes are the padded length of data, so exclude that
            let dataAddress := add(data, 32)

            result := call(
                sub(gas(), 34710),
                destination,
                0, // transfer value in wei
                dataAddress,
                mload(data),  // Size of the input, in bytes. Stored in position 0 of the array.
                outputAddress,
                0  // Output is ignored, therefore the output size is zero
            )
        }
        return result;
    }
// Solidity 0.7.0
/**
 * @dev Changes the name for given tokenId
 */
function changeName(uint256 tokenId, string memory newName) public {
        address owner = ownerOf(tokenId);

        require(_msgSender() == owner, "BCE: Ownership");
        require(validateName(newName) == true, "BCE: Invalid");
        require(sha256(bytes(newName)) != sha256(bytes(tokenNames[tokenId])), "BCE: Used");
        require(isNameReserved(newName) == false, "BCE: Taken");

        IERC20(bceNCTAddress).transferFrom(_msgSender(), address(this), 1e20);

        // If already named, dereserve old name
        if (bytes(tokenNames[tokenId]).length > 0) {
            toggleReserveName(tokenNames[tokenId], false);
        }

        toggleReserveName(newName, true);
        tokenNames[tokenId] = newName;
        IERC20(bceNCTAddress).burn(1e20);
        emit NameChange(tokenId, newName);
    }
// Solidity 0.7.0
/**
 * @dev Check if the name string is valid (Alphanumeric and spaces without leading or trailing space)
 */
function validateName(string memory str) public pure returns (bool){
        bytes memory b = bytes(str);
        if(b.length < 1) return false;
        if(b.length > 25) return false; // Cannot be longer than 25 characters
        if(b[0] == 0x20) return false; // Leading space
        if (b[b.length - 1] == 0x20) return false; // Trailing space

        bytes1 lastChar = b[0];

        for(uint i; i<b.length; i++){
            bytes1 char = b[i];

            if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces

            if(
                !(char >= 0x30 && char <= 0x39) && //9-0
                !(char >= 0x41 && char <= 0x5A) && //A-Z
                !(char >= 0x61 && char <= 0x7A) && //a-z
                !(char == 0x20) //space
            )
                return false;

            lastChar = char;
        }

        return true;
    }
// Solidity 0.7.0
/**
 * @dev Converts the string to lowercase
 */
function toLower(string memory str) public pure returns (string memory){
        bytes memory bStr = bytes(str);
        bytes memory bLower = new bytes(bStr.length);
        for (uint i = 0; i < bStr.length; i++) {
            // Uppercase character
            if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) {
                bLower[i] = bytes1(uint8(bStr[i]) + 32);
            } else {
                bLower[i] = bStr[i];
            }
        }
        return string(bLower);
    }
// Solidity 0.8.4
// send contract balance to addresses 1 and 2
function payAccounts() public payable {
        uint256 balance = address(this).balance;
        if (balance != 0) {
            account1.transfer((balance * 33 / 100));
            account2.transfer((balance * 33 / 100));
            account3.transfer(balance * 33 / 100);
        }
    }
// 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.
 */
function _feesAndRewardsFromPeriod(uint period, uint ownershipPercentage, uint debtEntryIndex, uint penalty)
        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 = recentFeePeriods[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 feesFromPeriodWithoutPenalty = recentFeePeriods[period].feesToDistribute
            .multiplyDecimal(debtOwnershipForPeriod);

        uint rewardsFromPeriodWithoutPenalty = recentFeePeriods[period].rewardsToDistribute
            .multiplyDecimal(debtOwnershipForPeriod);

        // Less their penalty if they have one.
        uint feesFromPeriod = feesFromPeriodWithoutPenalty.sub(feesFromPeriodWithoutPenalty.multiplyDecimal(penalty));

        uint rewardsFromPeriod = rewardsFromPeriodWithoutPenalty.sub(rewardsFromPeriodWithoutPenalty.multiplyDecimal(penalty));

        return (
            feesFromPeriod.preciseDecimalToDecimal(),
            rewardsFromPeriod.preciseDecimalToDecimal()
        );
    }
// Solidity 0.8.10
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
 * the total supply.
 *
 * Emits a {Transfer} event with `from` set to the zero address.
 *
 * Requirements:
 *
 * - `account` cannot be the zero address.
 */
function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply = _totalSupply.add(amount);
        _balances[account] = _balances[account].add(amount);
        emit Transfer(address(0), account, amount);
    }
// Solidity 0.8.10
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
  	    require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
  	    require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
  	    swapTokensAtAmount = newAmount;
  	    return true;
  	}
// Solidity 0.8.10
// useful for buybacks or to reclaim any BNB on the contract in a way that helps holders.
function buyBackTokens(uint256 bnbAmountInWei) external onlyOwner {
        // generate the uniswap pair path of weth -> eth
        address[] memory path = new address[](2);
        path[0] = uniswapV2Router.WETH();
        path[1] = address(this);

        // make the swap
        uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: bnbAmountInWei}(
            0, // accept any amount of Ethereum
            path,
            address(0xdead),
            block.timestamp
        );
        emit BuyBackTriggered(bnbAmountInWei);
    }
// Solidity 0.5.12
/**
 * Checks the return value of the previous function up to 32 bytes. Returns true if the previous
 * function returned 0 bytes or 1.
 */
function checkSuccess() private pure returns (bool) {
        // default to failure
        uint256 returnValue = 0;

        assembly {
            // check number of bytes returned from last function call
            switch returndatasize
                // no bytes returned: assume success
                case 0x0 {
                    returnValue := 1
                }
                // 32 bytes returned
                case 0x20 {
                    // copy 32 bytes into scratch space
                    returndatacopy(0x0, 0x0, 0x20)

                    // load those bytes into returnValue
                    returnValue := mload(0x0)
                }
                // not sure what was returned: dont mark as success
                default {

                }
        }

        // check if returned value is one or nothing
        return returnValue != 0;
    }
// Solidity 0.4.24
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
        balances[from] = safeSub(balances[from], tokens);
        allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
        balances[to] = safeAdd(balances[to], tokens);
        emit Transfer(from, to, tokens);
        return true;
    }
// Solidity 0.4.23
/*batch airdrop functions*/
function airdropWithAmount(address [] _recipients, uint256 _value) onlyOwner canMint whenDropable external {
        for (uint i = 0; i < _recipients.length; i++) {
            address recipient = _recipients[i];
            require(totalSupply_.add(_value) <= actualCap_);
            mint(recipient, _value);
        }
    }
// Solidity 0.4.23
/**
 * @dev Function to purchase tokens
 * @return A boolean that indicates if the operation was successful.
 */
function purchase() whenNotLocked canPurchase public payable returns (bool) {
        uint256 ethAmount = msg.value;
        uint256 tokenAmount = ethAmount.div(tokenPrice_).mul(10 ** uint256(decimals));
        require(totalSupply_.add(tokenAmount) <= actualCap_);
        totalSupply_ = totalSupply_.add(tokenAmount);
        balances[msg.sender] = balances[msg.sender].add(tokenAmount);
        etherAmount_ = etherAmount_.add(ethAmount);
        emit onPurchase(msg.sender, ethAmount, tokenAmount);
        emit Transfer(address(0), msg.sender, tokenAmount);
        return true;
    }
// Solidity 0.7.5
/** 
 *  @notice redeem bond for user
 *  @return uint
 */
function redeem(address _depositor) external returns (uint) {
        Bond memory info = bondInfo[ _depositor ];
        uint percentVested = percentVestedFor( _depositor ); // (blocks since last interaction / vesting term remaining)

        if ( percentVested >= 10000 ) { // if fully vested
            delete bondInfo[ _depositor ]; // delete user info
            emit BondRedeemed( _depositor, info.payout, 0 ); // emit bond data
            payoutToken.safeTransfer( _depositor, info.payout );
            return info.payout;

        } else { // if unfinished
            // calculate payout vested
            uint payout = info.payout.mul( percentVested ).div( 10000 );

            // store updated deposit info
            bondInfo[ _depositor ] = Bond({
                payout: info.payout.sub( payout ),
                vesting: info.vesting.sub( block.number.sub( info.lastBlock ) ),
                lastBlock: block.number,
                truePricePaid: info.truePricePaid
            });

            emit BondRedeemed( _depositor, payout, bondInfo[ _depositor ].payout );
            payoutToken.safeTransfer( _depositor, payout );
            return payout;
        }
        
    }
// Solidity 0.8.7
/**
 * @dev See {IERC721-transferFrom}.
 */
function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        //solhint-disable-next-line max-line-length
        require(
            _isApprovedOrOwner(_msgSender(), tokenId),
            "ERC721: transfer caller is not owner nor approved"
        );

        _transfer(from, to, tokenId);
    }
// Solidity 0.8.7
/**
 * @dev See {IERC721-safeTransferFrom}.
 */
function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) public virtual override {
        require(
            _isApprovedOrOwner(_msgSender(), tokenId),
            "ERC721: transfer caller is not owner nor approved"
        );
        _safeTransfer(from, to, tokenId, _data);
    }
// Solidity 0.8.7
/**
 * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
 * are aware of the ERC721 protocol to prevent tokens from being forever locked.
 *
 * `_data` is additional data, it has no specified format and it is sent in call to `to`.
 *
 * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
 * implement alternative mechanisms to perform token transfer, such as signature-based.
 *
 * Requirements:
 *
 * - `from` cannot be the zero address.
 * - `to` cannot be the zero address.
 * - `tokenId` token must exist and be owned by `from`.
 * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
 *
 * Emits a {Transfer} event.
 */
function _safeTransfer(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) internal virtual {
        _transfer(from, to, tokenId);
        require(
            _checkOnERC721Received(from, to, tokenId, _data),
            "ERC721: transfer to non ERC721Receiver implementer"
        );
    }
// Solidity 0.7.5
/**
 *  @notice calculate user's interest due for new bond, accounting for Olympus Fee. 
 If fee is in payout then takes in the already calcualted value. If fee is in principal token 
 than takes in the amount of principal being deposited and then calculautes the fee based on
 the amount of principal and not in terms of the payout token
 *  @param _value uint
 *  @return _payout uint
 *  @return _fee uint
 */
function payoutFor( uint _value ) public view returns ( uint _payout, uint _fee) {
        if(feeInPayout) {
            uint total = FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e11 );
            _fee = total.mul( currentOlympusFee() ).div( 1e6 );
            _payout = total.sub(_fee);
        } else {
            _fee = _value.mul( currentOlympusFee() ).div( 1e6 );
            _payout = FixedPoint.fraction( customTreasury.valueOfToken(address(principalToken), _value.sub(_fee)), bondPrice() ).decode112with18().div( 1e11 );
        }
    }
// Solidity 0.7.5
/**
 *  @notice current fee Olympus takes of each bond
 *  @return currentFee_ uint
 */
function currentOlympusFee() public view returns( uint currentFee_ ) {
        uint tierLength = feeTiers.length;
        for(uint i; i < tierLength; i++) {
            if(totalPrincipalBonded < feeTiers[i].tierCeilings || i == tierLength - 1 ) {
                return feeTiers[i].fees;
            }
        }
    }