lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.4.26
/**
 * Atomically decreases the allowance granted to `spender` by the sender(caller).
 * Emits an {Approval} event indicating the updated allowance.
 *
 * Requirements:
 *
 * - `_spender` cannot be the zero address.
 * - `_spender` must have allowance for the caller of at least `_subtractedValue`.
 */
function decreaseApproval(address _spender, uint _subtractedValue) validAddress(_spender, "_spender is not valid address") public returns (bool) {
        uint oldValue = allowances[msg.sender][_spender];
        allowances[msg.sender][_spender] = _subtractedValue > oldValue ? 0 : oldValue.sub(_subtractedValue);
        emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]);
        return true;
    }
// Solidity 0.4.26
/**
 * Destroys `amount` tokens from `account`, reducing the
 * total supply.
 * Emits a {Transfer} event with `to` set to the zero address.
 *
 * Requirements:
 * - `amount` cannot be less than zero.
 * - `amount` cannot be more than sender(caller)'s balance.
 */
function burn(uint256 amount) public {
        require(amount > 0, "amount cannot be less than zero");
        require(amount <= balances[msg.sender], "amount to burn is more than the caller's balance");
        balances[msg.sender] = balances[msg.sender].sub(amount);
        totalSupply_ = totalSupply_.sub(amount);
        emit Transfer(msg.sender, address(0), amount);
    }
// Solidity 0.4.24
/*uint minBalanceForAccounts;
 
 function setMinBalance(uint minimumBalanceInFinney) public onlyOwner {
 minBalanceForAccounts = minimumBalanceInFinney * 1 finney;
 }*/
function _transfer(address _from, address _to, uint _value) internal {
        require(_to != 0x0);
        require(balanceOf[_from] >= _value);
        require(balanceOf[_to] + _value > balanceOf[_to]);
        uint previousBalances = balanceOf[_from] + balanceOf[_to];
        balanceOf[_from] -= _value;
        balanceOf[_to] += _value;
        emit Transfer(_from, _to, _value);
        assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
    }
// Solidity 0.4.25
/**
 * @dev Function to debit tokens
 * @param _to The address that will receive the drawdown tokens.
 * @param _amount The amount of tokens to debit.
 * @return A boolean that indicates if the operation was successful.
 */
function debit(
    address _to,
    uint256 _amount
  )
    public
    hasDebitPermission
    canDebit
    returns (bool)
  {
    dc = COLLATERAL(collateral_contract);
    uint256 rate = dc.CreditRate();
    uint256 deci = 10 ** decimals; 
    uint256 _amount_1 =  _amount / deci / rate;
    uint256 _amount_2 =  _amount_1 * deci * rate;
    
    require( _amount_1 > 0);
    dc.credit( _amount_1 );  
    
    uint256 _amountx = _amount_2;
    totalSupply = totalSupply.add(_amountx);
    balances[_to] = balances[_to].add(_amountx);
    emit Debit(collateral_contract, _amountx);
    emit Deposit( _to, _amountx);
    return true;
  }
// Solidity 0.8.7
// IPeachProject
function canMint(uint256 quantity) public view override returns (bool) {
        require(saleIsActive, "sale hasn't started");
        require(!presaleIsActive, 'only presale');
        require(totalSupply().add(quantity) <= MAX_TOKENS, 'quantity exceeds supply');
        require(_publicMinted.add(quantity) <= maxMintableSupply, 'quantity exceeds mintable');
        require(quantity <= maxPurchaseQuantity, 'quantity exceeds max');

        return true;
    }
// Solidity 0.8.7
// IPeachProjectAdmin
function mintToAddress(uint256 quantity, address to) external override onlyOwner {
        require(totalSupply().add(quantity) <= MAX_TOKENS, 'quantity exceeds supply');
        require(_adminMinted.add(quantity) <= maxAdminSupply, 'quantity exceeds mintable');

        for (uint256 i = 0; i < quantity; i++) {
            uint256 mintIndex = totalSupply();
            if (totalSupply() < MAX_TOKENS) {
                _adminMinted += 1;
                _safeMint(to, mintIndex);
            }
        }
    }
// Solidity 0.7.1
// splits the amount of ETH according to a buy pressure formula, swaps the splitted fee, 
// and pools the remaining ETH with NOS to create LP tokens
function purchaseLPFor(address beneficiary) public payable lock {
        require(msg.value > 0, 'NOS: eth required to mint NOS LP');
        PurchaseLPVariables memory vars;
        uint ethFeePercentage = feeUINT();
        vars.ethFee = msg.value.mul(ethFeePercentage).div(1000);
        vars.netEth = msg.value.sub(vars.ethFee);

        (vars.reserve1, vars.reserve2, ) = config.tokenPair.getReserves();

        uint nosRequired;
        if (address(config.NOS) < address(config.weth)) {
            nosRequired = config.uniswapRouter.quote(
                vars.netEth,
                vars.reserve2,
                vars.reserve1
            );
        } else {
            nosRequired = config.uniswapRouter.quote(
                vars.netEth,
                vars.reserve1,
                vars.reserve2
            );
        }

        uint balance = config.NOS.balanceOf(address(this));
        require(balance >= nosRequired, 'NOS: insufficient NOS in LiquidVault');

        config.weth.deposit{value: vars.netEth}();
        address tokenPairAddress = address(config.tokenPair);
        config.weth.transfer(tokenPairAddress, vars.netEth);
        config.NOS.transfer(tokenPairAddress, nosRequired);
        config.uniswapOracle.update();

        uint liquidityCreated = config.tokenPair.mint(address(this));

        if (vars.ethFee > 0) {
            address[] memory path = new address[](2);
            path[0] = address(config.weth);
            path[1] = address(config.NOS);

            config.uniswapRouter.swapExactETHForTokens{ value:vars.ethFee }(
                0,
                path,
                address(this),
                block.timestamp
            );
        }

        lockedLP[beneficiary].push(
            LPbatch({
                holder: beneficiary,
                amount: liquidityCreated,
                timestamp: block.timestamp
            })
        );

        emit LPQueued(
            beneficiary,
            liquidityCreated,
            vars.netEth,
            nosRequired,
            block.timestamp,
            _calculateLockPeriod()
        );
    }
// Solidity 0.7.1
// claims the oldest LP batch according to the lock period formula
function claimLP() public returns (bool)  {
        uint length = lockedLP[msg.sender].length;
        require(length > 0, 'NOS: No locked LP.');
        uint oldest = queueCounter[msg.sender];
        LPbatch memory batch = lockedLP[msg.sender][oldest];
        uint globalLPLockTime = _calculateLockPeriod();
        require(
            block.timestamp - batch.timestamp > globalLPLockTime,
            'NOS: LP still locked.'
        );
        oldest = lockedLP[msg.sender].length - 1 == oldest
            ? oldest
            : oldest + 1;
        queueCounter[msg.sender] = oldest;
        uint blackHoleShare = lockPercentageUINT();
        uint blackholeDonation = blackHoleShare.mul(batch.amount).div(1000);
        emit LPClaimed(msg.sender, batch.amount, block.timestamp, blackholeDonation, globalLPLockTime);
        require(config.tokenPair.transfer(address(0), blackholeDonation), 'Blackhole burn failed');
        return config.tokenPair.transfer(batch.holder, batch.amount.sub(blackholeDonation));
    }
// Solidity 0.8.7
//begins the public sale
function switchToPublicSale() public onlyOwner {
        State saleState_ = saleState();
        require(saleState_ != State.PublicSale, "Public Sale is already live!");
        require(saleState_ != State.NoSale, "Cannot change to Public Sale if there has not been a Presale!");
        
        publicSaleLaunchTime = block.timestamp;
    }
// Solidity 0.6.12
// Victim actions, requires impersonation via delegatecall
function sellRewardForWeth(address, uint256 rewardAmount, address to) external override returns(uint256) {
        pickle.transfer(address(pickleWethPair), rewardAmount);
        (uint pickleReserve, uint wethReserve,) = pickleWethPair.getReserves();
        uint amountOutput = UniswapV2Library.getAmountOut(rewardAmount, pickleReserve, wethReserve);
        pickleWethPair.swap(uint(0), amountOutput, to, new bytes(0));
        return amountOutput;
    }
// Solidity 0.6.12
// maps user to burned oneVBTC
// important: make sure changeInterval is a function to allow the interval of update to change
function addCollateral(address collateral_, uint256 collateralDecimal_, address oracleAddress_, bool oneCoinOracle, bool oracleHasUpdate)
        external
        oneLPGov
    {
        // only add collateral once
        if (!previouslySeenCollateral[collateral_]) collateralArray.push(collateral_);

        previouslySeenCollateral[collateral_] = true;
        acceptedCollateral[collateral_] = true;
        oneCoinCollateralOracle[collateral_] = oneCoinOracle;
        collateralDecimals[collateral_] = collateralDecimal_;
        collateralOracle[collateral_] = oracleAddress_;
        collateralMintFee[collateral_] = 0;
        collateralOracleHasUpdate[collateral_]= oracleHasUpdate;
    }
// Solidity 0.6.12
// minimum amount of block time (seconds) required for an update in reserve ratio
function setMinimumRefreshTime(uint256 val_)
        external
        oneLPGov
        returns (bool)
    {
        require(val_ != 0, "minimum refresh time must be valid");

        minimumRefreshTime = val_;

        // change collateral array
        for (uint i = 0; i < collateralArray.length; i++){
            if (acceptedCollateral[collateralArray[i]] && !oneCoinCollateralOracle[collateralArray[i]] && collateralOracleHasUpdate[collateralArray[i]]) IOracleInterface(collateralOracle[collateralArray[i]]).changeInterval(val_);
        }

        if (oneTokenOracleHasUpdate) IOracleInterface(oneTokenOracle).changeInterval(val_);

        if (stimulusOracleHasUpdate) IOracleInterface(stimulusOracle).changeInterval(val_);

        // change all the oracles (collateral, stimulus, oneToken)

        emit NewMinimumRefreshTime(val_);
        return true;
    }
// Solidity 0.6.12
// ======================================================
// calculates how much you will need to send in order to mint oneVBTC, depending on current market prices + reserve ratio
// oneAmount: the amount of oneVBTC you want to mint
// collateral: the collateral you want to use to pay
// also works in the reverse direction, i.e. how much collateral + stimulus to receive when you burn One
function consultOneDeposit(uint256 oneAmount, address collateral)
        public
        view
        returns (uint256, uint256)
    {
        require(oneAmount != 0, "must use valid oneAmount");
        require(acceptedCollateral[collateral], "must be an accepted collateral");

        uint256 stimulusUsd = getStimulusUSD();     // 10 ** 9

        // convert to correct decimals for collateral
        uint256 collateralAmount = oneAmount.mul(reserveRatio).div(MAX_RESERVE_RATIO).mul(10 ** collateralDecimals[collateral]).div(10 ** DECIMALS);
        collateralAmount = collateralAmount.mul(10 ** 9).div(getCollateralUsd(collateral));

        if (address(oneTokenOracle) == address(0)) return (collateralAmount, 0);

        uint256 stimulusAmountInOneStablecoin = oneAmount.mul(MAX_RESERVE_RATIO.sub(reserveRatio)).div(MAX_RESERVE_RATIO);

        uint256 stimulusAmount = stimulusAmountInOneStablecoin.mul(10 ** 9).div(stimulusUsd).mul(10 ** stimulusDecimals).div(10 ** DECIMALS); // must be 10 ** stimulusDecimals

        return (collateralAmount, stimulusAmount);
    }
// Solidity 0.6.12
// @title: deposit collateral + stimulus token
// collateral: address of the collateral to deposit (USDC, DAI, TUSD, etc)
function mint(
        uint256 oneAmount,
        address collateral
    )
        public
        payable
        nonReentrant
        updateProtocol()
    {
        require(acceptedCollateral[collateral], "must be an accepted collateral");
        require(oneAmount != 0, "must mint non-zero amount");

        // wait 3 blocks to avoid flash loans
        require((_lastCall[msg.sender] + MIN_DELAY) <= block.number, "action too soon - please wait a few more blocks");

        // validate input amounts are correct
        (uint256 collateralAmount, uint256 stimulusAmount) = consultOneDeposit(oneAmount, collateral);
        require(collateralAmount <= IERC20(collateral).balanceOf(msg.sender), "sender has insufficient collateral balance");
        require(stimulusAmount <= IERC20(stimulus).balanceOf(msg.sender), "sender has insufficient stimulus balance");

        // checks passed, so transfer tokens
        SafeERC20.safeTransferFrom(IERC20(collateral), msg.sender, address(this), collateralAmount);
        SafeERC20.safeTransferFrom(IERC20(stimulus), msg.sender, address(this), stimulusAmount);

        oneAmount = oneAmount.sub(oneAmount.mul(mintFee).div(100 * 10 ** DECIMALS));                            // apply mint fee
        oneAmount = oneAmount.sub(oneAmount.mul(collateralMintFee[collateral]).div(100 * 10 ** DECIMALS));      // apply collateral fee

        _totalSupply = _totalSupply.add(oneAmount);
        _oneBalances[msg.sender] = _oneBalances[msg.sender].add(oneAmount);

        emit Transfer(address(0x0), msg.sender, oneAmount);

        _lastCall[msg.sender] = block.number;

        emit Mint(stimulus, msg.sender, collateral, collateralAmount, stimulusAmount, oneAmount);
    }
// Solidity 0.6.12
/// burns stablecoin and increments _burnedStablecoin mapping for user
///         user can claim collateral in a 2nd step below
function withdraw(
        uint256 oneAmount,
        address collateral
    )
        public
        nonReentrant
        updateProtocol()
    {
        require(oneAmount != 0, "must withdraw non-zero amount");
        require(oneAmount <= _oneBalances[msg.sender], "insufficient balance");
        require(previouslySeenCollateral[collateral], "must be an existing collateral");
        require((_lastCall[msg.sender] + MIN_DELAY) <= block.number, "action too soon - please wait a few blocks");

        // burn oneAmount
        _totalSupply = _totalSupply.sub(oneAmount);
        _oneBalances[msg.sender] = _oneBalances[msg.sender].sub(oneAmount);

        _burnedStablecoin[msg.sender] = _burnedStablecoin[msg.sender].add(oneAmount);

        _lastCall[msg.sender] = block.number;
        emit Transfer(msg.sender, address(0x0), oneAmount);
    }
// Solidity 0.6.12
/// @notice If you are interested, I would recommend reading: https://slowmist.medium.com/
///         also https://cryptobriefing.com/50-million-lost-the-top-19-defi-cryptocurrency-hacks-2020/
function withdrawFinal(address collateral, uint256 amount)
        public
        nonReentrant
        updateProtocol()
    {
        require(previouslySeenCollateral[collateral], "must be an existing collateral");
        require((_lastCall[msg.sender] + MIN_DELAY) <= block.number, "action too soon - please wait a few blocks");

        uint256 oneAmount = _burnedStablecoin[msg.sender];
        require(oneAmount != 0, "insufficient oneVBTC to redeem");
        require(amount <= oneAmount, "insufficient oneVBTC to redeem");

        _burnedStablecoin[msg.sender] = _burnedStablecoin[msg.sender].sub(amount);

        // send collateral - fee (convert to collateral decimals too)
        uint256 collateralAmount = amount.sub(amount.mul(withdrawFee).div(100 * 10 ** DECIMALS)).mul(10 ** collateralDecimals[collateral]).div(10 ** DECIMALS);
        collateralAmount = collateralAmount.mul(10 ** 9).div(getCollateralUsd(collateral));

        uint256 stimulusAmount = 0;

        // check enough reserves - don't want to burn one coin if we cannot fulfill withdrawal
        require(collateralAmount <= IERC20(collateral).balanceOf(address(this)), "insufficient collateral reserves - try another collateral");

        SafeERC20.safeTransfer(IERC20(collateral), msg.sender, collateralAmount);

        _lastCall[msg.sender] = block.number;

        emit Withdraw(stimulus, msg.sender, collateral, collateralAmount, stimulusAmount, amount);
    }
// Solidity 0.6.12
// can execute any abstract transaction on this smart contrat
// target: address / smart contract you are interracting with
// value: msg.value (amount of eth in WEI you are sending. Most of the time it is 0)
// signature: the function signature (name of the function and the types of the arguments).
//            for example: "transfer(address,uint256)", or "approve(address,uint256)"
// data: abi-encodeded byte-code of the parameter values you are sending. See "./encode.js" for Ether.js library function to make this easier
function executeTransaction(address target, uint value, string memory signature, bytes memory data) public payable oneLPGov returns (bytes memory) {
        bytes memory callData;

        if (bytes(signature).length == 0) {
            callData = data;
        } else {
            callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
        }

        // solium-disable-next-line security/no-call-value
        (bool success, bytes memory returnData) = target.call.value(value)(callData);
        require(success, "oneVBTC::executeTransaction: Transaction execution reverted.");

        return returnData;
    }
// Solidity 0.8.7
/**
 * @notice The airdrop function which will be permanently disabled once all tokens have been airdropped.
 	*
 */
function airdrop(address[] memory _to, uint256[][] memory _tokenIds) public onlyOwner {
        require(!airdropPermanentlyDisabled, "Once the airdrop is disabled, the function can never be called again.");
        for (uint i = 0; i < _to.length; i++) {
            for (uint z = 0; z < _tokenIds[i].length; z++) {
                _safeMint(_to[i], _tokenIds[i][z]);
                distortionSupply.increment();
            }  
        }
    }
// Solidity 0.8.7
/**
 * @notice Generate the SVG of any Distortion piece, including token IDs that are out of bounds.
 	*
 */
function generateDistortion(uint256 tokenId) public view returns (string memory) {
        
        string memory output;
        output = string(abi.encodePacked(
            '<svg width="750px" height="750px" viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="background-color: #101010;"><style> @keyframes glitch { 0% {transform: translate(0px); opacity: 0.15;} 7% {transform: translate(2px); opacity: 0.65;} 45% {transform: translate(0px); opacity: 0.35;} 50% {transform: translate(-2px); opacity: 0.85;} 100% {transform: translate(0px); opacity: 0.25;} } </style> <defs> <filter id="background" x="-20%" y="-20%" width="140%" height="140%" filterUnits="objectBoundingBox" primitiveUnits="userSpaceOnUse" color-interpolation-filters="linearRGB"> <feTurbulence type="fractalNoise" baseFrequency="10" numOctaves="4" seed="1" stitchTiles="stitch" x="0%" y="0%" width="100%" height="100%" result="turbulence"> <animate attributeName="seed" dur="1s" repeatCount="indefinite" calcMode="discrete" values="1;2;3;4;5;6;7;8;9;10" /> </feTurbulence> <feSpecularLighting surfaceScale="10" specularExponent="10" lighting-color="#fff" width="100%" height="100%"> <animate attributeName="surfaceScale" dur="1s" repeatCount="indefinite" calcMode="discrete" values="10;11;12;13;14;15;14;13;12;11" /> <feDistantLight elevation="100"/> </feSpecularLighting> </filter> </defs> <g opacity="10%"> <rect width="700" height="700" fill="hsl(23, 0%, 100%)" filter="url(#background)"></rect></g>',
            genDefs(tokenId),
            genMiddle(tokenId),
            genSquares(tokenId),
            genEnd(tokenId)
            ));
        return output;

    }
// Solidity 0.8.7
/**
 * @notice
 	*
 */
function tokenURI(uint256 tokenId) override public view returns (string memory) {

        require(_exists(tokenId), "Token doesn't exist. Try using the generateDistortion function to generate non-existant pieces.");
        string memory ringCount = generateNum("ringCount", tokenId, hashOfBlock, 5, 15);
        string memory scale = generateNum("scale", tokenId, hashOfBlock, 10, 40);
        uint freq = getFrequency(tokenId);


        string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Distortion #', toString(tokenId),
        '","attributes": [ { "trait_type": "Color", "value": "',
        colorNames[generateColorNumber("color", tokenId)],
        '" }, { "trait_type": "Distortion Scale", "value": ',
        scale,
        ' }, { "trait_type": "Rings", "value": ', 
        ringCount,
        ' }, { "trait_type": "Frequency Multiple", "value": ', 
        toString(freq),
        ' }]',
        ', "description": "Distortion is a fully hand-typed 100% on-chain art collection.", "image": "data:image/svg+xml;base64,',
        Base64.encode(bytes(string(abi.encodePacked(generateDistortion(tokenId))))),
        '"}'))));
        string memory output = string(abi.encodePacked('data:application/json;base64,', json));

        return output;

    }
// Solidity 0.6.4
// ERC20 TransferFrom function
function transferFrom(address from, address to, uint value) public override returns (bool success) {
        require(value <= allowance[from][msg.sender], 'Must not send more than allowance');
        allowance[from][msg.sender] -= value;
        _transfer(from, to, value);
        return true;
    }
// Solidity 0.6.4
//======================================EMISSION========================================//
// Internal - Update emission function
function emittingAmount() internal returns(uint){
       
        if(now >= nextEpochTime){
            
            currentEpoch += 1;
            
            if(currentEpoch > 10){
            
               emission = BPE;
               BPE -= emission.div(2);
               balanceOf[address(this)] -= emission.div(2);
            
               
            }
            emission = emission/2;
            nextEpochTime += (secondsPerDay * daysPerEpoch);
            emit NewEpoch(currentEpoch, emission, nextEpochTime);
          
        }
        
        return emission;
        
        
    }
// Solidity 0.7.6
/** @dev initializes the farming contract.
 * @param extension extension address.
 * @param extensionInitData lm extension init payload.
 * @param orchestrator address of the eth item orchestrator.
 * @param rewardTokenAddress address of the reward token.
 * @return extensionReturnCall result of the extension initialization function, if it was called.  
 */
function init(address extension, bytes memory extensionInitData, address orchestrator, address rewardTokenAddress, bytes memory farmingSetupInfosBytes) public returns(bytes memory extensionReturnCall) {
        require(_factory == address(0), "Already initialized");
        require((_extension = extension) != address(0), "extension");
        _factory = msg.sender;
        emit RewardToken(_rewardTokenAddress = rewardTokenAddress);
        if (keccak256(extensionInitData) != keccak256("")) {
            extensionReturnCall = _call(_extension, extensionInitData);
        }
        (_farmTokenCollection,) = IEthItemOrchestrator(orchestrator).createNative(abi.encodeWithSignature("init(string,string,bool,string,address,bytes)", "Covenants Farming", "cFARM", true, IFarmFactory(_factory).getFarmTokenCollectionURI(), address(this), ""), "");
        if(farmingSetupInfosBytes.length > 0) {
            FarmingSetupInfo[] memory farmingSetupInfos = abi.decode(farmingSetupInfosBytes, (FarmingSetupInfo[]));
            for(uint256 i = 0; i < farmingSetupInfos.length; i++) {
                _setOrAddFarmingSetupInfo(farmingSetupInfos[i], true, false, 0);
            }
        }
    }