Using the bit-and function for bitwise operations in Clarity smart contracts.
The bit-and function in Clarity performs a bitwise AND operation on two or more integer inputs. It's a powerful tool for working with compact data representations and flag systems in smart contracts.
Let's implement a simple role-based access control system using bit-and:
;; Define role constants(define-constant ROLE_ADMIN u1) ;; 0001(define-constant ROLE_MODERATOR u2) ;; 0010(define-constant ROLE_USER u4) ;; 0100;; Map to store user roles(define-map UserRoles principal uint);; Function to check if a user has a specific role(define-read-only (has-role? (user principal) (role uint)) (let ((userRole (default-to u0 (map-get? UserRoles user)))) (is-eq (bit-and userRole role) role) ));; Function to add a role to a user(define-public (add-role (user principal) (role uint)) (let ((currentRole (default-to u0 (map-get? UserRoles user)))) (ok (map-set UserRoles user (bit-or currentRole role))) ));; Function to remove a role from a user(define-public (remove-role (user principal) (role uint)) (let ((currentRole (default-to u0 (map-get? UserRoles user)))) (ok (map-set UserRoles user (bit-and currentRole (bit-not role)))) ));; Example usage(add-role tx-sender (bit-or ROLE_MODERATOR ROLE_USER))(has-role? tx-sender ROLE_MODERATOR) ;; Returns true(has-role? tx-sender ROLE_ADMIN) ;; Returns false(remove-role tx-sender ROLE_USER)(has-role? tx-sender ROLE_USER) ;; Returns false
This example demonstrates:
Using bit-and to check for specific roles.
Combining bit-and with bit-or and bit-not for role management.
Efficient storage of multiple roles in a single integer.
The bit-and function is a powerful tool for working with compact data representations in Clarity. By mastering this function along with other bitwise operations, you can create efficient and sophisticated smart contracts that make optimal use of storage and perform complex flag-based logic.