stx-get-balance
Querying the STX balance of a principal in Clarity smart contracts.
Function Signature
(stx-get-balance owner)
- Input:
principal
- Output:
uint
Why it matters
The stx-get-balance
function is crucial for:
- 1Querying the STX balance of a principal.
- 2Implementing logic that requires checking account balances.
- 3Ensuring data integrity by providing accurate balance information.
- 4Simplifying the process of handling balance-related operations in smart contracts.
When to use it
Use stx-get-balance
when you need to:
- Query the STX balance of a principal.
- Implement logic that requires checking account balances.
- Ensure accurate balance information for data integrity.
- Handle balance-related operations in your smart contract.
Best Practices
- Ensure the
principal
is correctly formatted and valid. - Use meaningful variable names for better readability.
- Combine with other account functions for comprehensive account management.
- Handle the possible error cases to ensure robust contract behavior.
Practical Example: Querying STX Balance
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:
- 1Using
stx-get-balance
to query the STX balance of a principal. - 2Implementing a public function to handle the balance query.
- 3Handling both successful and error cases.
Common Pitfalls
- 1Using
stx-get-balance
with an incorrectly formatted or invalidprincipal
, causing the operation to fail. - 2Assuming the balance query will always succeed, leading to unhandled error cases.
- 3Not handling all possible conditions, resulting in incomplete account management.
- 4Overlooking the need for proper error handling and validation.
Related Functions
stx-transfer?
: Transfers STX from one principal to another.stx-burn?
: Burns STX from a principal's account.stx-account
: Queries detailed STX account information.
Conclusion
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.