Querying Donation Data
Now that we can accept donations, we need ways to query the data. View methods allow anyone to read contract state without paying gas fees, making them perfect for displaying donation information.
Individual Donation Queries
First, let's implement a method to get donation information for a specific account:
- Rust
- TypeScript
Loading...
Loading...
Donation Data Structure
The methods return structured data that's easy for frontends to consume:
- Rust
- TypeScript
Loading...
Loading...
Counting Donors
A simple method to get the total number of unique donors:
- Rust
- TypeScript
Loading...
Loading...
Paginated Donation Lists
For displaying all donations, we need pagination to handle large datasets efficiently:
- Rust
- TypeScript
Loading...
Loading...
Beneficiary Management
Remember the beneficiary methods from our setup? They're view methods too:
- Rust
- TypeScript
Loading...
Loading...
Testing Query Methods
Let's verify our query methods work correctly in the integration tests:
- Rust
- TypeScript
Loading...
Loading...
Using View Methods via CLI
Once deployed, you can query your contract using NEAR CLI:
# Get beneficiary
near view donation.near-examples.testnet get_beneficiary
# Get number of donors
near view donation.near-examples.testnet number_of_donors
# Get donations with pagination
near view donation.near-examples.testnet get_donations \
'{"from_index": 0, "limit": 10}'
# Get specific donation
near view donation.near-examples.testnet get_donation_for_account \
'{"account_id": "alice.testnet"}'
Key Concepts
View Methods: Functions marked with #[view] (Rust) or @view({}) (TypeScript) are read-only and don't cost gas to call.
Pagination: Large datasets should be paginated to avoid hitting gas limits and provide better user experience.
Data Serialization: NEAR automatically serializes return values to JSON, making them easy to consume from frontends.
Public Access: View methods can be called by anyone, even accounts without NEAR tokens.
Query Performance Tips
- Use pagination for methods that could return large datasets
- Consider caching frequently accessed data in your frontend
- Batch queries when possible to reduce RPC calls
- Index important data for efficient lookups
Error Handling
View methods can still fail if they access non-existent data or exceed computation limits:
// Always handle missing data gracefully
let donated_amount = self
.donations
.get(&account_id)
.cloned()
.unwrap_or(NearToken::from_near(0)); // Default to 0 if not found
Continue to Deploy and Test to learn how to deploy your contract and test it on NEAR testnet.