-
Notifications
You must be signed in to change notification settings - Fork 39
/
request_funds.rs
64 lines (52 loc) · 2.2 KB
/
request_funds.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Copyright 2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
//! In this example we request funds from the faucet to the first address in the account.
//!
//! Make sure that `STRONGHOLD_SNAPSHOT_PATH` and `WALLET_DB_PATH` already exist by
//! running the `./how_tos/accounts_and_addresses/create_account.rs` example!
//!
//! Rename `.env.example` to `.env` first, then run the command:
//! ```sh
//! cargo run --release --all-features --example request_funds
//! ```
use iota_sdk::{client::request_funds_from_faucet, wallet::Result, Wallet};
#[tokio::main]
async fn main() -> Result<()> {
// This example uses secrets in environment variables for simplicity which should not be done in production.
dotenvy::dotenv().ok();
for var in ["WALLET_DB_PATH", "FAUCET_URL"] {
std::env::var(var).expect(&format!(".env variable '{var}' is undefined, see .env.example"));
}
let wallet = Wallet::builder()
.with_storage_path(&std::env::var("WALLET_DB_PATH").unwrap())
.finish()
.await?;
let account = wallet.get_account("Alice").await?;
let balance = account.sync(None).await?;
println!("Account synced");
let addresses = account.addresses().await?;
let funds_before = balance.base_coin().available();
println!("Current available funds: {funds_before}");
println!("Requesting funds from faucet...");
let faucet_response =
request_funds_from_faucet(&std::env::var("FAUCET_URL").unwrap(), addresses[0].address()).await?;
println!("Response from faucet: {}", faucet_response.trim_end());
println!("Waiting for funds (timeout=60s)...");
// Check for changes to the balance
let start = std::time::Instant::now();
let funds_after = loop {
if start.elapsed().as_secs() > 60 {
println!("Timeout: waiting for funds took too long");
return Ok(());
};
let balance = account.sync(None).await?;
let funds_after = balance.base_coin().available();
if funds_after > funds_before {
break funds_after;
} else {
tokio::time::sleep(instant::Duration::from_secs(2)).await;
}
};
println!("New available funds: {funds_after}");
Ok(())
}