nutshell_wallet.rs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. use std::time::Duration;
  2. use cdk_fake_wallet::create_fake_invoice;
  3. use serde::{Deserialize, Serialize};
  4. use serde_json::Value;
  5. use tokio::time::sleep;
  6. /// Response from the invoice creation endpoint
  7. #[derive(Debug, Serialize, Deserialize)]
  8. struct InvoiceResponse {
  9. payment_request: String,
  10. checking_id: Option<String>,
  11. }
  12. /// Maximum number of attempts to check invoice payment status
  13. const MAX_PAYMENT_CHECK_ATTEMPTS: u8 = 20;
  14. /// Delay between payment status checks in milliseconds
  15. const PAYMENT_CHECK_DELAY_MS: u64 = 500;
  16. /// Default test amount in satoshis
  17. const DEFAULT_TEST_AMOUNT: u64 = 10000;
  18. fn http_client() -> cdk_common::HttpClient {
  19. cdk_common::HttpClient::new()
  20. }
  21. /// Helper function to mint tokens via Lightning invoice
  22. async fn mint_tokens(base_url: &str, amount: u64) -> String {
  23. // Create an invoice for the specified amount
  24. let invoice_url = format!("{}/lightning/create_invoice?amount={}", base_url, amount);
  25. // POST with empty body
  26. let empty_body: [(&str, &str); 0] = [];
  27. let invoice_response: InvoiceResponse = http_client()
  28. .post_form(&invoice_url, &empty_body)
  29. .await
  30. .expect("Failed to send invoice creation request");
  31. println!("Created invoice: {}", invoice_response.payment_request);
  32. invoice_response.payment_request
  33. }
  34. /// Helper function to wait for payment confirmation
  35. async fn wait_for_payment_confirmation(base_url: &str, payment_request: &str) {
  36. let check_url = format!(
  37. "{}/lightning/invoice_state?payment_request={}",
  38. base_url, payment_request
  39. );
  40. let mut payment_confirmed = false;
  41. for attempt in 1..=MAX_PAYMENT_CHECK_ATTEMPTS {
  42. println!(
  43. "Checking invoice state (attempt {}/{})...",
  44. attempt, MAX_PAYMENT_CHECK_ATTEMPTS
  45. );
  46. let state_result: Result<Value, _> = http_client()
  47. .get(&check_url)
  48. .await;
  49. if let Ok(state) = state_result {
  50. println!("Payment state: {:?}", state);
  51. if let Some(result) = state.get("result") {
  52. if result == 1 {
  53. payment_confirmed = true;
  54. break;
  55. }
  56. }
  57. } else {
  58. println!("Failed to check payment state");
  59. }
  60. sleep(Duration::from_millis(PAYMENT_CHECK_DELAY_MS)).await;
  61. }
  62. if !payment_confirmed {
  63. panic!("Payment not confirmed after maximum attempts");
  64. }
  65. }
  66. /// Helper function to get the current wallet balance
  67. async fn get_wallet_balance(base_url: &str) -> u64 {
  68. let balance_url = format!("{}/balance", base_url);
  69. let balance: Value = http_client()
  70. .get(&balance_url)
  71. .await
  72. .expect("Failed to send balance request");
  73. balance["balance"]
  74. .as_u64()
  75. .expect("Could not parse balance as u64")
  76. }
  77. /// Test the Nutshell wallet's ability to mint tokens from a Lightning invoice
  78. #[tokio::test]
  79. async fn test_nutshell_wallet_mint() {
  80. // Get the wallet URL from environment variable
  81. let base_url = std::env::var("WALLET_URL").expect("Wallet url is not set");
  82. // Step 1: Create an invoice and mint tokens
  83. let amount = DEFAULT_TEST_AMOUNT;
  84. let payment_request = mint_tokens(&base_url, amount).await;
  85. // Step 2: Wait for the invoice to be paid
  86. wait_for_payment_confirmation(&base_url, &payment_request).await;
  87. // Step 3: Check the wallet balance
  88. let available_balance = get_wallet_balance(&base_url).await;
  89. // Verify the balance is at least the amount we minted
  90. assert!(
  91. available_balance >= amount,
  92. "Balance should be at least {} but was {}",
  93. amount,
  94. available_balance
  95. );
  96. }
  97. /// Test the Nutshell wallet's ability to mint tokens from a Lightning invoice
  98. #[tokio::test]
  99. async fn test_nutshell_wallet_swap() {
  100. // Get the wallet URL from environment variable
  101. let base_url = std::env::var("WALLET_URL").expect("Wallet url is not set");
  102. // Step 1: Create an invoice and mint tokens
  103. let amount = DEFAULT_TEST_AMOUNT;
  104. let payment_request = mint_tokens(&base_url, amount).await;
  105. // Step 2: Wait for the invoice to be paid
  106. wait_for_payment_confirmation(&base_url, &payment_request).await;
  107. let send_amount = 100;
  108. let send_url = format!("{}/send?amount={}", base_url, send_amount);
  109. let empty_body: [(&str, &str); 0] = [];
  110. let response: Value = http_client()
  111. .post_form(&send_url, &empty_body)
  112. .await
  113. .expect("Failed to send payment check request");
  114. // Extract the token and remove the surrounding quotes
  115. let token_with_quotes = response
  116. .get("token")
  117. .expect("Missing token")
  118. .as_str()
  119. .expect("Token is not a string");
  120. let token = token_with_quotes.trim_matches('"');
  121. let receive_url = format!("{}/receive?token={}", base_url, token);
  122. let response: Value = http_client()
  123. .post_form(&receive_url, &empty_body)
  124. .await
  125. .expect("Failed to receive request");
  126. let balance = response
  127. .get("balance")
  128. .expect("Bal in response")
  129. .as_u64()
  130. .expect("Valid num");
  131. let initial_balance = response
  132. .get("initial_balance")
  133. .expect("Bal in response")
  134. .as_u64()
  135. .expect("Valid num");
  136. let token_received = balance - initial_balance;
  137. let fee = 1;
  138. assert_eq!(token_received, send_amount - fee);
  139. }
  140. /// Test the Nutshell wallet's ability to melt tokens to pay a Lightning invoice
  141. #[tokio::test]
  142. async fn test_nutshell_wallet_melt() {
  143. // Get the wallet URL from environment variable
  144. let base_url = std::env::var("WALLET_URL").expect("Wallet url is not set");
  145. // Step 1: Create an invoice and mint tokens
  146. let amount = DEFAULT_TEST_AMOUNT;
  147. let payment_request = mint_tokens(&base_url, amount).await;
  148. // Step 2: Wait for the invoice to be paid
  149. wait_for_payment_confirmation(&base_url, &payment_request).await;
  150. // Get initial balance
  151. let initial_balance = get_wallet_balance(&base_url).await;
  152. println!("Initial balance: {}", initial_balance);
  153. // Step 3: Create a fake invoice to pay
  154. let payment_amount = 1000; // 1000 sats
  155. let fake_invoice = create_fake_invoice(payment_amount, "Test payment".to_string());
  156. let pay_url = format!("{}/lightning/pay_invoice?bolt11={}", base_url, fake_invoice);
  157. // Step 4: Pay the invoice
  158. let empty_body: [(&str, &str); 0] = [];
  159. let _response: Value = http_client()
  160. .post_form(&pay_url, &empty_body)
  161. .await
  162. .expect("Failed to send pay request");
  163. let final_balance = get_wallet_balance(&base_url).await;
  164. println!("Final balance: {}", final_balance);
  165. assert!(
  166. initial_balance > final_balance,
  167. "Balance should decrease after payment"
  168. );
  169. let balance_difference = initial_balance - final_balance;
  170. println!("Balance decreased by: {}", balance_difference);
  171. // The balance difference should be at least the payment amount
  172. assert!(
  173. balance_difference >= (payment_amount / 1000),
  174. "Balance should decrease by at least the payment amount ({}) but decreased by {}",
  175. payment_amount,
  176. balance_difference
  177. );
  178. }