lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.7.6
/**
 * Verifies a sequencer transaction, returning true if it was indeed included in the CTC
 * @param _transaction The transaction we are verifying inclusion of.
 * @param _txChainElement The chain element that the transaction is claimed to be a part of.
 * @param _batchHeader Header of the batch the transaction was included in.
 * @param _inclusionProof An inclusion proof into the CTC at a particular index.
 * @return True if the transaction was included in the specified location, else false.
 */
function _verifySequencerTransaction(
        Lib_OVMCodec.Transaction memory _transaction,
        Lib_OVMCodec.TransactionChainElement memory _txChainElement,
        Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
        Lib_OVMCodec.ChainInclusionProof memory _inclusionProof
    )
        internal
        view
        returns (
            bool
        )
    {
        OVM_ExecutionManager ovmExecutionManager = OVM_ExecutionManager(resolve("OVM_ExecutionManager"));
        uint256 gasLimit = ovmExecutionManager.getMaxTransactionGasLimit();
        bytes32 leafHash = _getSequencerLeafHash(_txChainElement);

        require(
            _verifyElement(
                leafHash,
                _batchHeader,
                _inclusionProof
            ),
            "Invalid Sequencer transaction inclusion proof."
        );

        require(
            _transaction.blockNumber        == _txChainElement.blockNumber
            && _transaction.timestamp       == _txChainElement.timestamp
            && _transaction.entrypoint      == resolve("OVM_DecompressionPrecompileAddress")
            && _transaction.gasLimit        == gasLimit
            && _transaction.l1TxOrigin      == address(0)
            && _transaction.l1QueueOrigin   == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE
            && keccak256(_transaction.data) == keccak256(_txChainElement.txData),
            "Invalid Sequencer transaction."
        );

        return true;
    }
// Solidity 0.7.6
/**
 * Verifies a queue transaction, returning true if it was indeed included in the CTC
 * @param _transaction The transaction we are verifying inclusion of.
 * @param _queueIndex The queueIndex of the queued transaction.
 * @param _batchHeader Header of the batch the transaction was included in.
 * @param _inclusionProof An inclusion proof into the CTC at a particular index (should point to queue tx).
 * @return True if the transaction was included in the specified location, else false.
 */
function _verifyQueueTransaction(
        Lib_OVMCodec.Transaction memory _transaction,
        uint256 _queueIndex,
        Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
        Lib_OVMCodec.ChainInclusionProof memory _inclusionProof
    )
        internal
        view
        returns (
            bool
        )
    {
        bytes32 leafHash = _getQueueLeafHash(_queueIndex);

        require(
            _verifyElement(
                leafHash,
                _batchHeader,
                _inclusionProof
            ),
            "Invalid Queue transaction inclusion proof."
        );

        bytes32 transactionHash = keccak256(
            abi.encode(
                _transaction.l1TxOrigin,
                _transaction.entrypoint,
                _transaction.gasLimit,
                _transaction.data
            )
        );

        Lib_OVMCodec.QueueElement memory el = getQueueElement(_queueIndex);
        require(
            el.queueRoot      == transactionHash
            && el.timestamp   == _transaction.timestamp
            && el.blockNumber == _transaction.blockNumber,
            "Invalid Queue transaction."
        );

        return true;
    }
// Solidity 0.7.6
/**
 * Verifies a batch inclusion proof.
 * @param _element Hash of the element to verify a proof for.
 * @param _batchHeader Header of the batch in which the element was included.
 * @param _proof Merkle inclusion proof for the element.
 */
function _verifyElement(
        bytes32 _element,
        Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
        Lib_OVMCodec.ChainInclusionProof memory _proof
    )
        internal
        view
        returns (
            bool
        )
    {
        require(
            Lib_OVMCodec.hashBatchHeader(_batchHeader) == batches().get(uint32(_batchHeader.batchIndex)),
            "Invalid batch header."
        );

        require(
            Lib_MerkleTree.verify(
                _batchHeader.batchRoot,
                _element,
                _proof.index,
                _proof.siblings,
                _batchHeader.batchSize
            ),
            "Invalid inclusion proof."
        );

        return true;
    }
// Solidity 0.4.24
/**
 * @notice Main entry point to initiate a rebase operation.
 *         The Orchestrator calls rebase on the policy and notifies downstream applications.
 *         Contracts are guarded from calling, to avoid flash loan attacks on liquidity
 *         providers.
 *         If a transaction in the transaction list reverts, it is swallowed and the remaining
 *         transactions are executed.
 */
function rebase()
        external
    {
        require(msg.sender == tx.origin);  // solhint-disable-line avoid-tx-origin

        UFragmentsPolicy.policyRebase();

        for (uint i = 0; i < transactions.length; i++) {
            Transaction storage t = transactions[i];
            if (t.enabled) {
                bool result =
                    externalCall(t.destination, t.data);
                if (!result) {
                    emit TransactionFailed(t.destination, i, t.data);
                    revert("Transaction Failed");
                }
            }
        }
    }
// Solidity 0.4.24
// msg.value is tip.
function accept(uint _brickId, address[] _winners, uint[] _weights) 
        public onlyBrickOwner(_brickId) 
        payable
        returns (bool success) 
    {
        uint total = getProvider(_brickId).accept(_brickId, _winners, _weights, msg.value);
        require(total > 0);
        for (uint i=0; i < _winners.length; i++) {
            _winners[i].transfer(total.mul(_weights[i]).div(DENOMINATOR));    
        }     

        emit WorkAccepted(_brickId, _winners);
        return true;   
    }
// Solidity 0.4.23
/**
 * Burn extra tokens from a balance.
 *
 */
function burn(uint burnAmount) public {
    address burner = msg.sender;
    balances[burner] = balances[burner].sub(burnAmount);
    totalSupply_ = totalSupply_.sub(burnAmount);
    emit Burned(burner, burnAmount);

    // Inform the blockchain explores that track the
    // balances only by a transfer event that the balance in this
    // address has decreased
    emit Transfer(burner, BURN_ADDRESS, burnAmount);
  }
// Solidity 0.4.23
/**
 * Create new tokens and allocate them to an address..
 *
 * Only callably by a crowdsale contract (mint agent).
 */
function mint(address receiver, uint amount) onlyMintAgent canMint public {
    totalSupply_ = totalSupply_.plus(amount);
    balances[receiver] = balances[receiver].plus(amount);

    // This will make the mint transaction apper in EtherScan.io
    // We can remove this after there is a standardized minting event
    emit Transfer(0, receiver, amount);
  }
// Solidity 0.6.6
/* Factory */
function _mintCreate(address _owner, bytes memory _args)
	internal returns (uint256)
	{
		// Create entry (proxy)
		address entry = Create2.deploy(0, keccak256(abi.encodePacked(_args, _owner)), proxyCode);
		// Initialize entry (casting to address payable is a pain in ^0.5.0)
		InitializableUpgradeabilityProxy(payable(entry)).initialize(master, _args);
		// Mint corresponding token
		_mint(_owner, uint256(entry));
		return uint256(entry);
	}
// Solidity 0.6.12
/**
 * @dev Return the approx logarithm of a value with log(x) where x <= 1.1.
 * All values are in integers with (1e18 == 1.0).
 *
 * Requirements:
 *
 * - input value x must be greater than 1e18
 */
function _logApprox(uint256 x) internal pure returns (uint256 y) {
        uint256 one = W_ONE;

        require(x >= one, "logApprox: x must >= 1");

        uint256 z = x - one;
        uint256 zz = z.mul(z).div(one);
        uint256 zzz = zz.mul(z).div(one);
        uint256 zzzz = zzz.mul(z).div(one);
        uint256 zzzzz = zzzz.mul(z).div(one);
        return z.sub(zz.div(2)).add(zzz.div(3)).sub(zzzz.div(4)).add(zzzzz.div(5));
    }
// Solidity 0.6.12
/**
 * Return weights and cached balances of all tokens
 * Note that the cached balance does not include the accrued interest since last rebalance.
 */
function _getBalancesAndWeights()
        internal
        view
        returns (uint256[] memory balances, uint256[] memory softWeights, uint256[] memory hardWeights, uint256 totalBalance)
    {
        uint256 ntokens = _ntokens;
        balances = new uint256[](ntokens);
        softWeights = new uint256[](ntokens);
        hardWeights = new uint256[](ntokens);
        totalBalance = 0;
        for (uint8 i = 0; i < ntokens; i++) {
            uint256 info = _tokenInfos[i];
            balances[i] = _getCashBalance(info);
            if (_isYEnabled(info)) {
                balances[i] = balances[i].add(_yBalances[i]);
            }
            totalBalance = totalBalance.add(balances[i]);
            softWeights[i] = _getSoftWeight(info);
            hardWeights[i] = _getHardWeight(info);
        }
    }
// Solidity 0.6.12
/**************************************************************************************
 * Methods for rebalance cash reserve
 * After rebalancing, we will have cash reserve equaling to 10% of total balance
 * There are two conditions to trigger a rebalancing
 * - if there is insufficient cash for withdraw; or
 * - if the cash reserve is greater than 20% of total balance.
 * Note that we use a cached version of total balance to avoid high gas cost on calling
 * getPricePerFullShare().
 *************************************************************************************/
function _updateTotalBalanceWithNewYBalance(
        uint256 tid,
        uint256 yBalanceNormalizedNew
    )
        internal
    {
        uint256 adminFee = 0;
        uint256 yBalanceNormalizedOld = _yBalances[tid];
        // They yBalance should not be decreasing, but just in case,
        if (yBalanceNormalizedNew >= yBalanceNormalizedOld) {
            adminFee = (yBalanceNormalizedNew - yBalanceNormalizedOld).mul(_adminInterestPct).div(W_ONE);
        }
        _totalBalance = _totalBalance
            .sub(yBalanceNormalizedOld)
            .add(yBalanceNormalizedNew)
            .sub(adminFee);
    }
// Solidity 0.6.12
/*
 * @dev Rebalance the cash reserve so that
 * cash reserve consists of 10% of total balance after substracting amountUnnormalized.
 *
 * Assume that current cash reserve < amountUnnormalized.
 */
function _rebalanceReserveSubstract(
        uint256 info,
        uint256 amountUnnormalized
    )
        internal
    {
        require(_isYEnabled(info), "yToken must be enabled for rebalancing");

        uint256 pricePerShare;
        uint256 cashUnnormalized;
        uint256 yBalanceUnnormalized;
        (pricePerShare, cashUnnormalized, yBalanceUnnormalized) = _getBalanceDetail(info);

        // Update _totalBalance with interest
        _updateTotalBalanceWithNewYBalance(
            _getTID(info),
            yBalanceUnnormalized.mul(_normalizeBalance(info))
        );

        // Evaluate the shares to withdraw so that cash = 10% of total
        uint256 expectedWithdraw = cashUnnormalized.add(yBalanceUnnormalized).sub(
            amountUnnormalized).div(10).add(amountUnnormalized).sub(cashUnnormalized);
        if (expectedWithdraw == 0) {
            return;
        }

        // Withdraw +1 wei share to make sure actual withdraw >= expected.
        uint256 withdrawShares = expectedWithdraw.mul(W_ONE).div(pricePerShare).add(1);
        uint256 balanceBefore = IERC20(address(info)).balanceOf(address(this));
        YERC20(_yTokenAddresses[_getTID(info)]).withdraw(withdrawShares);
        uint256 actualWithdraw = IERC20(address(info)).balanceOf(address(this)).sub(balanceBefore);
        require(actualWithdraw >= expectedWithdraw, "insufficient cash withdrawn from yToken");
        _yBalances[_getTID(info)] = yBalanceUnnormalized.sub(actualWithdraw)
            .mul(_normalizeBalance(info));
    }
// Solidity 0.6.12
/* @dev Transfer the amount of token out.  Rebalance the cash reserve if needed */
function _transferOut(
        uint256 info,
        uint256 amountUnnormalized,
        uint256 adminFee
    )
        internal
    {
        uint256 amountNormalized = amountUnnormalized.mul(_normalizeBalance(info));
        if (_isYEnabled(info)) {
            if (IERC20(address(info)).balanceOf(address(this)) < amountUnnormalized) {
                _rebalanceReserveSubstract(info, amountUnnormalized);
            }
        }

        IERC20(address(info)).safeTransfer(
            msg.sender,
            amountUnnormalized
        );
        _totalBalance = _totalBalance
            .sub(amountNormalized)
            .sub(adminFee.mul(_normalizeBalance(info)));
    }
// Solidity 0.6.12
/*
 * @dev Given the token id and the amount to be deposited, return the amount of lp token
 */
function getMintAmount(
        uint256 bTokenIdx,
        uint256 bTokenAmount
    )
        public
        view
        returns (uint256 lpTokenAmount)
    {
        require(bTokenAmount > 0, "Amount must be greater than 0");

        uint256 info = _tokenInfos[bTokenIdx];
        require(info != 0, "Backed token is not found!");

        // Obtain normalized balances
        uint256 bTokenAmountNormalized = bTokenAmount.mul(_normalizeBalance(info));
        // Gas saving: Use cached totalBalance with accrued interest since last rebalance.
        uint256 totalBalance = _totalBalance;
        uint256 sTokenAmount = _getMintAmount(
            bTokenAmountNormalized,
            totalBalance,
            _getBalance(info),
            _getSoftWeight(info),
            _getHardWeight(info)
        );

        return sTokenAmount.mul(totalSupply()).div(totalBalance);
    }
// Solidity 0.6.12
/*
 * @dev Return number of sUSD that is needed to redeem corresponding amount of token for another
 *      token
 * Withdrawing a token will result in increased percentage of other tokens, where
 * the function is used to calculate the penalty incured by the increase of one token.
 * @param totalBalance - normalized amount of the sum of all tokens
 * @param tokenBlance - normalized amount of the balance of a non-withdrawn token
 * @param redeemAount - normalized amount of the token to be withdrawn
 * @param softWeight - percentage that will incur penalty if the resulting token percentage is greater
 * @param hardWeight - maximum percentage of the token
 */
function _redeemPenaltyFor(
        uint256 totalBalance,
        uint256 tokenBalance,
        uint256 redeemAmount,
        uint256 softWeight,
        uint256 hardWeight
    )
        internal
        pure
        returns (uint256)
    {
        uint256 newTotalBalance = totalBalance.sub(redeemAmount);

        /* Soft weight is satisfied.  No penalty is incurred */
        if (tokenBalance.mul(W_ONE) <= newTotalBalance.mul(softWeight)) {
            return 0;
        }

        require (
            tokenBalance.mul(W_ONE) <= newTotalBalance.mul(hardWeight),
            "redeem: hard-limit weight is broken"
        );

        uint256 bx = 0;
        // Evaluate the beginning of the integral for broken soft weight
        if (tokenBalance.mul(W_ONE) < totalBalance.mul(softWeight)) {
            bx = totalBalance.sub(tokenBalance.mul(W_ONE).div(softWeight));
        }

        // x * (w - v) / w / w * ln(1 + (tx - bx) * w / (w * (S - tx) - x)) - (tx - bx) * v / w
        uint256 tdelta = tokenBalance.mul(
            _log(W_ONE.add(redeemAmount.sub(bx).mul(hardWeight).div(hardWeight.mul(newTotalBalance).div(W_ONE).sub(tokenBalance)))));
        uint256 s1 = tdelta.mul(hardWeight.sub(softWeight))
            .div(hardWeight).div(hardWeight);
        uint256 s2 = redeemAmount.sub(bx).mul(softWeight).div(hardWeight);
        return s1.sub(s2);
    }
// Solidity 0.6.12
/*
 * @dev Calculate the derivative of the penalty function.
 * Same parameters as _redeemPenaltyFor.
 */
function _redeemPenaltyDerivativeForOne(
        uint256 totalBalance,
        uint256 tokenBalance,
        uint256 redeemAmount,
        uint256 softWeight,
        uint256 hardWeight
    )
        internal
        pure
        returns (uint256)
    {
        uint256 dfx = W_ONE;
        uint256 newTotalBalance = totalBalance.sub(redeemAmount);

        /* Soft weight is satisfied.  No penalty is incurred */
        if (tokenBalance.mul(W_ONE) <= newTotalBalance.mul(softWeight)) {
            return dfx;
        }

        // dx = dx + x * (w - v) / (w * (S - tx) - x) / w - v / w
        return dfx.add(tokenBalance.mul(hardWeight.sub(softWeight))
            .div(hardWeight.mul(newTotalBalance).div(W_ONE).sub(tokenBalance)))
            .sub(softWeight.mul(W_ONE).div(hardWeight));
    }
// Solidity 0.6.12
/*
 * @dev Given the amount of sUSD to be redeemed, find the max token can be withdrawn
 * This function is for swap only.
 * @param tidOutBalance - the balance of the token to be withdrawn
 * @param totalBalance - total balance of all tokens
 * @param tidInBalance - the balance of the token to be deposited
 * @param sTokenAmount - the amount of sUSD to be redeemed
 * @param softWeight/hardWeight - normalized weights for the token to be withdrawn.
 */
function _redeemFindOne(
        uint256 tidOutBalance,
        uint256 totalBalance,
        uint256 tidInBalance,
        uint256 sTokenAmount,
        uint256 softWeight,
        uint256 hardWeight
    )
        internal
        pure
        returns (uint256)
    {
        uint256 redeemAmountNormalized = Math.min(
            sTokenAmount,
            tidOutBalance.mul(999).div(1000)
        );

        for (uint256 i = 0; i < 256; i++) {
            uint256 sNeeded = redeemAmountNormalized.add(
                _redeemPenaltyFor(
                    totalBalance,
                    tidInBalance,
                    redeemAmountNormalized,
                    softWeight,
                    hardWeight
                ));
            uint256 fx = 0;

            if (sNeeded > sTokenAmount) {
                fx = sNeeded - sTokenAmount;
            } else {
                fx = sTokenAmount - sNeeded;
            }

            // penalty < 1e-5 of out amount
            if (fx < redeemAmountNormalized / 100000) {
                require(redeemAmountNormalized <= sTokenAmount, "Redeem error: out amount > lp amount");
                require(redeemAmountNormalized <= tidOutBalance, "Redeem error: insufficient balance");
                return redeemAmountNormalized;
            }

            uint256 dfx = _redeemPenaltyDerivativeForOne(
                totalBalance,
                tidInBalance,
                redeemAmountNormalized,
                softWeight,
                hardWeight
            );

            if (sNeeded > sTokenAmount) {
                redeemAmountNormalized = redeemAmountNormalized.sub(fx.mul(W_ONE).div(dfx));
            } else {
                redeemAmountNormalized = redeemAmountNormalized.add(fx.mul(W_ONE).div(dfx));
            }
        }
        require (false, "cannot find proper resolution of fx");
    }
// Solidity 0.6.12
/*
 * @dev Given the amount of sUSD token to be redeemed, find the max token can be withdrawn
 * @param bTokenIdx - the id of the token to be withdrawn
 * @param sTokenAmount - the amount of sUSD token to be redeemed
 * @param totalBalance - total balance of all tokens
 * @param balances/softWeight/hardWeight - normalized balances/weights of all tokens
 */
function _redeemFind(
        uint256 bTokenIdx,
        uint256 sTokenAmount,
        uint256 totalBalance,
        uint256[] memory balances,
        uint256[] memory softWeights,
        uint256[] memory hardWeights
    )
        internal
        pure
        returns (uint256)
    {
        uint256 bTokenAmountNormalized = Math.min(
            sTokenAmount,
            balances[bTokenIdx].mul(999).div(1000)
        );

        for (uint256 i = 0; i < 256; i++) {
            uint256 sNeeded = bTokenAmountNormalized.add(
                _redeemPenaltyForAll(
                    bTokenIdx,
                    totalBalance,
                    balances,
                    softWeights,
                    hardWeights,
                    bTokenAmountNormalized
                ));
            uint256 fx = 0;

            if (sNeeded > sTokenAmount) {
                fx = sNeeded - sTokenAmount;
            } else {
                fx = sTokenAmount - sNeeded;
            }

            // penalty < 1e-5 of out amount
            if (fx < bTokenAmountNormalized / 100000) {
                require(bTokenAmountNormalized <= sTokenAmount, "Redeem error: out amount > lp amount");
                require(bTokenAmountNormalized <= balances[bTokenIdx], "Redeem error: insufficient balance");
                return bTokenAmountNormalized;
            }

            uint256 dfx = _redeemPenaltyDerivativeForAll(
                bTokenIdx,
                totalBalance,
                balances,
                softWeights,
                hardWeights,
                bTokenAmountNormalized
            );

            if (sNeeded > sTokenAmount) {
                bTokenAmountNormalized = bTokenAmountNormalized.sub(fx.mul(W_ONE).div(dfx));
            } else {
                bTokenAmountNormalized = bTokenAmountNormalized.add(fx.mul(W_ONE).div(dfx));
            }
        }
        require (false, "cannot find proper resolution of fx");
    }
// Solidity 0.6.12
/*
 * @dev Given token id and LP token amount, return the max amount of token can be withdrawn
 * @param tid - the id of the token to be withdrawn
 * @param lpTokenAmount - the amount of LP token
 */
function _getRedeemByLpTokenAmount(
        uint256 tid,
        uint256 lpTokenAmount
    )
        internal
        view
        returns (uint256 bTokenAmount, uint256 totalBalance, uint256 adminFee)
    {
        require(lpTokenAmount > 0, "Amount must be greater than 0");

        uint256 info = _tokenInfos[tid];
        require(info != 0, "Backed token is not found!");

        // Obtain normalized balances.
        // Gas saving: Use cached balances/totalBalance without accrued interest since last rebalance.
        uint256[] memory balances;
        uint256[] memory softWeights;
        uint256[] memory hardWeights;
        (balances, softWeights, hardWeights, totalBalance) = _getBalancesAndWeights();
        bTokenAmount = _redeemFind(
            tid,
            lpTokenAmount.mul(totalBalance).div(totalSupply()),
            totalBalance,
            balances,
            softWeights,
            hardWeights
        ).div(_normalizeBalance(info));
        uint256 fee = bTokenAmount.mul(_redeemFee).div(W_ONE);
        adminFee = fee.mul(_adminFeePct).div(W_ONE);
        bTokenAmount = bTokenAmount.sub(fee);
    }