lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.6.7
// Leverages until we're supplying <x> amount
// 1. Redeem <x> USDC
// 2. Repay <x> USDC
function leverageUntil(uint256 _supplyAmount) public onlyKeepers {
        // 1. Borrow out <X> USDC
        // 2. Supply <X> USDC

        uint256 leverage = getMaxLeverage();
        uint256 unleveragedSupply = getSuppliedUnleveraged();
        require(
            _supplyAmount >= unleveragedSupply &&
                _supplyAmount <= unleveragedSupply.mul(leverage).div(1e18),
            "!leverage"
        );

        // Since we're only leveraging one asset
        // Supplied = borrowed
        uint256 _borrowAndSupply;
        uint256 supplied = getSupplied();
        while (supplied < _supplyAmount) {
            _borrowAndSupply = getBorrowable();

            if (supplied.add(_borrowAndSupply) > _supplyAmount) {
                _borrowAndSupply = _supplyAmount.sub(supplied);
            }

            ICToken(cusdc).borrow(_borrowAndSupply);
            deposit();

            supplied = supplied.add(_borrowAndSupply);
        }
    }
// Solidity 0.4.24
/// @dev Internal function to actually purchase the tokens.
function deposit() payable public  {

        uint256 _incomingEthereum = msg.value;
        address _fundingSource = msg.sender;

        // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
        profitPerShare_ += (_incomingEthereum * magnitude / tokenSupply_);


        // fire event
        emit onDeposit(_fundingSource, _incomingEthereum, now);

    }
// Solidity 0.4.24
/// @dev Debits address by an amount or sets to zero
function debit(address _customerAddress, uint256 amount) onlyWhitelisted external returns (uint256){

        //No money movement; usually a lost wager
        vault[_customerAddress] = Math.max256(0, vault[_customerAddress].sub(amount));

        totalCustomerCredit = totalCustomerCredit.sub(amount);

        //Stats
        stats[_customerAddress].debit = stats[_customerAddress].debit.add(amount);
        stats[_customerAddress].xDebit += 1;

        emit onWithdraw(_customerAddress, amount, now);

        return vault[_customerAddress];
    }
// Solidity 0.4.24
/// @dev Withraws balance for address; returns amount sent
function withdraw(address _customerAddress) onlyWhitelisted external returns (uint256){
        require(vault[_customerAddress] > 0);

        uint256 amount = vault[_customerAddress];

        vault[_customerAddress] = 0;
        totalCustomerCredit = totalCustomerCredit.sub(amount);

        _customerAddress.transfer(amount);

        //Stats
        stats[_customerAddress].withdrawn = stats[_customerAddress].withdrawn.add(amount);
        stats[_customerAddress].xWithdrawn += 1;

        emit onWithdraw(_customerAddress, amount, now);
    }
// Solidity 0.4.24
/**
 * @dev The bridge to the launch ecosystem. Community has to participate to dump divs
 * Should
 */
function fundP6(uint256 amount) internal {
        uint256 fee = amount.mul(p6Fee).div(100);

        p6Outbound = p6Outbound.add(fee);

        //GO P6 GO!!!
        if (p6Outbound >= outboundThreshold){
            fee = p6Outbound;
            p6Outbound = 0;
            p6.buyFor.value(fee)(owner);
            emit onAirdrop(address(p6), fee, now);
        }

    }
// Solidity 0.4.8
//
// ======= interface methods =======
//
//accept payments here
function ()
    payable
    noReentrancy
    {
        State state = currentState();
        if (state == State.PRESALE_RUNNING) {
            receiveFunds();
        } else if (state == State.REFUND_RUNNING) {
            // any entring call in Refund Phase will cause full refund
            sendRefund();
        } else {
            throw;
        }
    }
// Solidity 0.4.8
//
// ======= implementation methods =======
//
function sendRefund() private tokenHoldersOnly {
        // load balance to refund plus amount currently sent
        var amount_to_refund = balances[msg.sender] + msg.value;
        // reset balance
        balances[msg.sender] = 0;
        // send refund back to sender
        if (!msg.sender.send(amount_to_refund)) throw;
    }
// Solidity 0.6.12
// migrate stakers from previous contract to this one. can only be called before farm starts.
function addStakes(uint _pid, address[] calldata stakers, uint256[] calldata amounts) external onlyOwner {
        require(block.number < startBlock, "addStakes: farm started.");
        for(uint i=0; i<stakers.length; i++){
            UserInfo storage user = userInfo[_pid][stakers[i]];
            PoolInfo storage pool = poolInfo[_pid];
            user.amount = user.amount.add(amounts[i]);
            pool.supply = pool.supply.add(amounts[i]);
            pool.lpToken.safeTransferFrom(address(msg.sender), address(this), amounts[i]);
        }       
    }
// Solidity 0.6.12
/**
 * @dev Allows for approvals to be made via secp256k1 signatures.
 * @param owner The owner of the funds
 * @param spender The spender
 * @param value The amount
 * @param deadline The deadline timestamp, type(uint256).max for max deadline
 * @param v Signature param
 * @param s Signature param
 * @param r Signature param
 */
function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public {
        require(block.timestamp <= deadline);

        uint256 ownerNonce = _nonces[owner];
        bytes32 permitDataDigest =
            keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, ownerNonce, deadline));
        bytes32 digest =
            keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR(), permitDataDigest));

        require(owner == ecrecover(digest, v, r, s));

        _nonces[owner] = ownerNonce.add(1);

        _allowances[owner][spender] = value;
        emit Approval(owner, spender, value);
    }
// Solidity 0.8.4
//New Pancakeswap router version?
//No problem, just change it!
function setRouterAddress(address newRouter) external onlyOwner() {
      IUniswapV2Router02 _uniswapV2newRouter = IUniswapV2Router02(newRouter);//v2 router --> 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
      // Create a pancakeswap pair for this new token 
      uniswapV2Pair = IUniswapV2Factory(_uniswapV2newRouter.factory())
            .createPair(address(this), _uniswapV2newRouter.WETH());

      // set the rest of the contract variables
      uniswapV2Router = _uniswapV2newRouter;
      
    }
// Solidity 0.5.14
/**
 * Update token info for withdraw. The interest will be withdrawn with higher priority.
 */
function withdraw(TokenInfo storage self, uint256 amount, uint256 accruedRate, uint256 _block) public {
        newDepositCheckpoint(self, accruedRate, _block);
        if (self.depositInterest >= amount) {
            self.depositInterest = self.depositInterest.sub(amount);
        } else if (self.depositPrincipal.add(self.depositInterest) >= amount) {
            self.depositPrincipal = self.depositPrincipal.sub(amount.sub(self.depositInterest));
            self.depositInterest = 0;
        } else {
            self.depositPrincipal = 0;
            self.depositInterest = 0;
        }
    }
// Solidity 0.5.14
/**
 * @dev Sets the given bit in the bitmap value
 * @param _bitmap Bitmap value to update the bit in
 * @param _index Index range from 0 to 127
 * @return Returns the updated bitmap value
 */
function setBit(uint128 _bitmap, uint8 _index) internal pure returns (uint128) {
        // Suppose `_bitmap` is in bit value:
        // 0001 0100 = represents third(_index == 2) and fifth(_index == 4) bit is set

        // Bit not set, hence, set the bit
        if( ! isBitSet(_bitmap, _index)) {
            // Suppose `_index` is = 3 = 4th bit
            // mask = 0000 1000 = Left shift to create mask to find 4rd bit status
            uint128 mask = uint128(1) << _index;

            // Setting the corrospending bit in _bitmap
            // Performing OR (|) operation
            // 0001 0100 (_bitmap)
            // 0000 1000 (mask)
            // -------------------
            // 0001 1100 (result)
            return _bitmap | mask;
        }

        // Bit already set, just return without any change
        return _bitmap;
    }
// Solidity 0.5.14
/**
 * @dev Returns true if the corrosponding bit set in the bitmap
 * @param _bitmap Bitmap value to check
 * @param _index Index to check. Index range from 0 to 127
 * @return Returns true if bit is set, false otherwise
 */
function isBitSet(uint128 _bitmap, uint8 _index) internal pure returns (bool) {
        require(_index < 128, "Index out of range for bit operation");
        // Suppose `_bitmap` is in bit value:
        // 0001 0100 = represents third(_index == 2) and fifth(_index == 4) bit is set

        // Suppose `_index` is = 2 = 3th bit
        // 0000 0100 = Left shift to create mask to find 3rd bit status
        uint128 mask = uint128(1) << _index;

        // Example: When bit is set:
        // Performing AND (&) operation
        // 0001 0100 (_bitmap)
        // 0000 0100 (mask)
        // -------------------------
        // 0000 0100 (bitSet > 0)

        // Example: When bit is not set:
        // Performing AND (&) operation
        // 0001 0100 (_bitmap)
        // 0000 1000 (mask)
        // -------------------------
        // 0000 0000 (bitSet == 0)

        uint128 bitSet = _bitmap & mask;
        // Bit is set when greater than zero, else not set
        return bitSet > 0;
    }
// Solidity 0.5.14
/**
 * @dev Add a new token to registry
 * @param _token ERC20 Token address
 * @param _decimals Token's decimals
 * @param _isTransferFeeEnabled Is token changes transfer fee
 * @param _isSupportedOnCompound Is token supported on Compound
 * @param _cToken cToken contract address
 * @param _chainLinkOracle Chain Link Aggregator address to get TOKEN/ETH rate
 */
function addToken(
        address _token,
        uint8 _decimals,
        bool _isTransferFeeEnabled,
        bool _isSupportedOnCompound,
        address _cToken,
        address _chainLinkOracle
    )
        public
        onlyOwner
    {
        require(_token != address(0), "Token address is zero");
        require(!isTokenExist(_token), "Token already exist");
        require(_chainLinkOracle != address(0), "ChainLinkAggregator address is zero");
        require(tokens.length < MAX_TOKENS, "Max token limit reached");

        TokenInfo storage storageTokenInfo = tokenInfo[_token];
        storageTokenInfo.index = uint8(tokens.length);
        storageTokenInfo.decimals = _decimals;
        storageTokenInfo.enabled = true;
        storageTokenInfo.isTransferFeeEnabled = _isTransferFeeEnabled;
        storageTokenInfo.isSupportedOnCompound = _isSupportedOnCompound;
        storageTokenInfo.cToken = _cToken;
        storageTokenInfo.chainLinkOracle = _chainLinkOracle;
        // Default values
        storageTokenInfo.borrowLTV = 60; //6e7; // 60%

        tokens.push(_token);
        emit TokenAdded(_token);
    }
// Solidity 0.5.14
/**
 * Initialize function to be called by the Deployer for the first time
 * @param _tokenAddresses list of token addresses
 * @param _cTokenAddresses list of corresponding cToken addresses
 * @param _globalConfig global configuration contract
 */
function initialize(
        address[] memory _tokenAddresses,
        address[] memory _cTokenAddresses,
        GlobalConfig _globalConfig
    )
        public
        initializer
    {
        // Initialize InitializableReentrancyGuard
        super._initialize();
        super._initialize(address(_globalConfig));

        globalConfig = _globalConfig;

        require(_tokenAddresses.length == _cTokenAddresses.length, "Token and cToken length don't match.");
        uint tokenNum = _tokenAddresses.length;
        for(uint i = 0;i < tokenNum;i++) {
            if(_cTokenAddresses[i] != address(0x0) && _tokenAddresses[i] != ETH_ADDR) {
                approveAll(_tokenAddresses[i]);
            }
        }
    }
// Solidity 0.5.14
/**
 * Borrow the amount of token from the saving pool.
 * @param _token token address
 * @param _amount amout of tokens to borrow
 */
function borrow(address _token, uint256 _amount) external onlySupportedToken(_token) onlyEnabledToken(_token) whenNotPaused nonReentrant {

        require(_amount != 0, "Borrow zero amount of token is not allowed.");

        globalConfig.bank().borrow(msg.sender, _token, _amount);

        // Transfer the token on Ethereum
        SavingLib.send(globalConfig, _amount, _token);

        emit Borrow(_token, msg.sender, _amount);
    }
// Solidity 0.5.14
/**
 * Withdraw all tokens from the saving pool.
 * @param _token the address of the withdrawn token
 */
function withdrawAll(address _token) external onlySupportedToken(_token) whenNotPaused nonReentrant {

        // Sanity check
        require(globalConfig.accounts().getDepositPrincipal(msg.sender, _token) > 0, "Token depositPrincipal must be greater than 0");

        // Add a new checkpoint on the index curve.
        globalConfig.bank().newRateIndexCheckpoint(_token);

        // Get the total amount of token for the account
        uint amount = globalConfig.accounts().getDepositBalanceCurrent(_token, msg.sender);

        uint256 actualAmount = globalConfig.bank().withdraw(msg.sender, _token, amount);
        if(actualAmount != 0) {
            SavingLib.send(globalConfig, actualAmount, _token);
        }
        emit WithdrawAll(_token, msg.sender, actualAmount);
    }
// Solidity 0.5.14
/**
 * @dev Initialize the Collateral flag Bitmap for given account
 * @notice This function is required for the contract upgrade, as previous users didn't
 *         have this collateral feature. So need to init the collateralBitmap for each user.
 * @param _account User account address
 */
function initCollateralFlag(address _account) public {
        Account storage account = accounts[_account];

        // For all users by default `isCollInit` will be `false`
        if(account.isCollInit == false) {
            // Two conditions:
            // 1) An account has some position previous to this upgrade
            //    THEN: copy `depositBitmap` to `collateralBitmap`
            // 2) A new account is setup after this upgrade
            //    THEN: `depositBitmap` will be zero for that user, so don't copy

            // all deposited tokens be treated as collateral
            if(account.depositBitmap > 0) account.collateralBitmap = account.depositBitmap;
            account.isCollInit = true;
        }

        // when isCollInit == true, function will just return after if condition check
    }
// Solidity 0.5.14
/**
 * @dev Enable/Disable collateral for a given token
 * @param _tokenIndex Index of the token
 * @param _enable `true` to enable the collateral, `false` to disable
 */
function setCollateral(uint8 _tokenIndex, bool _enable) public {
        address accountAddr = msg.sender;
        initCollateralFlag(accountAddr);
        Account storage account = accounts[accountAddr];

        if(_enable) {
            account.collateralBitmap = account.collateralBitmap.setBit(_tokenIndex);
            // when set new collateral, no need to evaluate borrow power
        } else {
            account.collateralBitmap = account.collateralBitmap.unsetBit(_tokenIndex);
            // when unset collateral, evaluate borrow power, only when user borrowed already
            if(account.borrowBitmap > 0) {
                require(getBorrowETH(accountAddr) <= getBorrowPower(accountAddr), "Insufficient collateral");
            }
        }

        emit CollateralFlagChanged(msg.sender, _tokenIndex, _enable);
    }
// Solidity 0.5.14
/**
 * Get deposit interest of an account for a specific token
 * @param _account account address
 * @param _token token address
 * @dev The deposit interest may not have been updated in AccountTokenLib, so we need to explicited calcuate it.
 */
function getDepositInterest(address _account, address _token) public view returns(uint256) {
        AccountTokenLib.TokenInfo storage tokenInfo = accounts[_account].tokenInfos[_token];
        // If the account has never deposited the token, return 0.
        uint256 lastDepositBlock = tokenInfo.getLastDepositBlock();
        if (lastDepositBlock == 0)
            return 0;
        else {
            // As the last deposit block exists, the block is also a check point on index curve.
            uint256 accruedRate = globalConfig.bank().getDepositAccruedRate(_token, lastDepositBlock);
            return tokenInfo.calculateDepositInterest(accruedRate);
        }
    }
// Solidity 0.5.14
/**
 * Update token info for deposit
 */
function deposit(address _accountAddr, address _token, uint256 _amount) public onlyAuthorized {
        initCollateralFlag(_accountAddr);
        AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token];
        if(tokenInfo.getDepositPrincipal() == 0) {
            uint8 tokenIndex = globalConfig.tokenInfoRegistry().getTokenIndex(_token);
            setInDepositBitmap(_accountAddr, tokenIndex);
        }

        uint256 blockNumber = getBlockNumber();
        uint256 lastDepositBlock = tokenInfo.getLastDepositBlock();
        if(lastDepositBlock == 0)
            tokenInfo.deposit(_amount, INT_UNIT, blockNumber);
        else {
            calculateDepositFIN(lastDepositBlock, _token, _accountAddr, blockNumber);
            uint256 accruedRate = globalConfig.bank().getDepositAccruedRate(_token, lastDepositBlock);
            tokenInfo.deposit(_amount, accruedRate, blockNumber);
        }
    }
// Solidity 0.5.14
/**
 * Get current borrow balance of a token
 * @param _token token address
 * @dev This is an estimation. Add a new checkpoint first, if you want to derive the exact balance.
 */
function getBorrowBalanceCurrent(
        address _token,
        address _accountAddr
    ) public view returns (uint256 borrowBalance) {
        AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token];
        Bank bank = globalConfig.bank();
        uint256 accruedRate;
        uint256 borrowRateIndex = bank.borrowRateIndex(_token, tokenInfo.getLastBorrowBlock());
        if(tokenInfo.getBorrowPrincipal() == 0) {
            return 0;
        } else {
            if(borrowRateIndex == 0) {
                accruedRate = INT_UNIT;
            } else {
                accruedRate = bank.borrowRateIndexNow(_token)
                .mul(INT_UNIT)
                .div(borrowRateIndex);
            }
            return tokenInfo.getBorrowBalance(accruedRate);
        }
    }
// Solidity 0.5.14
/**
 * Get borrowed balance of a token in the uint256 of Wei
 */
function getBorrowETH(
        address _accountAddr
    ) public view returns (uint256 borrowETH) {
        TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry();
        Account memory account = accounts[_accountAddr];
        uint128 hasBorrows = account.borrowBitmap;
        for(uint8 i = 0; i < 128; i++) {
            if(hasBorrows > 0) {
                bool isEnabled = (hasBorrows & uint128(1)) > 0;
                if(isEnabled) {
                    (address token, uint256 divisor, uint256 price, ) = tokenRegistry.getTokenInfoFromIndex(i);

                    uint256 borrowBalanceCurrent = getBorrowBalanceCurrent(token, _accountAddr);
                    borrowETH = borrowETH.add(borrowBalanceCurrent.mul(price).div(divisor));
                }
                hasBorrows = hasBorrows >> 1;
            } else {
                break;
            }
        }

        return borrowETH;
    }
// Solidity 0.5.14
/**
 * Check if the account is liquidatable
 * @param _borrower borrower's account
 * @return true if the account is liquidatable
 */
function isAccountLiquidatable(address _borrower) public returns (bool) {
        TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry();
        Bank bank = globalConfig.bank();

        // Add new rate check points for all the collateral tokens from borrower in order to
        // have accurate calculation of liquidation oppotunites.
        Account memory account = accounts[_borrower];
        uint128 hasBorrowsOrDeposits = account.borrowBitmap | account.depositBitmap;
        for(uint8 i = 0; i < 128; i++) {
            if(hasBorrowsOrDeposits > 0) {
                bool isEnabled = (hasBorrowsOrDeposits & uint128(1)) > 0;
                if(isEnabled) {
                    address token = tokenRegistry.addressFromIndex(i);
                    bank.newRateIndexCheckpoint(token);
                }
                hasBorrowsOrDeposits = hasBorrowsOrDeposits >> 1;
            } else {
                break;
            }
        }

        uint256 liquidationThreshold = globalConfig.liquidationThreshold();

        uint256 totalBorrow = getBorrowETH(_borrower);
        uint256 totalCollateral = getCollateralETH(_borrower);

        // It is required that LTV is larger than LIQUIDATE_THREADHOLD for liquidation
        // return totalBorrow.mul(100) > totalCollateral.mul(liquidationThreshold);
        return totalBorrow.mul(100) > totalCollateral.mul(liquidationThreshold);
    }
// Solidity 0.5.14
/**
 * An account claim all mined FIN token.
 * @dev If the FIN mining index point doesn't exist, we have to calculate the FIN amount
 * accurately. So the user can withdraw all available FIN tokens.
 */
function claim(address _account) public onlyAuthorized returns(uint256){
        TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry();
        Bank bank = globalConfig.bank();

        uint256 currentBlock = getBlockNumber();

        Account memory account = accounts[_account];
        uint128 depositBitmap = account.depositBitmap;
        uint128 borrowBitmap = account.borrowBitmap;
        uint128 hasDepositOrBorrow = depositBitmap | borrowBitmap;

        for(uint8 i = 0; i < 128; i++) {
            if(hasDepositOrBorrow > 0) {
                if((hasDepositOrBorrow & uint128(1)) > 0) {
                    address token = tokenRegistry.addressFromIndex(i);
                    AccountTokenLib.TokenInfo storage tokenInfo = accounts[_account].tokenInfos[token];
                    bank.updateMining(token);
                    if (depositBitmap.isBitSet(i)) {
                        bank.updateDepositFINIndex(token);
                        uint256 lastDepositBlock = tokenInfo.getLastDepositBlock();
                        calculateDepositFIN(lastDepositBlock, token, _account, currentBlock);
                        tokenInfo.deposit(0, bank.getDepositAccruedRate(token, lastDepositBlock), currentBlock);
                    }

                    if (borrowBitmap.isBitSet(i)) {
                        bank.updateBorrowFINIndex(token);
                        uint256 lastBorrowBlock = tokenInfo.getLastBorrowBlock();
                        calculateBorrowFIN(lastBorrowBlock, token, _account, currentBlock);
                        tokenInfo.borrow(0, bank.getBorrowAccruedRate(token, lastBorrowBlock), currentBlock);
                    }
                }
                hasDepositOrBorrow = hasDepositOrBorrow >> 1;
            } else {
                break;
            }
        }

        uint256 _FINAmount = FINAmount[_account];
        FINAmount[_account] = 0;
        return _FINAmount;
    }