Skip to main content

fedimint_wasm_tests/
faucet.rs

1use anyhow::Context;
2
3pub async fn invite_code() -> anyhow::Result<String> {
4    let resp = gloo_net::http::Request::get(&url("/connect-string")?)
5        .send()
6        .await?;
7    if resp.ok() {
8        Ok(resp.text().await?)
9    } else {
10        anyhow::bail!(resp.text().await?);
11    }
12}
13
14pub async fn pay_invoice(invoice: &str) -> anyhow::Result<()> {
15    let resp = gloo_net::http::Request::post(&url("/pay")?)
16        .body(invoice)?
17        .send()
18        .await?;
19    if resp.ok() {
20        Ok(())
21    } else {
22        anyhow::bail!(resp.text().await?);
23    }
24}
25
26pub async fn gateway_api() -> anyhow::Result<String> {
27    let resp = gloo_net::http::Request::get(&url("/gateway-api")?)
28        .send()
29        .await?;
30    if resp.ok() {
31        Ok(resp.text().await?)
32    } else {
33        anyhow::bail!(resp.text().await?);
34    }
35}
36
37pub async fn generate_invoice(amt: u64) -> anyhow::Result<String> {
38    let resp = gloo_net::http::Request::post(&url("/invoice")?)
39        .body(amt)?
40        .send()
41        .await?;
42    if resp.ok() {
43        Ok(resp.text().await?)
44    } else {
45        anyhow::bail!(resp.text().await?);
46    }
47}
48
49/// Devimint allocates the faucet port when it starts and exports it as
50/// `FM_PORT_FAUCET` to the command run via `wasm-test-setup --exec`, which
51/// is how it reaches this build. Browser tests have no other way to learn
52/// it at runtime.
53///
54/// Only the wasm build captures it. This crate is also compiled natively
55/// as part of `--workspace` builds, frequently from inside a devimint
56/// environment, and must not go stale every time devimint hands out a
57/// different port.
58#[cfg(target_arch = "wasm32")]
59const PORT: Option<&str> = option_env!("FM_PORT_FAUCET");
60#[cfg(not(target_arch = "wasm32"))]
61const PORT: Option<&str> = None;
62
63fn url(path: &str) -> anyhow::Result<String> {
64    let port = PORT.context(
65        "FM_PORT_FAUCET was not set when fedimint-wasm-tests was built; \
66         run the tests via `devimint wasm-test-setup --exec`",
67    )?;
68    Ok(format!("http://localhost:{port}{path}"))
69}