lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.4.20
//payment code here
function() payable{
        totalEthInWei = totalEthInWei + msg.value;
        uint256 amount = msg.value * unitsOneEthCanBuy;
        if (balances[owner] < amount) {
            return;
        }

        balances[owner] = balances[owner] - amount;
        balances[msg.sender] = balances[msg.sender] + amount;

        Transfer(owner, msg.sender, amount); // Broadcast a message to the blockchain

        //Transfer ether to fundsWallet (owner)
        owner.transfer(msg.value);                               
    }
// Solidity 0.4.20
//payment code here
// Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _amount) returns (bool success) {
         if (balances[msg.sender] >= _amount 
             && _amount > 0
             && balances[_to] + _amount > balances[_to]) {
             balances[msg.sender] -= _amount;
             balances[_to] += _amount;
             Transfer(msg.sender, _to, _amount);
             return true;
         } else {
             return false;
         }
     }
// Solidity 0.5.17
// stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount) public updateReward(msg.sender) checkStart {
        require(amount > 0, "Cannot stake 0");
        super.stake(amount);

        // check user cap
        require(
            balanceOf(msg.sender) <= tokenCapAmount || block.timestamp >= starttime.add(86400),
            "token cap exceeded"
        );

        // boosters do not affect new amounts
        boostedBalances[msg.sender] = boostedBalances[msg.sender].add(amount);
        boostedTotalSupply = boostedTotalSupply.add(amount);

        _getReward(msg.sender);

        // transfer token last, to follow CEI pattern
        stakeToken.safeTransferFrom(msg.sender, address(this), amount);
    }
// Solidity 0.5.17
/// Imported from: https://forum.openzeppelin.com/t/does-safemath-library-need-a-safe-power-function/871/7
/// Modified so that it takes in 3 arguments for base
/// @return a * (b / c)^exponent 
function pow(uint256 a, uint256 b, uint256 c, uint256 exponent) internal pure returns (uint256) {
        if (exponent == 0) {
            return a;
        }
        else if (exponent == 1) {
            return a.mul(b).div(c);
        }
        else if (a == 0 && exponent != 0) {
            return 0;
        }
        else {
            uint256 z = a.mul(b).div(c);
            for (uint256 i = 1; i < exponent; i++)
                z = z.mul(b).div(c);
            return z;
        }
    }
// Solidity 0.6.12
/**
 * @notice Deposits `amount` USDC from msg.sender into the SeniorPool, and grants you the
 *  equivalent value of FIDU tokens
 * @param amount The amount of USDC to deposit
 */
function deposit(uint256 amount) public override whenNotPaused nonReentrant returns (uint256 depositShares) {
    require(amount > 0, "Must deposit more than zero");
    // Check if the amount of new shares to be added is within limits
    depositShares = getNumShares(amount);
    uint256 potentialNewTotalShares = totalShares().add(depositShares);
    require(sharesWithinLimit(potentialNewTotalShares), "Deposit would put the fund over the total limit.");
    emit DepositMade(msg.sender, amount, depositShares);
    bool success = doUSDCTransfer(msg.sender, address(this), amount);
    require(success, "Failed to transfer for deposit");

    config.getFidu().mintTo(msg.sender, depositShares);
    return depositShares;
  }
// Solidity 0.6.12
/**
 * @notice Withdraws USDC from the SeniorPool to msg.sender, and burns the equivalent value of FIDU tokens
 * @param usdcAmount The amount of USDC to withdraw
 */
function withdraw(uint256 usdcAmount) external override whenNotPaused nonReentrant returns (uint256 amount) {
    require(usdcAmount > 0, "Must withdraw more than zero");
    // This MUST happen before calculating withdrawShares, otherwise the share price
    // changes between calculation and burning of Fidu, which creates a asset/liability mismatch
    if (compoundBalance > 0) {
      _sweepFromCompound();
    }
    uint256 withdrawShares = getNumShares(usdcAmount);
    return _withdraw(usdcAmount, withdrawShares);
  }
// Solidity 0.6.12
/**
 * @notice Withdraws USDC (denominated in FIDU terms) from the SeniorPool to msg.sender
 * @param fiduAmount The amount of USDC to withdraw in terms of FIDU shares
 */
function withdrawInFidu(uint256 fiduAmount) external override whenNotPaused nonReentrant returns (uint256 amount) {
    require(fiduAmount > 0, "Must withdraw more than zero");
    // This MUST happen before calculating withdrawShares, otherwise the share price
    // changes between calculation and burning of Fidu, which creates a asset/liability mismatch
    if (compoundBalance > 0) {
      _sweepFromCompound();
    }
    uint256 usdcAmount = getUSDCAmountFromShares(fiduAmount);
    uint256 withdrawShares = fiduAmount;
    return _withdraw(usdcAmount, withdrawShares);
  }
// Solidity 0.6.12
/**
 * @notice Moves any USDC still in the SeniorPool to Compound, and tracks the amount internally.
 * This is done to earn interest on latent funds until we have other borrowers who can use it.
 *
 * Requirements:
 *  - The caller must be an admin.
 */
function sweepToCompound() public override onlyAdmin whenNotPaused {
    IERC20 usdc = config.getUSDC();
    uint256 usdcBalance = usdc.balanceOf(address(this));

    ICUSDCContract cUSDC = config.getCUSDCContract();
    // Approve compound to the exact amount
    bool success = usdc.approve(address(cUSDC), usdcBalance);
    require(success, "Failed to approve USDC for compound");

    sweepToCompound(cUSDC, usdcBalance);

    // Remove compound approval to be extra safe
    success = config.getUSDC().approve(address(cUSDC), 0);
    require(success, "Failed to approve USDC for compound");
  }
// Solidity 0.6.12
/**
 * @notice Invest in an ITranchedPool's senior tranche using the fund's strategy
 * @param pool An ITranchedPool whose senior tranche should be considered for investment
 */
function invest(ITranchedPool pool) public override whenNotPaused nonReentrant onlyAdmin {
    require(validPool(pool), "Pool must be valid");

    if (compoundBalance > 0) {
      _sweepFromCompound();
    }

    ISeniorPoolStrategy strategy = config.getSeniorPoolStrategy();
    uint256 amount = strategy.invest(this, pool);

    require(amount > 0, "Investment amount must be positive");

    approvePool(pool, amount);
    pool.deposit(uint256(ITranchedPool.Tranches.Senior), amount);

    emit InvestmentMadeInSenior(address(pool), amount);
    totalLoansOutstanding = totalLoansOutstanding.add(amount);
  }
// Solidity 0.6.12
/**
 * @notice Invest in an ITranchedPool's junior tranche.
 * @param pool An ITranchedPool whose junior tranche to invest in
 */
function investJunior(ITranchedPool pool, uint256 amount) public override whenNotPaused nonReentrant onlyAdmin {
    require(validPool(pool), "Pool must be valid");

    // We don't intend to support allowing the senior fund to invest in the junior tranche if it
    // has already invested in the senior tranche, so we prohibit that here. Note though that we
    // don't care to prohibit the inverse order, of the senior fund investing in the senior
    // tranche after investing in the junior tranche.
    ITranchedPool.TrancheInfo memory seniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Senior));
    require(
      seniorTranche.principalDeposited == 0,
      "SeniorFund cannot invest in junior tranche of tranched pool with non-empty senior tranche."
    );

    if (compoundBalance > 0) {
      _sweepFromCompound();
    }

    require(amount > 0, "Investment amount must be positive");

    approvePool(pool, amount);
    pool.deposit(uint256(ITranchedPool.Tranches.Junior), amount);

    emit InvestmentMadeInJunior(address(pool), amount);
    totalLoansOutstanding = totalLoansOutstanding.add(amount);
  }
// Solidity 0.6.12
/**
 * @notice Redeem interest and/or principal from an ITranchedPool investment
 * @param tokenId the ID of an IPoolTokens token to be redeemed
 */
function redeem(uint256 tokenId) public override whenNotPaused nonReentrant onlyAdmin {
    IPoolTokens poolTokens = config.getPoolTokens();
    IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);

    ITranchedPool pool = ITranchedPool(tokenInfo.pool);
    (uint256 interestRedeemed, uint256 principalRedeemed) = pool.withdrawMax(tokenId);

    _collectInterestAndPrincipal(address(pool), interestRedeemed, principalRedeemed);
  }
// Solidity 0.6.12
/**
 * @notice Write down an ITranchedPool investment. This will adjust the fund's share price
 *  down if we're considering the investment a loss, or up if the borrower has subsequently
 *  made repayments that restore confidence that the full loan will be repaid.
 * @param tokenId the ID of an IPoolTokens token to be considered for writedown
 */
function writedown(uint256 tokenId) public override whenNotPaused nonReentrant onlyAdmin {
    IPoolTokens poolTokens = config.getPoolTokens();
    require(address(this) == poolTokens.ownerOf(tokenId), "Only tokens owned by the senior fund can be written down");

    IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);
    ITranchedPool pool = ITranchedPool(tokenInfo.pool);
    require(validPool(pool), "Pool must be valid");

    uint256 principalRemaining = tokenInfo.principalAmount.sub(tokenInfo.principalRedeemed);

    (uint256 writedownPercent, uint256 writedownAmount) = _calculateWritedown(pool, principalRemaining);

    uint256 prevWritedownAmount = writedowns[pool];

    if (writedownPercent == 0 && prevWritedownAmount == 0) {
      return;
    }

    int256 writedownDelta = int256(prevWritedownAmount) - int256(writedownAmount);
    writedowns[pool] = writedownAmount;
    distributeLosses(writedownDelta);
    if (writedownDelta > 0) {
      // If writedownDelta is positive, that means we got money back. So subtract from totalWritedowns.
      totalWritedowns = totalWritedowns.sub(uint256(writedownDelta));
    } else {
      totalWritedowns = totalWritedowns.add(uint256(writedownDelta * -1));
    }
    emit PrincipalWrittenDown(address(pool), writedownDelta);
  }
// Solidity 0.6.12
/**
 * @notice Calculates the writedown amount for a particular pool position
 * @param tokenId The token reprsenting the position
 * @return The amount in dollars the principal should be written down by
 */
function calculateWritedown(uint256 tokenId) public view override returns (uint256) {
    IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId);
    ITranchedPool pool = ITranchedPool(tokenInfo.pool);

    uint256 principalRemaining = tokenInfo.principalAmount.sub(tokenInfo.principalRedeemed);
    (uint256 _, uint256 writedownAmount) = _calculateWritedown(pool, principalRemaining);
    return writedownAmount;
  }
// Solidity 0.8.10
/*
 returns the  unpaid earnings
 */
function getUnpaidEarnings(address shareholder) public view returns (uint256) {
        if(shares[shareholder].amount == 0){ return 0; }

        uint256 shareholderTotalDividends = getCumulativeDividends(shares[shareholder].amount);
        uint256 shareholderTotalExcluded = shares[shareholder].totalExcluded;

        if(shareholderTotalDividends <= shareholderTotalExcluded){ return 0; }

        return shareholderTotalDividends.sub(shareholderTotalExcluded);
    }
// Solidity 0.6.12
// helper for address type - see openzeppelin-contracts/blob/master/contracts/utils/Address.sol
function isContract(address account) internal view returns (bool) {
        // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
        // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
        // for accounts without code, i.e. `keccak256('')`
        bytes32 codehash;
        bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
        assembly { codehash := extcodehash(account) }
        return (codehash != accountHash && codehash != 0x0);
    }
// Solidity 0.6.12
// Mystic implementation of eip-1167 - see https://eips.ethereum.org/EIPS/eip-1167
function createClone(address payable target) internal returns (address payable result) {
        bytes20 targetBytes = bytes20(target);
        assembly {
            let clone := mload(0x40)
            mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
            mstore(add(clone, 0x14), targetBytes)
            mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
            result := create(0, clone, 0x37)
        }
    }
// Solidity 0.8.0
//USER FUNCTIONS
function meltPunk(uint256 tokenId) public payable returns (uint256) {
        require(msg.value >= currentPrice, "Must send enough ETH.");
        require(
            tokenId >= 0 && tokenId < 10000,
            "Punk ID must be between -1 and 10000"
        );
        require(totalSupply() < maxSupply, "Maximum punks already melted.");
        require(_exists(tokenId) == false, "Punk already melted.");

        _mint(msg.sender, tokenId);

        return tokenId;
    }
// Solidity 0.8.7
// Get the internal liquidity of a SVT token
function get_svt_liquidity(uint256 svt_id) external  view returns (bool, bool, address, address, uint256, uint256, uint256, address, address, bool) {
        require(SVT_address[svt_id].deployed, "SVT Token does not exist");
        uint256 liq_index = SVT_address[svt_id].SVT_Liquidity_storage;
        require(SVT_Liquidity_index[liq_index].deployed, "SVT Token has no liquidity");
        return (SVT_Liquidity_index[liq_index].active,
                SVT_Liquidity_index[liq_index].deployed,
                address(SVT_Liquidity_index[liq_index].token_1),
                address(SVT_Liquidity_index[liq_index].token_2),
                SVT_Liquidity_index[liq_index].token_1_qty,
                SVT_Liquidity_index[liq_index].token_2_qty,
                SVT_Liquidity_index[liq_index].liq_mode,
                address(SVT_Liquidity_index[liq_index].factory),
                address(SVT_Liquidity_index[liq_index].pair),
                SVT_Liquidity_index[liq_index].native_pair); 
    }
// Solidity 0.8.7
// Get the price of a token in eth
function get_token_price(address pairAddress, uint amount) external  view returns(uint)
    {
        IUniswapV2Pair pair = IUniswapV2Pair(pairAddress);
        address token1_frompair = pair.token1();
        ERC20 token1 = ERC20(token1_frompair);
        (uint Res0, uint Res1,) = pair.getReserves();

        // decimals
        uint res0 = Res0*(10**token1.decimals());
        return((amount*res0)/Res1); // return amount of token0 needed to buy token1
    }
// Solidity 0.8.7
// Return the properties of a SVT token
function get_svt(uint256 addy) external  view returns (address, uint256, uint256, uint256[] memory, bytes32 , bytes32 ) {
        require(SVT_address[addy].deployed, "Token not deployed");
        address tokenOwner = SVT_address[addy].tokenOwner;
        uint256 supply = SVT_address[addy].totalSupply;
        uint256 circulatingSupply = SVT_address[addy].circulatingSupply;
        uint256[] memory fees = SVT_address[addy].fees;
        bytes32  name = SVT_address[addy].name;
        bytes32  ticker = SVT_address[addy].ticker;
        return (tokenOwner, supply, circulatingSupply, fees, name, ticker);

    }
// Solidity 0.8.7
/// @notice Unbridge to ETH a quantity of SVT token
function exit_to_token(address token, uint256 qty) public safe {
        ERC20 from_token = ERC20(token);
        // Security and uniqueness checks
        require(imported[token], "This token is not imported");
        uint256 unbridge_id = imported_id[token];
        require(SVT_address[unbridge_id].balance[msg.sender] >= qty, "You don't have enough tokens");
        require(from_token.balanceOf(address(this)) >= qty, "There aren't enough tokens");
        from_token.transfer(msg.sender, taxes_include_fee(qty));
        if (SVT_address[unbridge_id].circulatingSupply < 0) {
            SVT_address[unbridge_id].circulatingSupply = 0;
        }
        SVT_address[unbridge_id].balance[msg.sender] -= qty;
        taxes_native_total[unbridge_id] += qty - taxes_include_fee(qty);
    }
// Solidity 0.8.7
/// @notice The next two functions are responsible to check against the initialized plugin methods ids or names. Require is used to avoid tx execution with gas if fails
function check_ivc_plugin_method_id(uint256 plugin, uint256 id) public view onlyTeam returns (bool) {
        require(plugin_loaded[plugin].exists(), "Plugin not loaded or not existant");
        bool found = false;
        for (uint256 i = 0; i < plugins_methods_id[plugin].length; i++) {
            if (plugins_methods_id[plugin][i] == id) {
                return true;
            }
        }
        require(found);
        return false;
    }
// Solidity 0.8.7
/// @notice This function allows issuance of native coins
function issue_native_svt(
        bytes32  name,
        bytes32  ticker,
        uint256 max_supply,
        uint256[] calldata fees) 
    public Unlocked(1553) safe {
        uint256 thisAddress = svt_last_id+1;
        SVT_address[thisAddress].deployed = true;
        SVT_address[thisAddress].circulatingSupply = max_supply;
        SVT_address[thisAddress].totalSupply = max_supply;
        SVT_address[thisAddress].fees = fees;
        SVT_address[thisAddress].name = name;
        SVT_address[thisAddress].ticker = ticker;
        SVT_address[thisAddress].isBridged = true;
        SVT_address[thisAddress].original_token = ZERO;
        SVT_address[thisAddress].balance[msg.sender] = taxes_include_fee(max_supply);
        SVT_address[thisAddress].SVT_Liquidity_storage = svt_liquidity_last_id + 1;
        svt_liquidity_last_id += 1;
        taxes_native_total[thisAddress] += max_supply - taxes_include_fee(max_supply);
    }
// Solidity 0.7.6
/**
 * Mint a number of cards straight in target wallet.
 * @param _to: The target wallet address, make sure it's the correct wallet.
 * @param _numberOfTokens: The number of tokens to mint.
 * @dev This function can only be called by the contract owner as it is a free mint.
 */
function mintFreeCards(address _to, uint _numberOfTokens) public onlyOwner {
        uint totalSupply = totalSupply();
        require(_numberOfTokens <= _cardReserve, "Not enough cards left in reserve");
        require(totalSupply >= _mainCardCnt);
        require(totalSupply + _numberOfTokens <= _mainCardCnt + _cardReserve, "Purchase would exceed max supply of cards");
        for(uint i = 0; i < _numberOfTokens; i++) {
            uint mintIndex = totalSupply + i;
            _safeMint(_to, mintIndex);
        }
        _cardReserve -= _numberOfTokens;
    }
// Solidity 0.7.6
/**
 * Mint a number of cards straight in the caller's wallet.
 * @param _numberOfTokens: The number of tokens to mint.
 */
function mintCard(uint _numberOfTokens) public payable {
        uint totalSupply = totalSupply();
        require(_saleIsActive, "Sale must be active to mint a Card");
        require(_numberOfTokens < 21, "Can only mint 20 tokens at a time");
        require(totalSupply + _numberOfTokens <= _mainCardCnt, "Purchase would exceed max supply of cards");
        require(msg.value >= _cardPrice * _numberOfTokens, "Ether value sent is not correct");
        for(uint i = 0; i < _numberOfTokens; i++) {
            uint mintIndex = totalSupply + i;
            _safeMint(msg.sender, mintIndex);
        }
    }
// Solidity 0.4.24
/// @return id of new user
function register() public payable onlyNotExistingUser returns(uint256) {
        require(addressToUser[msg.sender] == 0);

        uint256 index = users.push(User(msg.sender, msg.value, 0, 0, new uint256[](4), new uint256[](referralLevelsCount))) - 1;
        addressToUser[msg.sender] = index;
        totalUsers++;

        emit CreateUser(index, msg.sender, msg.value);
        return index;
    }
// Solidity 0.4.24
/// @notice update referrersByLevel and referralsByLevel of new user
/// @param _newUserId the ID of the new user
/// @param _refUserId the ID of the user who gets the affiliate fee
function _updateReferrals(uint256 _newUserId, uint256 _refUserId) private {
        if (_newUserId == _refUserId) return;
        users[_newUserId].referrersByLevel[0] = _refUserId;

        for (uint i = 1; i < referralLevelsCount; i++) {
            uint256 _refId = users[_refUserId].referrersByLevel[i - 1];
            users[_newUserId].referrersByLevel[i] = _refId;
            users[_refId].referralsByLevel[uint8(i)].push(_newUserId);
        }

        users[_refUserId].referralsByLevel[0].push(_newUserId);
    }
// Solidity 0.4.24
/// @notice distribute value of tx to referrers of user
/// @param _userId the ID of the user who gets the affiliate fee
/// @param _sum value of ethereum for distribute to referrers of user
function _distributeReferrers(uint256 _userId, uint256 _sum) private {
        uint256[] memory referrers = users[_userId].referrersByLevel;

        for (uint i = 0; i < referralLevelsCount; i++) {
            uint256 referrerId = referrers[i];

            if (referrers[i] == 0) break;
            if (users[referrerId].totalPay < minSumReferral) continue;

            uint16[] memory percents = getReferralPercents(users[referrerId].totalPay);
            uint256 value = _sum * percents[i] / 10000;
            users[referrerId].balance = users[referrerId].balance.add(value);
            users[referrerId].referrersReceived = users[referrerId].referrersReceived.add(value);

            emit ReferrerDistribute(_userId, referrerId, value);
        }
    }
// Solidity 0.4.24
/// @notice deposit ethereum for user
/// @return balance value of user
function deposit() public payable onlyExistingUser returns(uint256) {
        require(msg.value > minSumDeposit, "Deposit does not enough");
        uint256 userId = addressToUser[msg.sender];
        users[userId].balance = users[userId].balance.add(msg.value);
        totalDeposit += msg.value;

        // distribute
        _distributeInvestment(msg.value);
        _updateLeaders(msg.sender, msg.value);

        emit Deposit(userId, msg.value);
        return users[userId].balance;
    }
// Solidity 0.4.24
/// @notice mechanics of buying any factory
/// @param _type type of factory needed
/// @return id of new factory
function buyFactory(FactoryType _type) public payable onlyExistingUser returns (uint256) {
        uint256 userId = addressToUser[msg.sender];

        // if user not registered
        if (addressToUser[msg.sender] == 0)
            userId = register();

        return _paymentProceed(userId, Factory(_type, 0, now));
    }
// Solidity 0.4.11
//This function is called when Ether is sent to the contract address
//Even if 0 ether is sent.
function () payable {
	    
	    uint256 tryAmount = div((mul(msg.value, rate)), 1 ether);                   //Don't let people buy more tokens than there are.
	    
		if (msg.value == 0 || msg.value < 0 || balanceOf(owner) < tryAmount) {		//If zero ether is sent, kill. Do nothing. 
			throw;
		}
		
	    amount = 0;									                //set the 'amount' var back to zero
		amount = div((mul(msg.value, rate)), 1 ether);				//take sent ether, multiply it by the rate then divide by 1 ether.
		transferFrom(owner, msg.sender, amount);                    //Send tokens to buyer
		amount = 0;									                //set the 'amount' var back to zero
		
		
		owner.transfer(msg.value);					                //Send the ETH to contract owner.

	}