lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.6.11
// Calculate a new stake based on the snapshots of the totalStakes and totalCollateral taken at the last liquidation
function _computeNewStake(uint _coll) internal view returns (uint) {
        uint stake;
        if (totalCollateralSnapshot == 0) {
            stake = _coll;
        } else {
            /*
            * The following assert() holds true because:
            * - The system always contains >= 1 trove
            * - When we close or liquidate a trove, we redistribute the pending rewards, so if all troves were closed/liquidated,
            * rewards would’ve been emptied and totalCollateralSnapshot would be zero too.
            */
            assert(totalStakesSnapshot > 0);
            stake = _coll.mul(totalStakesSnapshot).div(totalCollateralSnapshot);
        }
        return stake;
    }
// Solidity 0.6.11
/*
 * Remove a Trove owner from the TroveOwners array, not preserving array order. Removing owner 'B' does the following:
 * [A B C D E] => [A E C D], and updates E's Trove struct to point to its new array index.
 */
function _removeTroveOwner(address _borrower, uint TroveOwnersArrayLength) internal {
        Status troveStatus = Troves[_borrower].status;
        // It’s set in caller function `_closeTrove`
        assert(troveStatus != Status.nonExistent && troveStatus != Status.active);

        uint128 index = Troves[_borrower].arrayIndex;
        uint length = TroveOwnersArrayLength;
        uint idxLast = length.sub(1);

        assert(index <= idxLast);

        address addressToMove = TroveOwners[idxLast];

        TroveOwners[index] = addressToMove;
        Troves[addressToMove].arrayIndex = index;
        emit TroveIndexUpdated(addressToMove, index);

        TroveOwners.pop();
    }
// Solidity 0.6.11
/*
 * This function has two impacts on the baseRate state variable:
 * 1) decays the baseRate based on time passed since last redemption or LUSD borrowing operation.
 * then,
 * 2) increases the baseRate based on the amount redeemed, as a proportion of total supply
 */
function _updateBaseRateFromRedemption(uint _ETHDrawn,  uint _price, uint _totalLUSDSupply) internal returns (uint) {
        uint decayedBaseRate = _calcDecayedBaseRate();

        /* Convert the drawn ETH back to LUSD at face value rate (1 LUSD:1 USD), in order to get
        * the fraction of total supply that was redeemed at face value. */
        uint redeemedLUSDFraction = _ETHDrawn.mul(_price).div(_totalLUSDSupply);

        uint newBaseRate = decayedBaseRate.add(redeemedLUSDFraction.div(BETA));
        newBaseRate = LiquityMath._min(newBaseRate, DECIMAL_PRECISION); // cap baseRate at a maximum of 100%
        //assert(newBaseRate <= DECIMAL_PRECISION); // This is already enforced in the line above
        assert(newBaseRate > 0); // Base rate is always non-zero after redemption

        // Update the baseRate state variable
        baseRate = newBaseRate;
        emit BaseRateUpdated(newBaseRate);
        
        _updateLastFeeOpTime();

        return newBaseRate;
    }
// Solidity 0.7.6
/**
 @notice find the integer part of log2(p/q)
 => find largest x s.t p >= q * 2^x
 => find largest x s.t 2^x <= p / q
 */
function log2Int(uint256 _p, uint256 _q) internal pure returns (uint256) {
        uint256 res = 0;
        uint256 remain = _p / _q;
        while (remain > 0) {
            res++;
            remain /= 2;
        }
        return res - 1;
    }
// Solidity 0.7.6
/**
 @notice log2 for a number that it in [1,2)
 @dev _x is FP, return a FP
 @dev function is from Kyber. Long modified the condition to be (_x >= one) && (_x < two)
 to avoid the case where x = 2 may lead to incorrect result
 */
function log2ForSmallNumber(uint256 _x) internal pure returns (uint256) {
        uint256 res = 0;
        uint256 one = (uint256(1) << PRECISION_BITS);
        uint256 two = 2 * one;
        uint256 addition = one;

        require((_x >= one) && (_x < two), "MATH_ERROR");
        require(PRECISION_BITS < 125, "MATH_ERROR");

        for (uint256 i = PRECISION_BITS; i > 0; i--) {
            _x = (_x * _x) / one;
            addition = addition / 2;
            if (_x >= two) {
                _x = _x / 2;
                res += addition;
            }
        }

        return res;
    }
// Solidity 0.7.6
/**
 @notice log2 of (p/q). returns result in FP form
 @dev function is from Kyber.
 @dev _p & _q is FP, return a FP
 */
function logBase2(uint256 _p, uint256 _q) internal pure returns (uint256) {
        uint256 n = 0;

        if (_p > _q) {
            n = log2Int(_p, _q);
        }

        require(n * RONE <= BIG_NUMBER, "MATH_ERROR");
        require(!checkMultOverflow(_p, RONE), "MATH_ERROR");
        require(!checkMultOverflow(n, RONE), "MATH_ERROR");
        require(!checkMultOverflow(uint256(1) << n, _q), "MATH_ERROR");

        uint256 y = (_p * RONE) / (_q * (uint256(1) << n));
        uint256 log2Small = log2ForSmallNumber(y);

        assert(log2Small <= BIG_NUMBER);

        return n * RONE + log2Small;
    }
// Solidity 0.7.6
/**
 @notice calculate ln(p/q). returned result >= 0
 @dev function is from Kyber.
 @dev _p & _q is FP, return a FP
 */
function ln(uint256 p, uint256 q) internal pure returns (uint256) {
        uint256 ln2Numerator = 6931471805599453094172;
        uint256 ln2Denomerator = 10000000000000000000000;

        uint256 log2x = logBase2(p, q);

        require(!checkMultOverflow(ln2Numerator, log2x), "MATH_ERROR");

        return (ln2Numerator * log2x) / ln2Denomerator;
    }
// Solidity 0.7.6
/**
 @notice return e^exp in FP form
 @dev estimation by formula at http://pages.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/exp.html
 the function is based on exp function of:
 https://github.com/NovakDistributed/macroverse/blob/master/contracts/RealMath.sol
 @dev the function is expected to converge quite fast, after about 20 iteration
 @dev exp is a FP, return a FP
 */
function rpowe(uint256 exp) internal pure returns (uint256) {
        uint256 res = 0;

        uint256 curTerm = RONE;

        for (uint256 n = 0; ; n++) {
            res += curTerm;
            curTerm = rmul(curTerm, rdiv(exp, toFP(n + 1)));
            if (curTerm == 0) {
                break;
            }
            if (n == 500) {
                /*
                testing shows that in the most extreme case, it will take 430 turns to converge.
                however, it's expected that the numbers will not exceed 2^120 in normal situation
                the most extreme case is rpow((1<<256)-1,(1<<40)-1) (equal to rpow((2^256-1)/2^40,0.99..9))
                */
                revert("RPOWE_SLOW_CONVERGE");
            }
        }

        return res;
    }
// Solidity 0.7.6
/**
 @notice return base^exp with base in FP form and exp in Int
 @dev this function use a technique called: exponentiating by squaring
 complexity O(log(q))
 @dev function is from Kyber.
 @dev base is a FP, exp is an Int, return a FP
 */
function rpowi(uint256 base, uint256 exp) internal pure returns (uint256) {
        uint256 res = exp % 2 != 0 ? base : RONE;

        for (exp /= 2; exp != 0; exp /= 2) {
            base = rmul(base, base);

            if (exp % 2 != 0) {
                res = rmul(res, base);
            }
        }
        return res;
    }
// Solidity 0.7.6
/**
 @dev y is an Int, returns an Int
 @dev babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
 @dev from Uniswap
 */
function sqrt(uint256 y) internal pure returns (uint256 z) {
        if (y > 3) {
            z = y;
            uint256 x = y / 2 + 1;
            while (x < z) {
                z = x;
                x = (y / x + x) / 2;
            }
        } else if (y != 0) {
            z = 1;
        }
    }
// Solidity 0.5.2
/**
 * @dev update the balance of a type provided in _binBalances
 * @param _binBalances Uint256 containing the balances of objects
 * @param _index Index of the object in the provided bin
 * @param _amount Value to update the type balance
 * @param _operation Which operation to conduct :
 *     Operations.REPLACE : Replace type balance with _amount
 *     Operations.ADD     : ADD _amount to type balance
 *     Operations.SUB     : Substract _amount from type balance
 */
function updateTokenBalance(
    uint256 _binBalances,
    uint256 _index,
    uint256 _amount,
    Operations _operation) internal pure returns (uint256 newBinBalance)
  {
    uint256 objectBalance = 0;
    if (_operation == Operations.ADD) {
        objectBalance = getValueInBin(_binBalances, _index);
        newBinBalance = writeValueInBin(_binBalances, _index, objectBalance.add(_amount));
    } else if (_operation == Operations.SUB) {
        objectBalance = getValueInBin(_binBalances, _index);
        newBinBalance = writeValueInBin(_binBalances, _index, objectBalance.sub(_amount));
    } else if (_operation == Operations.REPLACE) {
        newBinBalance = writeValueInBin(_binBalances, _index, _amount);
    } else {
      revert("Invalid operation"); // Bad operation
    }

    return newBinBalance;
  }
// Solidity 0.5.2
/*
 * @dev return value in _binValue at position _index
 * @param _binValue uint256 containing the balances of TYPES_PER_UINT256 types
 * @param _index index at which to retrieve value
 * @return Value at given _index in _bin
 */
function getValueInBin(uint256 _binValue, uint256 _index) internal pure returns (uint256) {

    // Mask to retrieve data for a given binData
    uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1;

    // Shift amount
    uint256 rightShift = 256 - TYPES_BITS_SIZE * (_index + 1);
    return (_binValue >> rightShift) & mask;
  }
// Solidity 0.5.2
// Make public for testing
function recover(address token, uint256[] memory auctionData, uint256[] memory ids, uint256[] memory amounts, bytes memory signature) internal view returns (address) {
        return SigUtil.recover(
            // This recreates the message that was signed on the client.
            keccak256(abi.encodePacked("\x19\x01", domainSeparator(), hashAuction(token, auctionData, ids, amounts))), 
            signature
        );
    }
// Solidity 0.5.2
// function sendERC777Tokens(address _from, address _to, ERC777 _tokenContract, uint256 _amount, bytes calldata _data) external {
//     require(msg.sender == address(this), "can only be called by own");
//     _tokenContract.operatorSend(_from, _to, _amount, _data);
// }
// TODO safe /unsafe version
// function sendERC1155Tokens(address _from, address _to, ERC1155 _tokenContract, uint256 _tokenType, uint256 _amount, bytes calldata _data) external {
//     require(msg.sender == address(this), "can only be called by own");
//     _tokenContract.transfer...(_from, _to, _amount, _data);
// }
// TODO safe /unsafe version
// function sendERC721Tokens(address _from, address _to, ERC721 _tokenContract, uint256 _tokenType, bytes calldata _data) external {
//     require(msg.sender == address(this), "can only be called by own");
//     _tokenContract.transferFrom(_from, _to, _amount, _data); 
// }
function executeERC20MetaTx(
        address _from,
        address _to,  
        address _gasToken,
        bytes calldata _data,
        uint256[4] calldata params, // _nonce, _gasPrice, _txGas, _tokenGasPrice
        address _relayer,
        bytes calldata _sig,
        address _tokenReceiver,
        bool signedOnBehalf
    ) external returns (bool, bytes memory) {
        require(msg.sender != address(this), "can only be called externaly");
        uint256 initialGas = gasleft();
        ensureParametersValidity(_from, _gasToken, params, _relayer);
        ensureCorrectSigner(_from, _to, _gasToken, _data, params, _relayer, _sig, ERC20METATRANSACTION_TYPEHASH, signedOnBehalf);
        return performERC20MetaTx(_from, _to, _gasToken, _data, params, initialGas, _tokenReceiver);
    }
// Solidity 0.5.2
//override to block from emitting Transfer when not mErc20compatible
function _send(
        address _operator,
        address _from,
        address _to,
        uint256 _amount,
        bytes memory _data,
        bytes memory _operatorData,
        bool _preventLocking
    )
        internal
    {
        callSender(_operator, _from, _to, _amount, _data, _operatorData);

        require(_to != address(0), "Cannot send to 0x0");
        require(mBalances[_from] >= _amount, "Not enough funds");

        mBalances[_from] = mBalances[_from] -= _amount;
        mBalances[_to] = mBalances[_to] += _amount;

        callRecipient(_operator, _from, _to, _amount, _data, _operatorData, _preventLocking);

        emit Sent(_operator, _from, _to, _amount, _data, _operatorData);
    }
// Solidity 0.8.10
/**
 * @dev See {IBEP1155MetadataURI-uri}.
 *
 * This implementation returns the same URI for *all* token types. It relies
 * on the token type ID substitution mechanism
 * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
 *
 * Clients calling this function must replace the `\{id\}` substring with the
 * actual token type ID.
 */
function uri(uint256 tokenId)
        public
        view
        virtual
        override
        returns (string memory ipfsmetadata)
    {
        // return _uri;
        Metadata memory date = token_id[tokenId];
        ipfsmetadata = date.ipfsmetadata;
        // string memory ipfsmetadata = getmetadata(tokenId);

        return ipfsmetadata;
    }
// Solidity 0.8.10
/**
 * @dev See {IBEP1155-safeTransferFrom}.
 */
function safeTransferFrom(
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes memory data
    ) public virtual override {
        require(
            from == _msgSender() || isApprovedForAll(from, _msgSender()),
            "BEP1155: caller is not owner nor approved"
        );
        _safeTransferFrom(from, to, id, amount, data);
    }
// Solidity 0.8.10
/**
 * @dev See {IBEP1155-safeBatchTransferFrom}.
 */
function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) public virtual override {
        require(
            from == _msgSender() || isApprovedForAll(from, address(this)),
            "BEP1155: transfer caller is not owner nor approved"
        );
        _safeBatchTransferFrom(from, to, ids, amounts, data);
    }
// Solidity 0.8.10
/**
 * @dev xref:ROOT:BEP1155.adoc#batch-operations[Batched] version of {_burn}.
 *
 * Requirements:
 *
 * - `ids` and `amounts` must have the same length.
 */
function _burnBatch(
        address account,
        uint256[] memory ids,
        uint256[] memory amounts
    ) internal virtual {
        require(account != address(0), "BEP1155: burn from the zero address");
        require(
            ids.length == amounts.length,
            "BEP1155: ids and amounts length mismatch"
        );

        address operator = _msgSender();

        _beforeTokenTransfer(operator, account, address(0), ids, amounts, "");

        for (uint256 i = 0; i < ids.length; i++) {
            uint256 id = ids[i];
            uint256 amount = amounts[i];

            uint256 accountBalance = _balances[id][account];
            require(
                accountBalance >= amount,
                "BEP1155: burn amount exceeds balance"
            );
            unchecked {
                _balances[id][account] = accountBalance - amount;
            }
        }

        emit TransferBatch(operator, account, address(0), ids, amounts);
    }
// Solidity 0.8.10
// BNB TRANSFER PURCHASE
function saleToken(
        address payable from,
        uint256 tokenId,
        uint256 amount,
        uint256 nooftoken
    ) public payable {
        require(
            amount == order_place[from][tokenId].price.mul(nooftoken),
            "Invalid Balance"
        );
        _saleToken(from, tokenId, amount, "BNB");
        _setApprovalForAll(from, msg.sender, true);
        saleTokenTransfer(from, tokenId, nooftoken);
    }
// Solidity 0.5.2
// Note that address recovered from signatures must be strictly increasing, in order to prevent duplicates
function execute(uint8[] memory sigV, bytes32[] memory sigR, bytes32[] memory sigS, address destination, uint value, bytes memory data, address executor, uint gasLimit) public {
        require(sigR.length == threshold);
        require(sigR.length == sigS.length && sigR.length == sigV.length);
        require(executor == msg.sender || executor == address(0));

        bytes32 txInputHash = keccak256(abi.encodePacked(
            address(this),
            TXTYPE_HASH,
            SALT,
            destination,
            value,
            keccak256(data),
            nonce,
            executor,
            gasLimit
        ));
        bytes32 totalHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", txInputHash));

        address lastAdd = address(0); // cannot have address(0) as an owner
        for (uint i = 0; i < threshold; i++) {
            address recovered = ecrecover(totalHash, sigV[i], sigR[i], sigS[i]);
            require(recovered > lastAdd && isOwner[recovered]);
            lastAdd = recovered;
        }

        // If we make it here all signatures are accounted for.
        // The address.call() syntax is no longer recommended, see:
        // https://github.com/ethereum/solidity/issues/2884
        nonce = nonce + 1;
        bool success = false;
        assembly { success := call(gasLimit, destination, value, add(data, 0x20), mload(data), 0, 0) }
        require(success);
    }
// Solidity 0.4.18
// Process a transfer internally.
function xfer(address _from, address _to, uint _amount)
        internal
        returns (bool)
    {
        require(_amount <= balances[_from]);

        Transfer(_from, _to, _amount);

        // avoid wasting gas on 0 token transfers
        if(_amount == 0) return true;

        balances[_from] = balances[_from].sub(_amount);
        balances[_to]   = balances[_to].add(_amount);

        return true;
    }
// Solidity 0.4.18
// Calculates the sale and wholesale portion of tokens for a given value
// of wei at the time of calling.
function ethToTokens(uint _wei)
        public
        view
        returns (uint allTokens_, uint wholesaleTokens_)
    {
        // Get wholesale portion of ether and tokens
        uint wsValueLeft = wholeSaleValueLeft();
        uint wholesaleSpend =
                fundFailed() ? 0 :
                icoSucceeded ? 0 :
                now < START_DATE ? 0 :
                now > END_DATE ? 0 :
                // No wholesale purchse
                _wei < WHOLESALE_THRESHOLD ? 0 :
                // Total wholesale purchase
                _wei < wsValueLeft ?  _wei :
                // over funded for remaining wholesale tokens
                wsValueLeft;

        wholesaleTokens_ = wholesaleSpend
                .mul(RATE_WHOLESALE)
                .mul(TOKEN)
                .div(1 ether);

        // Remaining wei used to purchase retail tokens
        _wei = _wei.sub(wholesaleSpend);

        // Get retail rate
        uint saleRate = currentRate();

        allTokens_ = _wei
                .mul(saleRate)
                .mul(TOKEN)
                .div(1 ether)
                .add(wholesaleTokens_);
    }
// Solidity 0.4.18
// General addresses can purchase tokens during funding
function proxyPurchase(address _addr)
        public
        payable
        noReentry
        returns (bool)
    {
        require(!fundFailed());
        require(!icoSucceeded);
        require(now > START_DATE);
        require(now <= END_DATE);
        require(msg.value > 0);

        // Log ether deposit
        Deposit (_addr, msg.value);

        // Get ether to token conversion
        uint tokens;
        // Portion of tokens sold at wholesale rate
        uint wholesaleTokens;

        (tokens, wholesaleTokens) = ethToTokens(msg.value);

        // Block any failed token creation
        require(tokens > 0);

        // Prevent over subscribing
        require(balances[HUT34_RETAIN] - tokens >= RETAINED_TOKENS);

        // Adjust wholesale tokens left for sale
        if (wholesaleTokens != 0) {
            wholesaleLeft = wholesaleLeft.sub(wholesaleTokens);
        }

        // transfer tokens from fund wallet
        balances[HUT34_RETAIN] = balances[HUT34_RETAIN].sub(tokens);
        balances[_addr] = balances[_addr].add(tokens);
        Transfer(HUT34_RETAIN, _addr, tokens);

        // Update funds raised
        etherRaised = etherRaised.add(msg.value);

        // Update holder payments
        etherContributed[_addr] = etherContributed[_addr].add(msg.value);

        // Check KYC requirement
        if(etherContributed[_addr] >= KYC_THRESHOLD && !mustKyc[_addr]) {
            mustKyc[_addr] = true;
            Kyc(_addr, true);
        }

        return true;
    }
// Solidity 0.4.18
// Owner can sweep a successful funding to the fundWallet.
// Can be called repeatedly to recover errant ether which may have been
// `selfdestructed` to the contract
// Contract can be aborted up until this returns `true`
function finalizeICO()
        public
        onlyOwner
        preventReentry()
        returns (bool)
    {
        // Must have reached minimum cap
        require(fundRaised());

        // Set first vesting date (only once as this function can be called again)
        if(!icoSucceeded) {
            nextReleaseDate = now + VESTING_PERIOD;
        }

        // Set success flag;
        icoSucceeded = true;

        // Transfer % Developer commission
        uint devCommission = calcCommission();
        Withdrawal(this, COMMISSION_WALLET, devCommission);
        COMMISSION_WALLET.transfer(devCommission);

        // Remaining % to the fund wallet
        Withdrawal(this, HUT34_WALLET, this.balance);
        HUT34_WALLET.transfer(this.balance);
        return true;
    }
// Solidity 0.4.18
// Bulk refunds can be pushed from a failed ICO
function refundFor(address[] _addrs)
        public
        preventReentry()
        returns (bool)
    {
        require(fundFailed());
        uint i;
        uint len = _addrs.length;
        uint value;
        uint tokens;
        address addr;

        for (i; i < len; i++) {
            addr = _addrs[i];
            value = etherContributed[addr];
            tokens = balances[addr];
            if (tokens > 0) {
                // Return tokens
                // transfer tokens from fund wallet
                balances[HUT34_RETAIN] = balances[HUT34_RETAIN].add(tokens);
                delete balances[addr];
                Transfer(addr, HUT34_RETAIN, tokens);
            }

            if (value > 0) {
                // Refund ether contribution
                delete etherContributed[addr];
                delete mustKyc[addr];
                refunded = refunded.add(value);
                Withdrawal(this, addr, value);
                addr.transfer(value);
            }
        }
        return true;
    }
// Solidity 0.4.18
//
// ERC20 additional and overloaded functions
//
// Allows a sender to transfer tokens to an array of recipients
function transferToMany(address[] _addrs, uint[] _amounts)
        public
        noReentry
        returns (bool)
    {
        require(_addrs.length == _amounts.length);
        uint len = _addrs.length;
        for(uint i = 0; i < len; i++) {
            xfer(msg.sender, _addrs[i], _amounts[i]);
        }
        return true;
    }
// Solidity 0.4.18
// This will selfdestruct the contract on the condittion all have been
// processed.
function destroy()
        public
        noReentry
        onlyOwner
    {
        require(!__abortFuse);
        require(refunded == (etherRaised - PRESALE_ETH_RAISE));
        // Log burned tokens for complete ledger accounting on archival nodes
        Transfer(HUT34_RETAIN, 0x0, balances[HUT34_RETAIN]);
        Transfer(HUT34_VEST_ADDR, 0x0, VESTED_TOKENS);
        Transfer(PRESOLD_ADDRESS, 0x0, PRESOLD_TOKENS);
        // Garbage collect mapped state
        delete balances[HUT34_RETAIN];
        delete balances[PRESOLD_ADDRESS];
        selfdestruct(owner);
    }