Let's implement a function that queries the STX balance of a given principal:
(define-read-only (get-stx-balance (account principal)) (stx-get-balance account));; Usage(get-stx-balance 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u0 if the account has no balance(get-stx-balance (as-contract tx-sender)) ;; Returns the balance of the contract's principal
This example demonstrates:
Using stx-get-balance to query the STX balance of a principal.
Implementing a public function to handle the balance query.
The stx-get-balance function is a fundamental tool for querying the STX balance of a principal in Clarity smart contracts. It allows developers to implement logic that requires checking account balances, ensuring data integrity and simplifying balance-related operations. When used effectively, stx-get-balance enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle balance queries.