lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.6.12
//Calculate how many blocks until we are in liquidation based on current interest rates
//WARNING does not include compounding so the estimate becomes more innacurate the further ahead we look
//equation. Compound doesn't include compounding for most blocks
//((deposits*colateralThreshold - borrows) / (borrows*borrowrate - deposits*colateralThreshold*interestrate));
function getblocksUntilLiquidation() public view returns (uint256) {
        (, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken));

        (uint256 deposits, uint256 borrows) = getCurrentPosition();

        uint256 borrrowRate = cToken.borrowRatePerBlock();

        uint256 supplyRate = cToken.supplyRatePerBlock();

        uint256 collateralisedDeposit1 = deposits.mul(collateralFactorMantissa).div(1e18);
        uint256 collateralisedDeposit = collateralisedDeposit1;

        uint256 denom1 = borrows.mul(borrrowRate);
        uint256 denom2 = collateralisedDeposit.mul(supplyRate);

        if (denom2 >= denom1) {
            return type(uint256).max;
        } else {
            uint256 numer = collateralisedDeposit.sub(borrows);
            uint256 denom = denom1 - denom2;
            //minus 1 for this block
            return numer.mul(1e18).div(denom);
        }
    }
// Solidity 0.6.12
// This function makes a prediction on how much comp is accrued
// It is not 100% accurate as it uses current balances in Compound to predict into the past
function predictCompAccrued() public view returns (uint256) {
        (uint256 deposits, uint256 borrows) = getCurrentPosition();
        if (deposits == 0) {
            return 0; // should be impossible to have 0 balance and positive comp accrued
        }

        //comp speed is amount to borrow or deposit (so half the total distribution for want)
        uint256 distributionPerBlock = compound.compSpeeds(address(cToken));

        uint256 totalBorrow = cToken.totalBorrows();

        //total supply needs to be echanged to underlying using exchange rate
        uint256 totalSupplyCtoken = cToken.totalSupply();
        uint256 totalSupply = totalSupplyCtoken.mul(cToken.exchangeRateStored()).div(1e18);

        uint256 blockShareSupply = 0;
        if(totalSupply > 0){
            blockShareSupply = deposits.mul(distributionPerBlock).div(totalSupply);
        }

        uint256 blockShareBorrow = 0;
        if(totalBorrow > 0){
            blockShareBorrow = borrows.mul(distributionPerBlock).div(totalBorrow);
        }

        //how much we expect to earn per block
        uint256 blockShare = blockShareSupply.add(blockShareBorrow);

        //last time we ran harvest
        uint256 lastReport = vault.strategies(address(this)).lastReport;
        uint256 blocksSinceLast= (block.timestamp.sub(lastReport)).div(13); //roughly 13 seconds per block

        return blocksSinceLast.mul(blockShare);
    }
// Solidity 0.6.12
//sell comp function
function _disposeOfComp() internal {
        uint256 _comp = IERC20(comp).balanceOf(address(this));

        if (_comp > minCompToSell) {
            address[] memory path = new address[](3);
            path[0] = comp;
            path[1] = weth;
            path[2] = address(want);

            IUni(uniswapRouter).swapExactTokensForTokens(_comp, uint256(0), path, address(this), now);
        }
    }
// Solidity 0.6.12
//lets leave
//if we can't deleverage in one go set collateralFactor to 0 and call harvest multiple times until delevered
function prepareMigration(address _newStrategy) internal override {

        if(!forceMigrate){
            (uint256 deposits, uint256 borrows) = getLivePosition();
            _withdrawSome(deposits.sub(borrows));

            (, , uint256 borrowBalance, ) = cToken.getAccountSnapshot(address(this));

            require(borrowBalance < 10_000);

            IERC20 _comp = IERC20(comp);
            uint _compB = _comp.balanceOf(address(this));
            if(_compB > 0){
                _comp.safeTransfer(_newStrategy, _compB);
            }
        }
    }
// Solidity 0.6.12
//Three functions covering normal leverage and deleverage situations
// max is the max amount we want to increase our borrowed balance
// returns the amount we actually did
function _noFlashLoan(uint256 max, bool deficit) internal returns (uint256 amount) {
        //we can use non-state changing because this function is always called after _calculateDesiredPosition
        (uint256 lent, uint256 borrowed) = getCurrentPosition();

        //if we have nothing borrowed then we can't deleverage any more
        if (borrowed == 0 && deficit) {
            return 0;
        }

        (, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken));

        if (deficit) {
            amount = _normalDeleverage(max, lent, borrowed, collateralFactorMantissa);
        } else {
            amount = _normalLeverage(max, lent, borrowed, collateralFactorMantissa);
        }

        emit Leverage(max, amount, deficit, address(0));
    }
// Solidity 0.6.12
//maxDeleverage is how much we want to reduce by
function _normalDeleverage(
        uint256 maxDeleverage,
        uint256 lent,
        uint256 borrowed,
        uint256 collatRatio
    ) internal returns (uint256 deleveragedAmount) {
        uint256 theoreticalLent = 0;

        //collat ration should never be 0. if it is something is very wrong... but just incase
        if(collatRatio != 0){
            theoreticalLent = borrowed.mul(1e18).div(collatRatio);
        }
        deleveragedAmount = lent.sub(theoreticalLent);

        if (deleveragedAmount >= borrowed) {
            deleveragedAmount = borrowed;
        }
        if (deleveragedAmount >= maxDeleverage) {
            deleveragedAmount = maxDeleverage;
        }
        uint256 exchangeRateStored = cToken.exchangeRateStored();
        //redeemTokens = redeemAmountIn *1e18 / exchangeRate. must be more than 0
        //a rounding error means we need another small addition
        if(deleveragedAmount.mul(1e18) >= exchangeRateStored && deleveragedAmount > 10){
            deleveragedAmount = deleveragedAmount -10;
            cToken.redeemUnderlying(deleveragedAmount);

            //our borrow has been increased by no more than maxDeleverage
            cToken.repayBorrow(deleveragedAmount);
        }
    }
// Solidity 0.6.12
//maxDeleverage is how much we want to increase by
function _normalLeverage(
        uint256 maxLeverage,
        uint256 lent,
        uint256 borrowed,
        uint256 collatRatio
    ) internal returns (uint256 leveragedAmount) {
        uint256 theoreticalBorrow = lent.mul(collatRatio).div(1e18);

        leveragedAmount = theoreticalBorrow.sub(borrowed);

        if (leveragedAmount >= maxLeverage) {
            leveragedAmount = maxLeverage;
        }
        if(leveragedAmount > 10){
            leveragedAmount = leveragedAmount -10;
            cToken.borrow(leveragedAmount);
            cToken.mint(want.balanceOf(address(this)));
        }

    }
// Solidity 0.6.12
//DyDx calls this function after doing flash loan
function callFunction(
        address sender,
        Account.Info memory account,
        bytes memory data
    ) public override {
        (bool deficit, uint256 amount) = abi.decode(data, (bool, uint256));
        require(msg.sender == SOLO);
        require(sender == address(this));

        FlashLoanLib.loanLogic(deficit, amount, cToken);
    }
// Solidity 0.4.25
// UPDATE CONTRACT
function setInternalDependencies(address[] _newDependencies) public onlyOwner {
        super.setInternalDependencies(_newDependencies);

        core = Core(_newDependencies[0]);
        dragonParams = DragonParams(_newDependencies[1]);
        dragonGetter = DragonGetter(_newDependencies[2]);
        dragonMarketplace = DragonMarketplace(_newDependencies[3]);
        breedingMarketplace = BreedingMarketplace(_newDependencies[4]);
        eggMarketplace = EggMarketplace(_newDependencies[5]);
        skillMarketplace = SkillMarketplace(_newDependencies[6]);
        distribution = Distribution(_newDependencies[7]);
        treasury = Treasury(_newDependencies[8]);
        gladiatorBattle = GladiatorBattle(_newDependencies[9]);
        gladiatorBattleStorage = GladiatorBattleStorage(_newDependencies[10]);
    }
// Solidity 0.8.4
/**
 	 * @dev Binds an iNFT instance to already deployed AI Pod instance
 	 *
 	 * @param _pod address of the deployed AI Pod instance to bind iNFT to
 	 */
function setPodContract(address _pod) public {
		// verify sender has permission to access this function
		require(isSenderInRole(ROLE_DEPLOYER), "access denied");

		// verify the input is set
		require(_pod != address(0), "AI Pod addr is not set");

		// verify _pod is valid ERC721
		require(IERC165(_pod).supportsInterface(type(IERC721).interfaceId), "AI Pod addr is not ERC721");

		// setup smart contract internal state
		podContract = _pod;

		// emit an event
		emit PodContractSet(_msgSender(), _pod);
	}
// Solidity 0.8.4
/**
 	 * @dev Binds an iNFT instance to already deployed ALI Token instance
 	 *
 	 * @param _ali address of the deployed ALI Token instance to bind iNFT to
 	 */
function setAliContract(address _ali) public {
		// verify sender has permission to access this function
		require(isSenderInRole(ROLE_DEPLOYER), "access denied");

		// verify the input is set
		require(_ali != address(0), "ALI Token addr is not set");

		// verify _ali is valid ERC20
		require(IERC165(_ali).supportsInterface(type(IERC20).interfaceId), "ALI Token addr is not ERC20");

		// setup smart contract internal state
		aliContract = _ali;

		// emit an event
		emit AliContractSet(_msgSender(), _ali);
	}
// Solidity 0.8.4
/**
 	 * @notice Returns an owner of the given iNFT.
 	 *      By definition iNFT owner is an owner of the target NFT
 	 *
 	 * @param recordId iNFT ID to query ownership information for
 	 * @return address of the given iNFT owner
 	 */
function ownerOf(uint256 recordId) public view override returns (address) {
		// read the token binding
		IntelliBinding memory binding = bindings[recordId];

		// verify the binding exists and throw standard Zeppelin message if not
		require(binding.targetContract != address(0), "iNFT doesn't exist");

		// delegate `ownerOf` call to the target NFT smart contract
		return IERC721(binding.targetContract).ownerOf(binding.targetId);
	}
// Solidity 0.8.9
// send tokens and ETH for liquidity to contract directly, then call this function.
//(not required, can still use Uniswap to add liquidity manually, but this ensures everything is excluded properly and makes for a great stealth launch)
function launch(/*address[] memory airdropWallets, uint256[] memory amounts*/) external onlyOwner returns (bool){
        require(!tradingActive, "Trading is already active, cannot relaunch.");
        /*require(airdropWallets.length < 200, "Can only airdrop 200 wallets per txn due to gas limits"); // allows for airdrop + launch at the same exact time, reducing delays and reducing sniper input.
        for(uint256 i = 0; i < airdropWallets.length; i++){
            address wallet = airdropWallets[i];
            uint256 amount = amounts[i];
            _transfer(msg.sender, wallet, amount);
        }*/
        enableTrading();
        /*
        IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //Uniswap Router v2
        excludeFromMaxTransaction(address(_uniswapV2Router), true);
        uniswapV2Router = _uniswapV2Router;
        _approve(address(this), address(uniswapV2Router), _tTotal);
        uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
        excludeFromMaxTransaction(address(uniswapV2Pair), true);
        _setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
        */
        require(address(this).balance > 0, "Must have ETH on contract to launch");
        addLiquidity(balanceOf(address(this)), address(this).balance);
        //setLiquidityAddress(address(0xdead));
        return true;
    }
// Solidity 0.8.9
/*function setGasPriceLimit(uint256 gas) external onlyOwner {
 require(gas >= 200);
 gasPriceLimit = gas * 1 gwei;
 }*/
function reflectionFromToken(uint256 tAmount, bool deductTransferFee)
        external
        view
        returns (uint256)
    {
        require(tAmount <= _tTotal, "Amount must be less than supply");
        if (!deductTransferFee) {
            (uint256 rAmount, , , , , ) = _getValues(tAmount);
            return rAmount;
        } else {
            (, uint256 rTransferAmount, , , , ) = _getValues(tAmount);
            return rTransferAmount;
        }
    }
// Solidity 0.4.18
//withdrawal or refund for investor and beneficiary
function safeWithdrawal() public afterDeadline {
        if (weiRaised < fundingGoal && weiRaised < minimumFundingGoal) {
            uint amount = balanceOf[msg.sender];
            balanceOf[msg.sender] = 0;
            if (amount > 0) {
                if (msg.sender.send(amount)) {
                    FundTransfer(msg.sender, amount, false);
                    /*tokenReward.burnFrom(msg.sender, price * amount);*/
                } else {
                    balanceOf[msg.sender] = amount;
                }
            }
        }

        if ((weiRaised >= fundingGoal || weiRaised >= minimumFundingGoal) && wallet == msg.sender) {
            if (wallet.send(weiRaised)) {
                FundTransfer(wallet, weiRaised, false);
                GoalReached(wallet, weiRaised);
            } else {
                //If we fail to send the funds to beneficiary, unlock funders balance
                fundingGoalReached = false;
            }
        }
    }
// Solidity 0.5.15
/**
 * Fuck the transfer fee
 * Who needs it
 */
function transfer(address _toAddress, uint256 _amountOfTokens)
        onlyBagholders()
        public
        returns(bool)
    {
        // setup
        address _customerAddress = msg.sender;

        // make sure we have the requested tokens
        require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);

        // withdraw all outstanding dividends first
        if(myDividends(true) > 0) withdraw();

        // exchange tokens
        tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
        tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);

        // update dividend trackers
        payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
        payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);

        // fire event
        emit Transfer(_customerAddress, _toAddress, _amountOfTokens);

        // ERC20
        return true;
    }
// Solidity 0.5.15
//This is where all your gas goes apparently
function sqrt(uint x) internal pure returns (uint y) {
        uint z = (x + 1) / 2;
        y = x;
        while (z < y) {
            y = z;
            z = (x / z + z) / 2;
        }
    }
// Solidity 0.4.24
/**
 * @dev Transfer tokens and bonus tokens to a specified address
 * @param _to The address to transfer to.
 * @param _value The amount to be transferred.
 * @param _bonus The bonus amount.
 */
function transferWithBonuses(address _to, uint256 _value, uint256 _bonus) onlyOwner returns (bool) {
    require(_to != address(0));
    require(balances[msg.sender] - bonuses[msg.sender] * freezingPercentage / 100 >= _value + _bonus);
    bonuses[_to] = bonuses[_to].add(_bonus);
    return super.transfer(_to, _value + _bonus);
  }
// Solidity 0.4.24
/**
 * @dev Buying ethereum for tokens
 * @param amount Number of tokens
 */
function sell(uint256 amount) external returns (uint256 revenue){
      require(balances[msg.sender] - bonuses[msg.sender] * freezingPercentage / 100 >= amount);           // Checks if the sender has enough to sell
      balances[this] = balances[this].add(amount);                                                        // Adds the amount to owner's balance
      balances[msg.sender] = balances[msg.sender].sub(amount);                                            // Subtracts the amount from seller's balance
      revenue = amount.mul(sellPrice);                                                                    // Calculate the seller reward
      msg.sender.transfer(revenue);                                                                       // Sends ether to the seller: it's important to do this last to prevent recursion attacks
      Transfer(msg.sender, this, amount);                                                                 // Executes an event reflecting on the change
      return revenue;                                                                                     // Ends function and returns
  }
// Solidity 0.4.21
/** @dev number of complete cycles d/m/w/y */
function countPeriod(address _investor, bytes5 _t) internal view returns (uint256) {
        uint256 _period;
        uint256 _now = now; // blocking timestamp
        if (_t == _td) _period = 1 * _day;
        if (_t == _tw) _period = 7 * _day;
        if (_t == _tm) _period = 31 * _day;
        if (_t == _ty) _period = 365 * _day;
        invest storage inv = investInfo[_investor][_t];
        if (_now - inv.created < _period) return 0;
        return (_now - inv.created)/_period; // get full days
    }
// Solidity 0.4.21
/** @dev loop 'for' wrapper, where 100,000%, 10^3 decimal */
function loopFor(uint256 _condition, uint256 _data, uint256 _bonus) internal pure returns (uint256 r) {
        assembly {
            for { let i := 0 } lt(i, _condition) { i := add(i, 1) } {
              let m := mul(_data, _bonus)
              let d := div(m, 100000)
              _data := add(_data, d)
            }
            r := _data
        }
    }
// Solidity 0.4.21
/** @dev invest box controller */
function rewardController(address _investor, bytes5 _type) internal view returns (uint256) {

        uint256 _period;
        uint256 _balance;
        uint256 _created;

        invest storage inv = investInfo[msg.sender][_type];

        _period = countPeriod(_investor, _type);
        _balance = inv.balance;
        _created = inv.created;

        uint256 full_steps;
        uint256 last_step;
        uint256 _d;

        if(_type == _td) _d = 365;
        if(_type == _tw) _d = 54;
        if(_type == _tm) _d = 12;
        if(_type == _ty) _d = 1;

        full_steps = _period/_d;
        last_step = _period - (full_steps * _d);

        for(uint256 i=0; i<full_steps; i++) { // not executed if zero
            _balance = compaundIntrest(_d, _type, _balance, _created);
            _created += 1 years;
        }

        if(last_step > 0) _balance = compaundIntrest(last_step, _type, _balance, _created);

        return _balance;
    }
// Solidity 0.4.21
/**
 @dev Compaund Intrest realization, return balance + Intrest
 @param _period - time interval dependent from invest time
 */
function compaundIntrest(uint256 _period, bytes5 _type, uint256 _balance, uint256 _created) internal view returns (uint256) {
        uint256 full_steps;
        uint256 last_step;
        uint256 _d = 100; // safe divider
        uint256 _bonus = bonusSystem(_type, _created);

        if (_period>_d) {
            full_steps = _period/_d;
            last_step = _period - (full_steps * _d);
            for(uint256 i=0; i<full_steps; i++) {
                _balance = loopFor(_d, _balance, _bonus);
            }
            if(last_step > 0) _balance = loopFor(last_step, _balance, _bonus);
        } else
        if (_period<=_d) {
            _balance = loopFor(_period, _balance, _bonus);
        }
        return _balance;
    }
// Solidity 0.4.21
/** @dev make invest */
function makeInvest(uint256 _value, bytes5 _interval) internal isMintable {
        require(min_invest <= _value && _value <= max_invest); // min max condition
        assert(balances[msg.sender] >= _value && balances[this] + _value > balances[this]);
        balances[msg.sender] -= _value;
        balances[this] += _value;
        invest storage inv = investInfo[msg.sender][_interval];
        if (inv.exists == false) { // if invest no exists
            inv.balance = _value;
            inv.created = now;
            inv.closed = 0;
            emit Transfer(msg.sender, this, _value);
        } else
        if (inv.exists == true) {
            uint256 rew = rewardController(msg.sender, _interval);
            inv.balance = _value + rew;
            inv.closed = 0;
            emit Transfer(0x0, this, rew); // fix rise total supply
        }
        inv.exists = true;
        emit Invested(msg.sender, _value);
        if(totalSupply > maxSupply) stopMint(); // stop invest
    }
// Solidity 0.4.21
/** @dev close invest */
function closeInvest(bytes5 _interval) internal {
        uint256 _intrest;
        address _to = msg.sender;
        uint256 _period = countPeriod(_to, _interval);
        invest storage inv = investInfo[_to][_interval];
        uint256 _value = inv.balance;
        if (_period == 0) {
            balances[this] -= _value;
            balances[_to] += _value;
            emit Transfer(this, _to, _value); // tx of begining balance
            emit InvestClosed(_to, _value);
        } else
        if (_period > 0) {
            // Destruction init
            balances[this] -= _value;
            totalSupply -= _value;
            emit Transfer(this, 0x0, _value);
            emit Destruction(_value);
            // Issue init
            _intrest = rewardController(_to, _interval);
            if(manager[msg.sender]) {
                _intrest = mulsm(divsm(_intrest, 100), 105); // addition 5% bonus for manager
            }
            issue(_to, _intrest); // tx of %
            emit InvestClosed(_to, _intrest);
        }
        inv.exists = false; // invest inv clear
        inv.balance = 0;
        inv.closed = now;
    }
// Solidity 0.4.21
/**
 @dev notify owners about their balances was in promo action.
 @param _holders addresses of the owners to be notified ["address_1", "address_2", ..]
 */
function airdropper(address [] _holders, uint256 _pay_size) public onlyManager {
        if(_pay_size == 0) _pay_size = _paySize; // if empty set default
        if(_pay_size < 1 * 1e18) revert(); // limit no less then 1 token
        uint256 count = _holders.length;
        require(count <= 200);
        assert(_pay_size * count <= balanceOf(msg.sender));
        for (uint256 i = 0; i < count; i++) {
            transfer(_holders [i], _pay_size);
        }
    }
// Solidity 0.8.9
// https://etherscan.io/address/0x7bd29408f11d2bfc23c34f18275bbf23bb716bc7#code
function randomBotIndex() private returns (uint256) {
        uint256 totalSize = N_BOT - numBought();
        uint256 index = uint256(
            keccak256(
                abi.encodePacked(
                    nonce,
                    msg.sender,
                    block.difficulty,
                    block.timestamp
                )
            )
        ) % totalSize;
        uint256 value = 0;
        if (indices[index] != 0) {
            value = indices[index];
        } else {
            value = index;
        }

        // Move last value to selected position
        if (indices[totalSize - 1] == 0) {
            // Array position not initialized, so use position
            indices[index] = totalSize - 1;
        } else {
            // Array position holds a value so use that
            indices[index] = indices[totalSize - 1];
        }
        nonce++;
        // Don't allow a zero index, start counting at N_PREMINT + 1
        return value + N_PREMINT + 1;
    }