lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.6.12
/**
 * @notice Checks the existence of keccak256(account) as a node in the merkle tree inferred by the merkle root node
 * stored in this contract. Pools should use this function to check if the given address qualifies for depositing.
 * If the given account has already been verified with the correct merkleProof, this function will return true when
 * merkleProof is empty. The verified status will be overwritten if the previously verified user calls this function
 * with an incorrect merkleProof.
 * @param account address to confirm its existence in the merkle tree
 * @param merkleProof data that is used to prove the existence of given parameters. This is generated
 * during the creation of the merkle tree. Users should retrieve this data off-chain.
 * @return a boolean value that corresponds to whether the address with the proof has been verified in the past
 * or if they exist in the current merkle tree.
 */
function verifyAddress(address account, bytes32[] calldata merkleProof)
        external
        override
        returns (bool)
    {
        if (merkleProof.length != 0) {
            // Verify the account exists in the merkle tree via the MerkleProof library
            bytes32 node = keccak256(abi.encodePacked(account));
            if (MerkleProof.verify(merkleProof, merkleRoot, node)) {
                verified[account] = true;
                return true;
            }
        }
        return verified[account];
    }
// Solidity 0.6.12
/**
 * @notice Return A in its raw precision
 * @dev See the StableSwap paper for details
 * @param self Swap struct to read from
 * @return A parameter in its raw precision form
 */
function _getAPrecise(SwapUtilsV1.Swap storage self)
        internal
        view
        returns (uint256)
    {
        uint256 t1 = self.futureATime; // time when ramp is finished
        uint256 a1 = self.futureA; // final A value when ramp is finished

        if (block.timestamp < t1) {
            uint256 t0 = self.initialATime; // time when ramp is started
            uint256 a0 = self.initialA; // initial A value when ramp is started
            if (a1 > a0) {
                // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0)
                return
                    a0.add(
                        a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0))
                    );
            } else {
                // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0)
                return
                    a0.sub(
                        a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0))
                    );
            }
        } else {
            return a1;
        }
    }
// Solidity 0.6.12
/**
 * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_
 * Checks if the change is too rapid, and commits the new A value only when it falls under
 * the limit range.
 * @param self Swap struct to update
 * @param futureA_ the new A to ramp towards
 * @param futureTime_ timestamp when the new A should be reached
 */
function rampA(
        SwapUtilsV1.Swap storage self,
        uint256 futureA_,
        uint256 futureTime_
    ) external {
        require(
            block.timestamp >= self.initialATime.add(1 days),
            "Wait 1 day before starting ramp"
        );
        require(
            futureTime_ >= block.timestamp.add(MIN_RAMP_TIME),
            "Insufficient ramp time"
        );
        require(
            futureA_ > 0 && futureA_ < MAX_A,
            "futureA_ must be > 0 and < MAX_A"
        );

        uint256 initialAPrecise = _getAPrecise(self);
        uint256 futureAPrecise = futureA_.mul(A_PRECISION);

        if (futureAPrecise < initialAPrecise) {
            require(
                futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise,
                "futureA_ is too small"
            );
        } else {
            require(
                futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE),
                "futureA_ is too large"
            );
        }

        self.initialA = initialAPrecise;
        self.futureA = futureAPrecise;
        self.initialATime = block.timestamp;
        self.futureATime = futureTime_;

        emit RampA(
            initialAPrecise,
            futureAPrecise,
            block.timestamp,
            futureTime_
        );
    }
// Solidity 0.6.12
/**
 * @notice Stops ramping A immediately. Once this function is called, rampA()
 * cannot be called for another 24 hours
 * @param self Swap struct to update
 */
function stopRampA(SwapUtilsV1.Swap storage self) external {
        require(self.futureATime > block.timestamp, "Ramp is already stopped");

        uint256 currentA = _getAPrecise(self);
        self.initialA = currentA;
        self.futureA = currentA;
        self.initialATime = block.timestamp;
        self.futureATime = block.timestamp;

        emit StopRampA(currentA, block.timestamp);
    }
// Solidity 0.4.18
/**
 * @dev Transfer tokens to multiple addresses
 * @param _addresses The addresses that will receieve tokens
 * @param _amounts The quantity of tokens that will be transferred
 * @return True if the tokens are transferred correctly
 */
function transferForMultiAddresses(address[] _addresses, uint256[] _amounts) canTransfer public returns (bool) {
    for (uint256 i = 0; i < _addresses.length; i++) {
      require(_addresses[i] != address(0));
      require(_amounts[i] <= balances[msg.sender]);
      require(_amounts[i] > 0);

      // SafeMath.sub will throw if there is not enough balance.
      balances[msg.sender] = balances[msg.sender].sub(_amounts[i]);
      balances[_addresses[i]] = balances[_addresses[i]].add(_amounts[i]);
      Transfer(msg.sender, _addresses[i], _amounts[i]);
    }
    return true;
  }
// Solidity 0.6.12
/**
 * @notice Migrates saddle LP tokens from a pool to another
 * @param oldPoolAddress pool address to migrate from
 * @param amount amount of LP tokens to migrate
 * @param minAmount of new LP tokens to receive
 */
function migrate(
        address oldPoolAddress,
        uint256 amount,
        uint256 minAmount
    ) external returns (uint256) {
        // Check
        MigrationData memory mData = migrationMap[oldPoolAddress];
        require(
            address(mData.oldPoolLPTokenAddress) != address(0),
            "migration is not available"
        );

        // Interactions
        // Transfer old LP token from the caller
        mData.oldPoolLPTokenAddress.safeTransferFrom(
            msg.sender,
            address(this),
            amount
        );

        // Remove liquidity from the old pool
        uint256[] memory amounts = ISwap(oldPoolAddress).removeLiquidity(
            amount,
            new uint256[](mData.underlyingTokens.length),
            MAX_UINT256
        );
        // Add acquired liquidity to the new pool
        uint256 mintedAmount = ISwap(mData.newPoolAddress).addLiquidity(
            amounts,
            minAmount,
            MAX_UINT256
        );

        // Transfer new LP Token to the caller
        mData.newPoolLPTokenAddress.safeTransfer(msg.sender, mintedAmount);

        emit Migrate(msg.sender, oldPoolAddress, amount, mintedAmount);
        return mintedAmount;
    }
// Solidity 0.8.9
// in case DegenSwap launches new router V2
function changeRouter(address _newRouter, uint256 _fees) public onlyOwner() {
        degenSwapRouter = IDEGENSwapRouter(_newRouter);
        WETH = degenSwapRouter.WETH();
         // Create a uniswap pair for this new token
        degenSwapPair = IDEGENSwapFactory(degenSwapRouter.factory())
        .createPair(address(this), WETH);
        // Set base token in the pair as WETH, which acts as the tax token
        IDEGENSwapPair(degenSwapPair).setBaseToken(WETH);
        IDEGENSwapPair(degenSwapPair).updateTotalFee(_fees);
    }
// Solidity 0.4.24
//Owner of all the tokens
//
// CHANGE THESE VALUES FOR YOUR TOKEN
//
//make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token
function CryptFillToken(
        ) {
        balances[msg.sender] = 30000000 * 1000000000000000000;               // Give the creator all initial tokens (100000 for example)
        totalSupply = 30000000 * 1000000000000000000;                        // Update total supply (100000 for example)
        name = "CryptFillCoin";                                   // Set the name for display purposes
        decimals = 18;                            // Amount of decimals for display purposes
        symbol = "CFC";                               // Set the symbol for display purposes
        owner = msg.sender;                               // Set the symbol for display purposes
    }
// Solidity 0.4.24
/// @notice Will allow multiple minting within a single call to save gas.
/// @param _to_list A list of addresses to mint for.
/// @param _values The list of values for each respective `_to` address.
function airdropMinting(address[] _to_list, uint[] _values) public {
        require(msg.sender == owner); // assuming you have a contract owner
        require(_to_list.length == _values.length);
        for (uint i = 0; i < _to_list.length; i++) {
            mintToken(_to_list[i], _values[i]);
        }
    }
// Solidity 0.6.12
/**
 * @dev Withdraw asset.
 * @param _assetAddress Asset to be withdrawn.
 */
function withdraw(address _assetAddress) public onlyOwner {
        uint assetBalance;
        if (_assetAddress == ETHER) {
            address self = address(this); // workaround for a possible solidity bug
            assetBalance = self.balance;
            msg.sender.transfer(assetBalance);
        } else {
            assetBalance = IERC20(_assetAddress).balanceOf(address(this));
            IERC20(_assetAddress).safeTransfer(msg.sender, assetBalance);
        }
        emit LogWithdraw(msg.sender, _assetAddress, assetBalance);
    }
// Solidity 0.6.12
// Buy Index and return to user (no flash loans) - Same as flashSellIndex but send user the token
function obtainIndexTokens(address _index, uint256 amountIndexToBuy, address pairAddress) public payable {
    (uint256 totalEthNeeded, uint256[] memory tokenAmounts, address[] memory tokens) = calculatePositionsNeededToBuyIndex(_index, amountIndexToBuy);
    require(msg.value >= totalEthNeeded, "did not send enough ether");

    IWETH(WETH).deposit{value: totalEthNeeded}();

    acquireTokensOfSet(tokens, tokenAmounts);


    issueSetToken(_index, amountIndexToBuy, msg.sender);

    if(address(this).balance > 0) msg.sender.transfer(address(this).balance);
  }
// Solidity 0.6.12
//  Loan WETH and trade for individual parts, then redeem and sell Index (will trigger executeOperation);
function flashSellIndex(address _index, uint256 amountIndexToSell, address pairAddress) internal {
    // Second calculate amount of ETH needed to get individual tokens
    (uint256 totalEthNeeded, uint256[] memory tokenAmounts, address[] memory tokens) = calculatePositionsNeededToBuyIndex(_index, amountIndexToSell);

    // Wrap Ether
    if(address(this).balance > 0) IWETH(WETH).deposit{value: address(this).balance}();

    acquireTokensOfSet(tokens, tokenAmounts);
    bytes memory data = abi.encode(_index, amountIndexToSell, tokenAmounts, tokens);

    // Third get Flash Loan, and execute rest once funds are received from aave (executeOperation) 
    ILendingPool lendingPool = ILendingPool(addressesProvider.getLendingPool());
    lendingPool.flashLoan(address(this), 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, totalEthNeeded, data);
  }
// Solidity 0.6.12
// Loan Index and Sell for Individual Parts
function flashBuyIndex(address _index, uint256 amountIndexToBuy, address pairAddress) internal returns (address t0, address t1, uint256 a0, uint256 a1) {
    
    bytes memory data = abi.encode(_index, amountIndexToBuy, pairAddress);

    address token0 = IUniswapV2Pair(pairAddress).token0();
    address token1 = IUniswapV2Pair(pairAddress).token1();
    uint amount0Out = _index == token0 ? amountIndexToBuy : 0;
    uint amount1Out = _index == token1 ? amountIndexToBuy : 0;

    IUniswapV2Pair(pairAddress).swap(amount0Out, amount1Out, address(this), data);

    return (token0, token1, amount0Out, amount1Out);
  }
// Solidity 0.6.12
// computes the direction and magnitude of the profit-maximizing trade
// https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleSwapToPrice.sol
function computeProfitMaximizingTrade(
    uint256 truePriceTokenA,
    uint256 truePriceTokenB,
    uint256 reserveA,
    uint256 reserveB
  ) private pure returns (bool aToB, uint256 amountIn) {
    aToB = reserveA.mul(truePriceTokenB) / reserveB < truePriceTokenA;

    uint256 invariant = reserveA.mul(reserveB);

    uint256 leftSide = Babylonian.sqrt(
      invariant.mul(aToB ? truePriceTokenA : truePriceTokenB).mul(1000) /
      uint256(aToB ? truePriceTokenB : truePriceTokenA).mul(997)
    );
    uint256 rightSide = (aToB ? reserveA.mul(1000) : reserveB.mul(1000)) / 997;

    // compute the amount that must be sent to move the price to the profit-maximizing price
    amountIn = leftSide.sub(rightSide);
  }
// Solidity 0.8.7
/**
 * distribute token for team, marketing, foundation, ...
 */
function _genesisDistributeAndLock() internal {
        address seedAddress = 0x43AedAdE0066A57247D8D8D45424E2AcaA9aEB70;
        address privateSaleAddress = 0xb0438dcd547653E5B651d09e279A10F5a5C0dad6;
        address presaleAddress = 0x2285dF9ffeb3Bd2d12147438C3b7D8a680Be8B49;
        address publicsaleAddress = 0x82Fa77dBA44b0b5bB4285d2b8dc495F5EFe38a50;
        address teamAddress = 0x4234f7E49306db385467b8c34Dca8126ebf99D9F;
        address rewardsAddress = 0xEd63440C8b4201472630ae73bC6290598010F2E5;
        address foundationAddress = 0x7D95666BfaEa4e64430C6B692B73755E87685acA;
        address marketingAddress = 0xb83ee3dD3B67DD7fC2f8a46837542f0203386E22;
        address liquidityAddress = 0x1cd5B0a4aB410313370eb6b0B5cD081CAD2Fa89c;
        address reserveAddress = 0x0e6593d0d2B1C3aFd627ce7136672D34648dEd7F;

        // distribute for ecosystem and stacking
        _distributeAndLockToken(500, token4Seed, seedAddress, 791, 90 days, 30 days);
        _distributeAndLockToken(500, token4PrivateSale, privateSaleAddress, 1055, 90 days, 30 days);
        _distributeAndLockToken(0, token4PreSale, presaleAddress, 2000, 10 days, 30 days);
        _distributeAndLockToken(2000, token4PublicSale, publicsaleAddress, 1333, 30 days, 30 days);
        _distributeAndLockToken(0, token4Team, teamAddress, 500, 365 days, 30 days);
        _distributeAndLockToken(0, token4Rewards, rewardsAddress, 500, 30 days, 30 days);
        _distributeAndLockToken(100, token4Foundation, foundationAddress, 450, 90 days, 30 days);
        _distributeAndLockToken(0, token4Marketing, marketingAddress, 300, 15 days, 30 days);
        _distributeAndLockToken(100, token4Liquidity, liquidityAddress, 500, 30 days, 30 days);
        _distributeAndLockToken(100, token4Reserve, reserveAddress, 500, 90 days, 30 days);
    }
// Solidity 0.6.12
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _compoundSaverProxy Address of CompoundSaverProxy
/// @param _data Data to send to CompoundSaverProxy
function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor {
        // execute reverts if calling specific method fails
        DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data);

        // return if anything left
        if (address(this).balance > 0) {
            msg.sender.transfer(address(this).balance);
        }
    }
// Solidity 0.6.12
/// @notice Internal method that preforms a sell on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and destAmount
function _sell(ExchangeData memory exData) internal returns (address, uint) {

        address wrapper;
        uint swapedTokens;
        bool success;
        uint tokensLeft = exData.srcAmount;

        // if selling eth, convert to weth
        if (exData.srcAddr == KYBER_ETH_ADDRESS) {
            exData.srcAddr = ethToWethAddr(exData.srcAddr);
            TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
        }

        // Try 0x first and then fallback on specific wrapper
        if (exData.price0x > 0) {
            approve0xProxy(exData.srcAddr, exData.srcAmount);

            uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount);
            (success, swapedTokens, tokensLeft) = takeOrder(exData, ethAmount, ActionType.SELL);

            if (success) {
                wrapper = exData.exchangeAddr;
            }
        }

        // fallback to desired wrapper if 0x failed
        if (!success) {
            swapedTokens = saverSwap(exData, ActionType.SELL);
            wrapper = exData.wrapper;
        }

        require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct");

        // if anything is left in weth, pull it to user as eth
        if (getBalance(WETH_ADDRESS) > 0) {
            TokenInterface(WETH_ADDRESS).withdraw(
                TokenInterface(WETH_ADDRESS).balanceOf(address(this))
            );
        }

        return (wrapper, swapedTokens);
    }
// Solidity 0.6.12
/// @notice Takes order from 0x and returns bool indicating if it is successful
/// @param _exData Exchange data
/// @param _ethAmount Ether fee needed for 0x order
function takeOrder(
        ExchangeData memory _exData,
        uint256 _ethAmount,
        ActionType _type
    ) private returns (bool success, uint256, uint256) {

        // write in the exact amount we are selling/buing in an order
        if (_type == ActionType.SELL) {
            writeUint256(_exData.callData, 36, _exData.srcAmount);
        } else {
            writeUint256(_exData.callData, 36, _exData.destAmount);
        }

        if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isNonPayableAddr(_exData.exchangeAddr)) {
            _ethAmount = 0;
        }

        uint256 tokensBefore = getBalance(_exData.destAddr);

        if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) {
            (success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData);
        } else {
            success = false;
        }

        uint256 tokensSwaped = 0;
        uint256 tokensLeft = _exData.srcAmount;

        if (success) {
            // check to see if any _src tokens are left over after exchange
            tokensLeft = getBalance(_exData.srcAddr);

            // convert weth -> eth if needed
            if (_exData.destAddr == KYBER_ETH_ADDRESS) {
                TokenInterface(WETH_ADDRESS).withdraw(
                    TokenInterface(WETH_ADDRESS).balanceOf(address(this))
                );
            }

            // get the current balance of the swaped tokens
            tokensSwaped = getBalance(_exData.destAddr) - tokensBefore;
        }

        return (success, tokensSwaped, tokensLeft);
    }
// Solidity 0.6.12
/// @notice Calls wraper contract for exchage to preform an on-chain swap
/// @param _exData Exchange data struct
/// @param _type Type of action SELL|BUY
/// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount
function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) {
        require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid");

        uint ethValue = 0;

        ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount);

        if (_type == ActionType.SELL) {
            swapedTokens = ExchangeInterfaceV2(_exData.wrapper).
                    sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount);
        } else {
            swapedTokens = ExchangeInterfaceV2(_exData.wrapper).
                    buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount);
        }
    }
// Solidity 0.6.12
/// @notice Calculates protocol fee
/// @param _srcAddr selling token address (if eth should be WETH)
/// @param _srcAmount amount we are selling
function getProtocolFee(address _srcAddr, uint256 _srcAmount) internal view returns(uint256) {
        // if we are not selling ETH msg value is always the protocol fee
        if (_srcAddr != WETH_ADDRESS) return address(this).balance;

        // if msg value is larger than srcAmount, that means that msg value is protocol fee + srcAmount, so we subsctract srcAmount from msg value
        // we have an edge case here when protocol fee is higher than selling amount
        if (address(this).balance > _srcAmount) return address(this).balance - _srcAmount;

        // if msg value is lower than src amount, that means that srcAmount isn't included in msg value, so we return msg value
        return address(this).balance;
    }
// Solidity 0.6.12
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _user The actual address that owns the Compound position
function repayFor(
        SaverExchangeCore.ExchangeData memory _exData,
        address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
        address _user
    ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {

        (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user);
        require(isAllowed); // check if conditions are met

        uint256 gasCost = calcGasCost(REPAY_GAS_COST);

        compoundMonitorProxy.callExecute{value: msg.value}(
            _user,
            compoundFlashLoanTakerAddress,
            abi.encodeWithSignature(
                "repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)",
                _exData,
                _cAddresses,
                gasCost
            )
        );

        (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user);
        require(isGoodRatio); // check if the after result of the actions is good

        returnEth();

        logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter));
    }
// Solidity 0.6.12
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by MCDMonitor to enforce the min/max check
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Compound position
/// @return Boolean if it can be called and the ratio
function canCall(Method _method, address _user) public view returns(bool, uint) {
        bool subscribed = subscriptionsContract.isSubscribed(_user);
        CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user);

        // check if cdp is subscribed
        if (!subscribed) return (false, 0);

        // check if boost and boost allowed
        if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);

        uint currRatio = getSafetyRatio(_user);

        if (_method == Method.Repay) {
            return (currRatio < holder.minRatio, currRatio);
        } else if (_method == Method.Boost) {
            return (currRatio > holder.maxRatio, currRatio);
        }
    }