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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
use crate::{
idl::{self, Idl},
program_client_generator, Client,
};
use cargo_metadata::{MetadataCommand, Package};
use fehler::{throw, throws};
use futures::future::try_join_all;
use log::debug;
use solana_sdk::signer::keypair::Keypair;
use std::{borrow::Cow, io, iter, path::Path, process::Stdio, string::FromUtf8Error};
use thiserror::Error;
use tokio::{
fs,
io::AsyncWriteExt,
process::{Child, Command},
};
pub static PROGRAM_CLIENT_DIRECTORY: &str = ".program_client";
#[derive(Error, Debug)]
pub enum Error {
#[error("{0:?}")]
Io(#[from] io::Error),
#[error("{0:?}")]
Utf8(#[from] FromUtf8Error),
#[error("localnet is not running")]
LocalnetIsNotRunning,
#[error("localnet is still running")]
LocalnetIsStillRunning,
#[error("build programs failed")]
BuildProgramsFailed,
#[error("testing failed")]
TestingFailed,
#[error("read program code failed: '{0}'")]
ReadProgramCodeFailed(String),
#[error("{0:?}")]
Idl(#[from] idl::Error),
#[error("{0:?}")]
TomlDeserialize(#[from] toml::de::Error),
#[error("parsing Cargo.toml dependencies failed")]
ParsingCargoTomlDependenciesFailed,
}
pub struct LocalnetHandle {
solana_test_validator_process: Child,
}
impl LocalnetHandle {
#[throws]
pub async fn stop(mut self) {
self.solana_test_validator_process.kill().await?;
if Client::new(Keypair::new()).is_localnet_running(false).await {
throw!(Error::LocalnetIsStillRunning);
}
debug!("localnet stopped");
}
#[throws]
pub async fn stop_and_remove_ledger(self) {
self.stop().await?;
fs::remove_dir_all("test-ledger").await?;
debug!("ledger removed");
}
}
pub struct Commander {
root: Cow<'static, str>,
}
impl Commander {
pub fn new() -> Self {
Self {
root: "../../".into(),
}
}
pub fn with_root(root: impl Into<Cow<'static, str>>) -> Self {
Self { root: root.into() }
}
#[throws]
pub async fn build_programs(&self) {
let success = Command::new("cargo")
.arg("build-bpf")
.arg("--")
.args(["-Z", "avoid-dev-deps"])
.spawn()?
.wait()
.await?
.success();
if !success {
throw!(Error::BuildProgramsFailed);
}
}
#[throws]
pub async fn run_tests(&self) {
let success = Command::new("cargo")
.arg("test")
.arg("--")
.arg("--nocapture")
.spawn()?
.wait()
.await?
.success();
if !success {
throw!(Error::TestingFailed);
}
}
#[throws]
pub async fn create_program_client_crate(&self) {
let crate_path = Path::new(self.root.as_ref()).join(PROGRAM_CLIENT_DIRECTORY);
if fs::metadata(&crate_path).await.is_ok() {
return;
}
fs::create_dir(&crate_path).await?;
let cargo_toml_content = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/src/templates/program_client/Cargo.toml.tmpl"
));
fs::write(crate_path.join("Cargo.toml"), &cargo_toml_content).await?;
let src_path = crate_path.join("src");
fs::create_dir(&src_path).await?;
let lib_rs_content = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/src/templates/program_client/lib.rs"
));
fs::write(src_path.join("lib.rs"), &lib_rs_content).await?;
debug!("program_client crate created")
}
pub fn program_packages(&self) -> impl Iterator<Item = Package> {
let cargo_toml_data = MetadataCommand::new()
.no_deps()
.exec()
.expect("Cargo.toml reading failed");
cargo_toml_data.packages.into_iter().filter(|package| {
if let Some("programs") = package.manifest_path.iter().nth_back(2) {
return true;
}
false
})
}
#[throws]
pub async fn generate_program_client_deps(&self) {
let trdelnik_dep = r#"trdelnik-client = "0.1.6""#.parse().unwrap();
let absolute_root = fs::canonicalize(self.root.as_ref()).await?;
let program_deps = self.program_packages().map(|package| {
let name = package.name;
let path = package
.manifest_path
.parent()
.unwrap()
.strip_prefix(&absolute_root)
.unwrap();
format!(r#"{name} = {{ path = "../{path}", features = ["no-entrypoint"] }}"#)
.parse()
.unwrap()
});
let cargo_toml_path = Path::new(self.root.as_ref())
.join(PROGRAM_CLIENT_DIRECTORY)
.join("Cargo.toml");
let mut cargo_toml_content: toml::Value =
fs::read_to_string(&cargo_toml_path).await?.parse()?;
let cargo_toml_deps = cargo_toml_content
.get_mut("dependencies")
.and_then(toml::Value::as_table_mut)
.ok_or(Error::ParsingCargoTomlDependenciesFailed)?;
for dep in iter::once(trdelnik_dep).chain(program_deps) {
if let toml::Value::Table(table) = dep {
let (name, value) = table.into_iter().next().unwrap();
cargo_toml_deps.entry(name).or_insert(value);
}
}
fs::write(cargo_toml_path, cargo_toml_content.to_string()).await?;
}
#[throws]
pub async fn generate_program_client_lib_rs(&self) {
let idl_programs = self.program_packages().map(|package| async move {
let name = package.name;
let output = Command::new("cargo")
.arg("+nightly")
.arg("rustc")
.args(["--package", &name])
.arg("--profile=check")
.arg("--")
.arg("-Zunpretty=expanded")
.output()
.await?;
if output.status.success() {
let code = String::from_utf8(output.stdout)?;
Ok(idl::parse_to_idl_program(name, &code).await?)
} else {
let error_text = String::from_utf8(output.stderr)?;
Err(Error::ReadProgramCodeFailed(error_text))
}
});
let idl = Idl {
programs: try_join_all(idl_programs).await?,
};
let program_client = program_client_generator::generate_source_code(idl);
let program_client = Self::format_program_code(&program_client).await?;
let rust_file_path = Path::new(self.root.as_ref())
.join(PROGRAM_CLIENT_DIRECTORY)
.join("src/lib.rs");
fs::write(rust_file_path, &program_client).await?;
}
#[throws]
pub async fn format_program_code(code: &str) -> String {
let mut rustfmt = Command::new("rustfmt")
.args(["--edition", "2018"])
.kill_on_drop(true)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()?;
if let Some(stdio) = &mut rustfmt.stdin {
stdio.write_all(code.as_bytes()).await?;
}
let output = rustfmt.wait_with_output().await?;
String::from_utf8(output.stdout)?
}
#[throws]
pub async fn start_localnet(&self) -> LocalnetHandle {
let mut process = Command::new("solana-test-validator")
.arg("-C")
.arg([&self.root, "config.yml"].concat())
.arg("-r")
.arg("-q")
.spawn()?;
if !Client::new(Keypair::new()).is_localnet_running(true).await {
process.kill().await.ok();
throw!(Error::LocalnetIsNotRunning);
}
debug!("localnet started");
LocalnetHandle {
solana_test_validator_process: process,
}
}
}
impl Default for Commander {
fn default() -> Self {
Self::new()
}
}