basic_usage.rs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. //! Basic usage example for the `NpubCash` SDK
  2. //!
  3. //! This example demonstrates:
  4. //! - Creating a client with authentication
  5. //! - Fetching all quotes
  6. //! - Fetching quotes since a timestamp
  7. //! - Error handling
  8. use std::sync::Arc;
  9. use cdk_npubcash::{JwtAuthProvider, NpubCashClient};
  10. use nostr_sdk::Keys;
  11. #[tokio::main]
  12. async fn main() -> Result<(), Box<dyn std::error::Error>> {
  13. tracing_subscriber::fmt::init();
  14. let base_url =
  15. std::env::var("NPUBCASH_URL").unwrap_or_else(|_| "https://npubx.cash".to_string());
  16. let keys = if let Ok(nsec) = std::env::var("NOSTR_NSEC") {
  17. Keys::parse(&nsec)?
  18. } else {
  19. println!("No NOSTR_NSEC found, generating new keys");
  20. Keys::generate()
  21. };
  22. println!("Public key: {}", keys.public_key());
  23. let auth_provider = Arc::new(JwtAuthProvider::new(base_url.clone(), keys));
  24. let client = NpubCashClient::new(base_url, auth_provider);
  25. println!("\n=== Fetching all quotes ===");
  26. match client.get_quotes(None).await {
  27. Ok(quotes) => {
  28. println!("Successfully fetched {} quotes", quotes.len());
  29. if let Some(first) = quotes.first() {
  30. println!("\nFirst quote:");
  31. println!(" ID: {}", first.id);
  32. println!(" Amount: {}", first.amount);
  33. println!(" Unit: {}", first.unit);
  34. }
  35. }
  36. Err(e) => {
  37. eprintln!("Error fetching quotes: {e}");
  38. }
  39. }
  40. let one_hour_ago = std::time::SystemTime::now()
  41. .duration_since(std::time::UNIX_EPOCH)?
  42. .as_secs()
  43. - 3600;
  44. println!("\n=== Fetching quotes from last hour ===");
  45. match client.get_quotes(Some(one_hour_ago)).await {
  46. Ok(quotes) => {
  47. println!("Found {} quotes in the last hour", quotes.len());
  48. }
  49. Err(e) => {
  50. eprintln!("Error fetching recent quotes: {e}");
  51. }
  52. }
  53. Ok(())
  54. }