-
Notifications
You must be signed in to change notification settings - Fork 178
Expand file tree
/
Copy pathrequirements.rs
More file actions
71 lines (61 loc) · 2.11 KB
/
requirements.rs
File metadata and controls
71 lines (61 loc) · 2.11 KB
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
65
66
67
68
69
70
71
use clarity_repl::clarity::types::QualifiedContractIdentifier;
use std::fs::{self, File};
use std::io::Write;
use std::path::PathBuf;
pub fn retrieve_contract(
contract_id: &QualifiedContractIdentifier,
use_cache: bool,
cache_path: Option<PathBuf>,
) -> Result<(String, PathBuf), String> {
let contract_deployer = contract_id.issuer.to_address();
let contract_name = contract_id.name.to_string();
let mut file_path = PathBuf::new();
if use_cache {
if let Some(ref cache_path) = cache_path {
let mut path = PathBuf::from(cache_path);
path.push(format!("{}.clar", contract_id));
if let Ok(data) = fs::read_to_string(&path) {
return Ok((data, path));
}
}
}
let stacks_node_addr = if contract_deployer.starts_with("SP") {
"https://stacks-node-api.mainnet.stacks.co".to_string()
} else {
"https://stacks-node-api.testnet.stacks.co".to_string()
};
let request_url = format!(
"{host}/v2/contracts/source/{addr}/{name}?proof=0",
host = stacks_node_addr,
addr = contract_deployer,
name = contract_name
);
let rt = tokio::runtime::Runtime::new().unwrap();
let response = rt.block_on(async { fetch_contract(request_url).await });
let code = response.source.to_string();
if use_cache {
if let Some(ref cache_path) = cache_path {
file_path = PathBuf::from(cache_path);
let _ = fs::create_dir_all(&file_path);
file_path.push(format!("{}.clar", contract_id));
if let Ok(ref mut file) = File::create(&file_path) {
let _ = file.write_all(code.as_bytes());
}
}
}
Ok((code, file_path))
}
#[derive(Deserialize, Debug, Default, Clone)]
struct Contract {
source: String,
publish_height: u32,
}
async fn fetch_contract(request_url: String) -> Contract {
let response: Contract = reqwest::get(&request_url)
.await
.expect("Unable to retrieve contract")
.json()
.await
.expect("Unable to parse contract");
return response;
}