use anyhow::{Context, Result, ensure};
use miden_client::account::Account;
use crate::fee_funding::FUNDING_AMOUNT;
pub const FUNDING_SERVICE_ENV: &str = "MIDEN_FUNDING_SERVICE_URL";
pub async fn request_funds(account: &Account) -> Result<()> {
let service_url = std::env::var(FUNDING_SERVICE_ENV).with_context(|| {
format!("{FUNDING_SERVICE_ENV} is not set. Start the node with MIDEN_ACCOUNT_ALLOWLIST=1")
})?;
let url = format!("{}/request-funds", service_url.trim_end_matches('/'));
let request = serde_json::json!({
"account_id": account.id().to_hex(),
"amount": FUNDING_AMOUNT,
});
let response = reqwest::Client::new()
.post(&url)
.json(&request)
.send()
.await
.with_context(|| format!("failed to reach the funding service at {url}"))?;
let status = response.status();
ensure!(
status.is_success(),
"the funding service refused to fund account {}: {status} {}",
account.id(),
response.text().await.unwrap_or_default()
);
Ok(())
}