Vyper Booleans (Usage + Code Examples)

whiteboard crypto logo
Published by:
Whiteboard Crypto
on

A Boolean is a value-type variable in the Vyper programming language which stores a binary value of 1 or 0. Similarly, we think of the variable being either true or false. Here’s an example:

valid_user: bool

@external
def validate_user(status: bool): 
  self.valid_user = status


@external
def get_validation() -> bool:  
  return self.valid_user


registration_open: bool

@external
def register():
  assert self.registration_open == True, "Registration is currently closed."


eligibility_age: uint256 = 18
has_paid_fee: bool

@external
def check_eligibility(user_age: uint256, user_has_paid_fee: bool) -> bool:  
  self.has_paid_fee = user_has_paid_fee
  return user_age >= self.eligibility_age and self.has_paid_fee

Boolean Function

Let’s start with the basics. The Boolean type, denoted by the bool keyword in Vyper, is the simplest data type and is used to represent truth values.

In computing, and Vyper is no exception, a Boolean variable can only hold one of two values: True or False. These two values are the cornerstone of logical statements and control structures, dictating the flow of your smart contracts.

Consider this simple Vyper smart contract that emulates a light switch:

@public
light_switch: bool
 
@external
def get_switch() -> bool:
    """
    Return the current state of the light switch.
    """
    return self.light_switch
 
@external
def change_switch():
    """
    Toggle the state of the light switch.
    """
    self.light_switch = not self.light_switch


In this contract, light_switch exemplifies a Boolean in action, being toggled on and off by the change_switch function.

Booleans with Operators

Booleans in Vyper come with operator tools for crafting logical expressions:

  • not flips the truth value
  • and requires both values to be True for the result to be True
  • or requires at least one value to be True for the result to be True
  • == checks if two values are equal
  • != checks if two values are different

These aren’t just theoretical concepts — they are the decision-makers in your Vyper smart contracts.

Truth with Short-Circuiting

Vyper’s Boolean or and and operators exhibit short-circuiting behavior. This means once an “if” statement returns true, the rest of the code in the conditional is skipped. This performance feature and safety mechanism ensures your logical expressions are as efficient as possible. To highlight this behavior, consider an eligibility check based on age:

@public
is_eligible: bool
 
@external
def check_eligibility(age: uint256) -> bool:
    """
    Determine eligibility based on age.
    """
    if age >= 18:
        return True
    else:
        return False
 
@external
def update_eligibility(age: uint256):
    """
    Update the stored eligibility status based on the given age.
    """
    self.is_eligible = self.check_eligibility(age)

In this example, we use a condition within check_eligibility and update our state variable is_eligible based on the result, illustrating the use of Booleans for logical decision-making.

Example 1: Storing and Retrieving a Boolean Value

Our first example demonstrates how a Boolean value can be stored and retrieved in a smart contract.

valid_user: bool

@external
def validate_user(status: bool): 
  # Store a Boolean value in the contract.
  self.valid_user = status

@external
def get_validation() -> bool:  
  # Retrieve the stored Boolean value.
  return self.valid_user

In the contract above, a state variable valid_user of type bool is declared. The function validate_user allows the Boolean status of a user to be stored in valid_user. Meanwhile, the get_validation method allows us to retrieve this stored Boolean value.

Example 2: Using Boolean in Conditional Statement

Next, we use a Boolean in a conditional statement to make decisions.

registration_open: bool

@external
def register():
  # Register a user only if registration is open.
  assert self.registration_open == True, "Registration is currently closed."

In this example, the register function uses an assert statement to ensure that registration is open (i.e., self.registration_open is True) before proceeding with user registration. If self.registration_open is False, the string “Registration is currently closed” is returned.

Example 3: Boolean Operators in Practice

Our last example showcases how Boolean operators andor, and not can be used in a Vyper contract.

eligibility_age: uint256 = 18
has_paid_fee: bool

@external
def check_eligibility(user_age: uint256, user_has_paid_fee: bool) -> bool:  
  # Check if a user is eligible.
  self.has_paid_fee = user_has_paid_fee
  return user_age >= self.eligibility_age and self.has_paid_fee

In this contract, the check_eligibility function takes an age and a Boolean that indicates whether the user has paid the required fee. The function returns True only if the user is of the eligible age and has paid the fee.

Best Practices and Common Pitfalls

While using Boolean data types in Vyper, consider the following best practices and common pitfalls:

  1. Explicit is Better than Implicit: When making comparisons, be explicit. Instead of writing if is_valid: or if not is_valid:, write if is_valid == True: or if is_valid == False:. This style is more readable and less prone to mistakes.
  2. Avoid Redundancy: Don’t compare Boolean variables to True or False in conditions. For example, instead of writing if is_valid == True:, you can simply write if is_valid:.
  3. Order of Logical Operations: Be aware that the logical operations and and or are short-circuited, meaning that if the first operand of an and operation is False, the second operand won’t be evaluated because the result is definitely False. Similarly, if the first operand of an or operation is True, the second operand won’t be evaluated. While this can sometimes help optimize your code, it may also lead to unexpected behavior if the second operand has side effects.

Remember, Boolean data types play a vital role in controlling the conditional flow of code execution. Thoughtful and effective implementation can often lead to a more secure, understandable, and efficient smart contract.

Best Practices

When using Booleans in Vyper:

  • Choose descriptive variable names, like is_eligible or has_balance.
  • Be explicit; if is_verified: is clearer than if is_verified == True:.
  • Utilize short-circuiting for efficient code; consider the order of your logical operations.

Remember, Booleans are passed by value and immutable, so reassignments won’t affect the original variable.

Booleans in Vyper are simple yet powerful foundational tools. By understanding and utilizing Booleans and their operators, you can create smart contracts that are precise, efficient, and reliable.

Vyper Booleans
whiteboard crypto logo

WhiteboardCrypto is the #1 online resource for crypto education that explains topics of the cryptocurrency world using analogies, stories, and examples so that anyone can easily understand them. Growing to over 870,000 Youtube subscribers, the content has been shared around the world, played in public conferences and universities, and even in Congress.