lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.8.0
/// @dev Hook that is called before any token transfer. This includes minting
function _beforeTokenTransfer(
        address from,
        address to,
        uint tokenId
    ) internal virtual override {
        super._beforeTokenTransfer(from, to, tokenId);

        if (from == address(0)) {
            assert(tokenId == _totalSupply); // Ensure token is minted sequentially
            _totalSupply += 1;
        } else if (from != to) {
            _removeTokenFromOwnerEnumeration(from, tokenId);
        }

        if (to == address(0)) {
            // do nothing
        } else if (to != from) {
            _addTokenToOwnerEnumeration(to, tokenId);
        }
    }
// Solidity 0.8.0
/**
 * @dev See {ERC721Enumerable-_removeTokenFromOwnerEnumeration}.
 * @param from address representing the previous owner of the given token ID
 * @param tokenId uint ID of the token to be removed from the tokens list of the given address
 */
function _removeTokenFromOwnerEnumeration(address from, uint tokenId) private {
        // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint lastTokenIndex = ERC721.balanceOf(from) - 1;
        uint tokenIndex = _ownedTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary
        if (tokenIndex != lastTokenIndex) {
            uint lastTokenId = _ownedTokens[from][lastTokenIndex];

            _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
            _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
        }

        // This also deletes the contents at the last position of the array
        delete _ownedTokensIndex[tokenId];
        delete _ownedTokens[from][lastTokenIndex];
    }
// Solidity 0.8.0
// #0 - #29: Reserved for giveaways and people who helped along the way
function reserveGiveaway(uint numWpunks) public onlyOwner {
        uint currentSupply = totalSupply();
        require(currentSupply + numWpunks <= 10, "Exceeded giveaway limit");
        for (uint index = 0; index < numWpunks; index++) {
            _safeMint(owner(), currentSupply + index);
        }
    }
// Solidity 0.7.5
/**
 @notice increases sKEEPER supply to increase staking balances relative to _profit
 @param _profit uint256
 @return uint256
 */
function rebase(uint256 _profit, uint _epoch) public onlyStakingContract() returns (uint256) {
        uint256 rebaseAmount;
        uint256 _circulatingSupply = circulatingSupply();

        if (_profit == 0) {
            emit LogSupply(_epoch, block.timestamp, _totalSupply);
            emit LogRebase(_epoch, 0, index());
            return _totalSupply;
        }
        else if (_circulatingSupply > 0) {
            rebaseAmount = _profit.mul(_totalSupply).div(_circulatingSupply);
        }
        else {
            rebaseAmount = _profit;
        }

        _totalSupply = _totalSupply.add(rebaseAmount);
        if (_totalSupply > MAX_SUPPLY) {
            _totalSupply = MAX_SUPPLY;
        }

        _gonsPerFragment = TOTAL_GONS.div(_totalSupply);
        _storeRebase(_circulatingSupply, _profit, _epoch);
        return _totalSupply;
    }
// Solidity 0.7.5
// Sets terms for multiple wallets
function setTermsMultiple(address[] calldata _vesters, uint[] calldata _amountCanClaims, uint[] calldata _rates ) external onlyOwner() returns ( bool ) {
        for (uint i=0; i < _vesters.length; i++) {
            terms[_vesters[i]].max = _amountCanClaims[i];
            terms[_vesters[i]].initPercent = _rates[i];
        }
        return true;
    }
// Solidity 0.7.5
// Allows wallet to redeem cKEEPER for KEEPER
function exercise( uint _amount, bool _stake, bool _wrap ) external returns ( bool ) {
        Term memory info = terms[ msg.sender ];
        require( redeemable( info ) >= _amount, 'Not enough vested' );
        require( info.max.sub( info.claimed ) >= _amount, 'Claimed over max' );

        uint usdcAmount = _amount.div(1e12);
        IERC20( USDC ).safeTransferFrom( msg.sender, address( this ), usdcAmount );
        IcKEEPER( cKEEPER ).burnFrom( msg.sender, _amount );

        IERC20( USDC ).approve( treasury, usdcAmount );
        uint KEEPERToSend = ITreasury( treasury ).deposit( usdcAmount, USDC, 0 );

        terms[ msg.sender ].claimed = info.claimed.add( _amount );

        if ( _stake ) {
            IERC20( KEEPER ).approve( staking, KEEPERToSend );
            IStaking( staking ).stake( KEEPERToSend, msg.sender, _wrap );
        } else {
            IERC20( KEEPER ).safeTransfer( msg.sender, KEEPERToSend );
        }

        return true;
    }
// Solidity 0.7.5
// Allows wallet to pull rights from an old address
function pullWalletChange( address _oldWallet ) external returns ( bool ) {
        require( walletChange[ _oldWallet ] == msg.sender, "wallet did not push" );
        walletChange[ _oldWallet ] = address(0);
        terms[ msg.sender ] = terms[ _oldWallet ];
        delete terms[ _oldWallet ];
        return true;
    }
// Solidity 0.7.5
// function updateTotalRedeemable() external {
//     require( msg.sender == redeemUpdater, "Only redeem updater can call." );
//     uint keeperBalance = KEEPER.balanceOf( address(this) );
//     uint newRedeemable = keeperBalance.add(totalRedeemed).mul(block.timestamp.sub(redeemableLastUpdated)).div(31536000);
//     totalRedeemable = totalRedeemable.add(newRedeemable);
//     if (totalRedeemable > keeperBalance ) {
//         totalRedeemable = keeperBalance;
//     }
//     redeemableLastUpdated = block.timestamp;
// }
// Allows wallet to redeem KEEPER
function redeem( uint _amount ) external returns ( bool ) {
        Term memory info = terms[ msg.sender ];
        require( redeemable( info ) >= _amount, 'Not enough vested' );
        KEEPER.safeTransfer(msg.sender, _amount);
        terms[ msg.sender ].claimed = info.claimed.add( _amount );
        totalRedeemed = totalRedeemed.add(_amount);
        emit KeeperRedeemed(msg.sender, _amount);
        return true;
    }
// Solidity 0.7.5
/**
 *  @notice calculate amount of KEEPER available for claim by depositor
 *  @param _depositor address
 *  @return pendingPayout_ uint
 */
function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) {
        uint percentVested = percentVestedFor( _depositor );
        uint payout = bondInfo[ _depositor ].payout;

        if ( percentVested >= 10000 ) {
            pendingPayout_ = payout;
        } else {
            pendingPayout_ = payout.mul( percentVested ).div( 10000 );
        }
    }
// Solidity 0.7.5
/**
 *  @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO
 *  @return bool
 */
function recoverLostToken( address _token ) external returns ( bool ) {
        require( _token != KEEPER );
        require( _token != principle );
        IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) );
        return true;
    }
// Solidity 0.4.24
/**
 * Allows for the transfer of MSTCOIN tokens from peer to peer. 
 *
 * @param _to The address of the receiver
 * @param _value The amount of tokens to send
 **/
function transfer(address _to, uint256 _value) public returns(bool) {
        require(balances[msg.sender] >= _value && _value > 0 && _to != 0x0);
        balances[msg.sender] = balances[msg.sender].sub(_value);
        balances[_to] = balances[_to].add(_value);
        Transfer(msg.sender, _to, _value);
        return true;
    }
// Solidity 0.4.24
/**
 * Allows for the transfer of tokens on the behalf of the owner given that the owner has
 * allowed it previously. 
 *
 * @param _from The address of the owner
 * @param _to The address of the recipient 
 * @param _value The amount of tokens to be sent
 **/
function transferFrom(address _from, address _to, uint256 _value) public  returns (bool) {
        require(allowances[_from][msg.sender] >= _value && _to != 0x0 && balances[_from] >= _value && _value > 0);
        balances[_from] = balances[_from].sub(_value);
        balances[_to] = balances[_to].add(_value);
        allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_value);
        Transfer(_from, _to, _value);
        return true;
    }
// Solidity 0.4.24
/**
 * Allows the owner of tokens to approve another to spend tokens on his or her behalf
 *
 * @param _spender The address which is being allowed to spend tokens on the owner' behalf
 * @param _value The amount of tokens to be sent
 **/
function approve(address _spender, uint256 _value) public returns (bool) {
        require(_spender != 0x0 && _value > 0);
        if(allowances[msg.sender][_spender] > 0 ) {
            allowances[msg.sender][_spender] = 0;
        }
        allowances[msg.sender][_spender] = _value;
        Approval(msg.sender, _spender, _value);
        return true;
    }
// Solidity 0.6.2
// Setup new addresses
function setup(address carMechanicsAddress, address payable walletAddress) public onlyOwner returns (bool) {
        
        // Should not set zero address
        require(carMechanicsAddress != address(0), "Should not set 0 address for car mechanics");
        require(walletAddress != address(0), "Should not set 0 address for wallet");

        // Save
        _carMechanicsContract = CarMechanics(carMechanicsAddress);
        _wallet = walletAddress;
    }
// Solidity 0.6.2
// Private function to keep tokens on auction array updated
function updateTokensOnAuction(uint256 tokenToRemove, uint256 tokenToAdd) internal {
        
        uint256 removeIndex = 0;

        // Find index for token to remove
        for (uint i = 0; i<_tokensOnAuction.length; i++) {
            if (_tokensOnAuction[i] == tokenToRemove) {
                removeIndex = i;
            }
        }
        
        // Set new token on index
        _tokensOnAuction[removeIndex] = tokenToAdd;

        // Event
        emit AuctionTokensChanged(tokenToRemove, tokenToAdd);
    }
// Solidity 0.6.2
//
// ******************* PRICE *******************
//
// Start price for car on auction
function carAuctionStartPrice(uint256 carId) public view returns(uint256) {

        // has auction started for this token?
        require(openAuctionForCar(carId) == true, "Car not on auction");

        uint256 decimalMultiplier = (uint256(10) ** uint256(18));

        // min_price + (token_id * 0.0001)        
        return _minPrice.add(carId.mul(decimalMultiplier).div(100000)); 
    }
// Solidity 0.6.2
// Current car price on auction - Helper
function carAuctionCurrentPriceHelper(uint256 nowTime, uint256 carId) public view returns(uint256) {

        // has auction started for this token?
        require(openAuctionForCar(carId) == true, "Car not on auction");
        
        // Get start and end price of the auction
        uint256 startPrice = carAuctionStartPrice(carId);
        
        // Calculate price reduction
        uint256 priceReductionPerSecond = carPriceReductionPerSecond(carId);
        
        // Calculate seconds the auction has been running
        uint256 carAuctionStartTime = _tokenAuctionStart[carId];
        uint256 secondsPassedInAuction = nowTime.sub(carAuctionStartTime);

        uint256 calculatedPrice = startPrice.sub(secondsPassedInAuction.mul(priceReductionPerSecond));

        if (calculatedPrice < _minPrice) {
            // Return minimum price
            return _minPrice;
        }
        
        // Return current price
        return calculatedPrice;
    }
// Solidity 0.6.2
// Private helper function
function carPriceReductionPerSecond(uint256 carId) internal view returns(uint256) {

        // has auction started for this token?
        require(openAuctionForCar(carId) == true, "Car not on auction");

        // Get start and end price of the auction
        uint256 startPrice = carAuctionStartPrice(carId);
        uint256 endPrice = _minPrice; 
        
        // Calculate price reduction
        uint256 priceReductionPerSecond = startPrice.sub(endPrice).div(_timePerAuction);

        return priceReductionPerSecond;
    }
// Solidity 0.4.18
//This notifies clients about the amount burnt
//Constructor function
function YourMomToken(string tokenName, string tokenSymbol, uint256 initialSupplyInEther) public {
		name = tokenName;								//Set the name for display purposes
		symbol = tokenSymbol;							//Set the symbol for display purposes
		decimals = 18;									//Amount of decimals for display purposes
		totalSupply = initialSupplyInEther * 10**18;	//Defines the initial supply as the total supply (in wei)
		balanceOf[msg.sender] = totalSupply;			//Give the creator all initial tokens
	}
// Solidity 0.7.0
// Deposit LP tokens to MasterUniverse for NOVA allocation.
function deposit(uint256 _pid, uint256 _amount) external {
        require(_pid < poolLength(), "bad pid");
        require(_amount > 0, "amount could'n be 0");
        require(_amount >= 0.1 ether, "amount could'n be lower than 0.1 LP token");

        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];

        updatePool(_pid);

        if (user.amount == 0) {
            user.lastStakedTime = block.timestamp; 
        }

        // they already staked so let's harvest
        if (user.amount > 0) {
            uint256 pending = user.plasmaPower.mul(pool.accNovaPerShare).div(1e12).sub(user.rewardDebt);
            if (pending > 0) {
                uint feesPercentage = calculateFeesPercentage(_pid, msg.sender);
                uint256 fees = pending.mul(feesPercentage).div(100);
                uint256 gain = pending.sub(fees);
                safeNovaTransfer(devaddr, fees);
                safeNovaTransfer(msg.sender, gain);
            }
        }

        if (_amount > 0) {
            pool.lpToken.safeTransferFrom(address(msg.sender),address(this),_amount);
            user.amount = user.amount.add(_amount);
            user.buffRate = calculateBuffRate(user.amount);
            uint prevPlasmaPower = user.plasmaPower;
            user.plasmaPower = user.amount.mul(user.buffRate);
            pool.totalPlasmaPower = pool.totalPlasmaPower.sub(prevPlasmaPower).add(user.plasmaPower);
        }

        user.rewardDebt = user.plasmaPower.mul(pool.accNovaPerShare).div(1e12);
        emit Deposit(msg.sender, _pid, _amount);
    }
// Solidity 0.4.19
// Pixels are represented using 4-bits.  We pack 2 pixels into one byte like so:
// [left_pixel|right_pixel]
// To set these bytes, we use bitwise operations to change either the upper or
// lower half of a packed byte.
// [index] is the index of the pixel; not the byte
// [color] is a 4-bit integer; the upper 4 bits of the uint8 are discarded.
function set(uint32 index, uint8 color) public payable {
        require(index < 1000000);
        require(msg.value >= feeWei);

        uint32 packedByteIndex = index / 2;
        byte currentByte = packedBytes[packedByteIndex];
        bool left = index % 2 == 0;

        byte newByte;
        if (left) {
            // clear upper 4 bits of existing byte
            // OR with new byte shifted left 4 bits
            newByte = (currentByte & hex'0f') | bytes1(color * 2 ** 4);
        } else {
            // clear lower 4 bits of existing byte
            // OR with with new color, with upper 4 bits cleared
            newByte = (currentByte & hex'f0') | (bytes1(color) & hex'0f');
        }

        packedBytes[packedByteIndex] = newByte;
        PixelUpdate(index, color);
    }
// Solidity 0.7.5
/**
 @notice allow approved address to deposit an asset for KEEPER
 @param _amount uint
 @param _token address
 @param _profit uint
 @return send_ uint
 */
function deposit( uint _amount, address _token, uint _profit ) external returns ( uint send_ ) {
        require( isReserveToken[ _token ] || isLiquidityToken[ _token ], "Not accepted" );
        IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount );

        if ( isReserveToken[ _token ] ) {
            require( isReserveDepositor[ msg.sender ], "Not approved" );
        } else {
            require( isLiquidityDepositor[ msg.sender ], "Not approved" );
        }

        uint value = valueOfToken(_token, _amount);
        // mint KEEPER needed and store amount of rewards for distribution
        send_ = value.sub( _profit );
        KEEPER.mint( msg.sender, send_ );

        totalReserves = totalReserves.add( value );
        emit ReservesUpdated( totalReserves );
        emit Deposit( _token, _amount, value );
    }
// Solidity 0.7.5
/**
 @notice allow approved address to burn KEEPER for reserves
 @param _amount uint
 @param _token address
 */
function withdraw( uint _amount, address _token ) external {
        require( isReserveToken[ _token ], "Not accepted" ); // Only reserves can be used for redemptions
        require( isReserveSpender[ msg.sender ] == true, "Not approved" );

        uint value = valueOfToken( _token, _amount );
        KEEPER.burnFrom( msg.sender, value );

        totalReserves = totalReserves.sub( value );
        emit ReservesUpdated( totalReserves );

        IERC20Extended( _token ).safeTransfer( msg.sender, _amount );

        emit Withdrawal( _token, _amount, value );
    }
// Solidity 0.7.5
/**
 @notice allow approved address to repay borrowed reserves with KEEPER
 @param _amount uint
 */
function repayDebtWithKEEPER( uint _amount ) external {
        require( isDebtor[ msg.sender ], "Not approved" );
        KEEPER.burnFrom( msg.sender, _amount );
        debtorBalance[ msg.sender ] = debtorBalance[ msg.sender ].sub( _amount );
        totalDebt = totalDebt.sub( _amount );
        emit RepayDebt( msg.sender, address(KEEPER), _amount, _amount );
    }
// Solidity 0.7.5
/**
 @notice returns KEEPER valuation of asset
 @param _token address
 @param _amount uint
 @return value_ uint
 */
function valueOfToken( address _token, uint _amount ) public view returns ( uint value_ ) {
        if ( isReserveToken[ _token ] ) {
            // convert amount to match KEEPER decimals
            value_ = _amount.mul( 10 ** keeperDecimals ).div( 10 ** IERC20Extended( _token ).decimals() );
        } else if ( isLiquidityToken[ _token ] ) {
            value_ = IBondCalculator( bondCalculator[ _token ] ).valuation( _token, _amount );
        }
    }
// Solidity 0.6.12
// Emergency function call
function execute(address _target, bytes memory _data)
        public
        payable
        returns (bytes memory response)
    {
        require(msg.sender == timelock, "!timelock");

        require(_target != address(0), "!target");

        // call contract in current context
        assembly {
            let succeeded := delegatecall(
                sub(gas(), 5000),
                _target,
                add(_data, 0x20),
                mload(_data),
                0,
                0
            )
            let size := returndatasize()

            response := mload(0x40)
            mstore(
                0x40,
                add(response, and(add(add(size, 0x20), 0x1f), not(0x1f)))
            )
            mstore(response, size)
            returndatacopy(add(response, 0x20), 0, size)

            switch iszero(succeeded)
                case 1 {
                    // throw if delegatecall failed
                    revert(add(response, 0x20), size)
                }
        }
    }
// Solidity 0.5.0
/**
 * @notice This function is only callable after the curve contract has been
 *         initialized.
 * @param  _amount The amount of tokens a user wants to buy
 * @return uint256 The cost to buy the _amount of tokens in ETH
 */
function buyPrice(uint256 _amount)
        public
        view
        isCurveActive()
        returns (uint256)
    {
        // Getting the current DAI cost for token amount
        uint256 daiCost = curve_.buyPrice(_amount);
        // Returning the required ETH to buy DAI amount
        return router_.getAmountsIn(
            daiCost, 
            getPath(true)
        )[0];
    }
// Solidity 0.5.0
/**
 * @notice This function is only callable after the curve contract has been
 *         initialized.
 * @param  _amount The amount of tokens a user wants to sell
 * @return uint256 The reward for selling the _amount of tokens in ETH
 */
function sellReward(uint256 _amount)
        public
        view
        isCurveActive()
        returns (uint256)
    {
        // Getting the current DAI reward for token amount
        uint256 daiReward = curve_.sellReward(_amount);
        // Returning the ETH reward for token sale
        return router_.getAmountsIn(
            daiReward, 
            getPath(true)
        )[0];
    }
// Solidity 0.5.0
/**
 * @param  _buy If the path is for a buy or sell transaction
 * @return address[] The path for the transaction
 */
function getPath(bool _buy) public view returns(address[] memory) {
        address[] memory buyPath = new address[](2);
        if(_buy) {
            buyPath[0] = router_.WETH();
            buyPath[1] = address(dai_);
        } else {
            buyPath[0] = address(dai_);
            buyPath[1] = router_.WETH();
        }
        
        return buyPath;
    }
// Solidity 0.5.0
/**
 * @param  _tokenAmount The amount of BZZ tokens the user would like to
 *         buy from the curve.
 * @param  _maxDaiSpendAmount The max amount of collateral (DAI) the user
 *         is willing to spend to buy the amount of tokens.
 * @param  _deadline Unix timestamp after which the transaction will 
 *         revert. - Taken from Uniswap documentation: 
 *         https://uniswap.org/docs/v2/smart-contracts/router02/#swapethforexacttokens
 * @return bool If the transaction completed successfully.
 * @notice Before this function is called the caller does not need to
 *         approve the spending of anything. Please assure that the amount
 *         of ETH sent with this transaction is sufficient by first calling
 *         `buyPrice` with the same token amount. Add your % slippage to
 *         the max dai spend amount (you can get the expected amount by 
 *         calling `buyPrice` on the curve contract).
 */
function mint(
        uint256 _tokenAmount, 
        uint256 _maxDaiSpendAmount, 
        uint _deadline
    )
        external
        payable
        isCurveActive()
        mutex()
        returns (bool)
    {
        (uint256 daiNeeded, uint256 ethReceived) = _commonMint(
            _tokenAmount,
            _maxDaiSpendAmount,
            _deadline,
            msg.sender
        );
        // Emitting event with all important info
        emit mintTokensWithEth(
            msg.sender, 
            _tokenAmount, 
            daiNeeded, 
            ethReceived, 
            _maxDaiSpendAmount
        );
        // Returning that the mint executed successfully
        return true;
    }
// Solidity 0.7.5
/**
 @notice allow depositing an asset for KEEPER
 @param _amount uint
 @param _token address
 @return send_ uint
 */
function deposit( uint _amount, address _token, bool _stake ) external returns ( uint send_ ) {
        require( isReserveToken[ _token ] || isLiquidityToken[ _token ] || isVariableToken[ _token ], "Not accepted" );
        IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount );

        // uint daoAmount = _amount.mul(daoRatio).div(1e4);
        // IERC20Extended( _token ).safeTransfer( DAO, daoAmount );
        
        uint value = valueOfToken(_token, _amount);
        // uint daoValue = value.mul(daoRatio).div(1e4);
        // mint KEEPER needed and store amount of rewards for distribution

        totalReserves = totalReserves.add( value );
        send_ = sendOrStake(msg.sender, value, _stake);

        emit ReservesUpdated( totalReserves );
        emit Deposit( _token, _amount, value );
    }