salt-sdk 0.0.0-alpha1

Salt asset manager Rust SDK
Documentation
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
pub mod prelude {
	#![allow(unused_imports)]
	pub use crate::Salt;

	pub(crate) use tracing::{debug, error, info, trace, warn};

	pub(crate) use crate::{Error, Result};
	pub(crate) use camino::{Utf8Path, Utf8PathBuf};
}

use std::process::ExitStatus;

use camino::FromPathBufError;
use cli::{Command, Output};
use git::Git;
use url::Url;
use which::which;

use crate::prelude::*;

pub struct Salt {
	project_folder: Utf8PathBuf,
	config: SaltConfig,
}

#[derive(Clone, serde::Deserialize)]
pub struct SaltConfig {
	#[serde(rename = "PRIVATE_KEY")]
	pub private_key: String,

	#[serde(rename = "ORCHESTRATION_NETWORK_RPC_NODE_URL")]
	pub orchestration_network_rpc_node: Url,

	#[serde(rename = "BROADCASTING_NETWORK_RPC_NODE_URL")]
	pub broadcasting_network_rpc_node: Url,

	#[serde(rename = "BROADCASTING_NETWORK_ID")]
	pub broadcasting_network_id: u64,
}

impl std::fmt::Debug for SaltConfig {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		let map = self.clone().iter();
		let mut fmt = f.debug_struct("SaltConfig");
		let blacklisted_fields = ["PRIVATE_KEY"];
		for (key, value) in map {
			if blacklisted_fields.contains(&key) {
				fmt.field(key, &"redacted".to_owned());
			} else {
				fmt.field(key, &value);
			}
		}
		fmt.finish()
	}
}

impl SaltConfig {
	fn iter(self) -> impl IntoIterator<Item = (&'static str, String)> {
		[
			("PRIVATE_KEY", self.private_key),
			(
				"ORCHESTRATION_NETWORK_RPC_NODE_URL",
				self.orchestration_network_rpc_node.to_string(),
			),
			(
				"BROADCASTING_NETWORK_RPC_NODE_URL",
				self.broadcasting_network_rpc_node.to_string(),
			),
			(
				"BROADCASTING_NETWORK_ID",
				self.broadcasting_network_id.to_string(),
			),
		]
	}
}

#[derive(thiserror::Error, Debug)]
pub enum Error {
	#[error(
		"Couldn't find appropriate default director: https://docs.rs/dirs/latest/dirs/fn.data_dir.html or https://docs.rs/dirs/latest/dirs/fn.data_local_dir.html"
	)]
	NoStandardDirectoryFound,

	#[error("{0}")]
	Camino(#[from] FromPathBufError),

	#[error("Executable file doesn't exist")]
	ExecutableFileDoesntExist(Utf8PathBuf),

	#[error("{0}")]
	FailedToExecute(std::io::Error),

	#[error("Subprocess exited badly: {0:?}")]
	SubprocessExitedBadly(ExitStatus),

	#[error("Subprocess exited badly with exit status {0}")]
	SubprocessExitedBadlyWithOutput(Output),

	#[error("Couldn't make anonymous pipe: {0}")]
	CouldntMakeAnonymousePipe(std::io::Error),

	#[error(
		"Expected `{bin_name}` binary to be in PATH environment variable or finable with which https://docs.rs/which/latest/which/fn.which.html ({err_msg}): {which}"
	)]
	Which {
		bin_name: String,
		err_msg: String,
		which: ::which::Error,
	},
}

pub type Result<T> = core::result::Result<T, Error>;

impl Salt {
	fn default_project_path() -> Result<Utf8PathBuf> {
		let dir = dirs::data_local_dir()
			.or(dirs::data_dir())
			.ok_or(Error::NoStandardDirectoryFound)?;
		let path = Utf8PathBuf::try_from(dir)?;
		Ok(path.join("salt-asset-manager"))
	}

	pub fn new(config: SaltConfig) -> Result<Salt> {
		let salt = Salt {
			project_folder: Salt::default_project_path()?,
			config,
		};

		salt.init()?;

		Ok(salt)
	}

	#[tracing::instrument(name = "salt_sdk::transaction", skip_all)]
	pub fn transaction(
		&self,
		amount: &str,
		vault_address: &str,
		recipient_address: &str,
	) -> Result<Output> {
		debug!("Beginning transaction ...");
		let output = self
			.cmd([
				"-amount",
				amount,
				"-vault-address",
				vault_address,
				"-recipient-address",
				recipient_address,
			])?
			.run_and_wait_for_output()?;
		debug!("Finished transaction.");

		Ok(output)
	}

	pub fn broadcasting_network_id(&self) -> u64 {
		self.config.broadcasting_network_id.clone()
	}

	/// git pull && deno install && nu fix.nu
	fn init(&self) -> Result<()> {
		let git = self.git()?;
		git.ensure_latest_branch(
			Url::parse("https://github.com/ActuallyHappening/salt-asset-manager").unwrap(),
			"master",
		)?;

		let deno = Salt::deno()?;
		cli::Command::pure(deno)?
			.with_cwd(self.project_folder.clone())
			.with_args(["install"])
			.run_and_wait()?;

		if self.project_folder.join("fix.nu").exists() {
			debug!("Detected fix.nu, running this after deno install");
			// run fix.nu
			let nu = which(
				"nu",
				"required shell to run fix.nu, see https://www.nushell.sh/book/installation.html#package-managers",
			)?;
			cli::Command::pure(nu)?
				.with_cwd(self.project_folder.clone())
				.with_args(["fix.nu"])
				.run_and_wait()?;
		}

		info!(
			"Successfully initialized/updated git checkout at {} ready for runtime consumption",
			self.project_folder
		);

		Ok(())
	}

	fn deno() -> Result<Utf8PathBuf> {
		which("deno", "required javascript runtime")
	}

	fn cmd(&self, args: impl IntoIterator<Item = impl AsRef<str>>) -> Result<Command> {
		let cmd = cli::Command::pure(Salt::deno()?)?
			.with_cwd(self.project_folder.clone())
			.with_args(
				[
					"run",
					"--unstable-sloppy-imports",
					"-A",
					"src/index.ts",
					"--",
					"-use-cli-only",
				]
				.into_iter()
				.map(String::from),
			)
			.with_args(args)
			.with_envs(self.config.clone().iter());
		Ok(cmd)
	}

	fn git(&self) -> Result<Git> {
		Ok(Git::new(self.project_folder.to_owned())?)
	}
}

mod cli {
	use std::process::{ExitStatus, Stdio};

	use crate::prelude::*;

	pub struct Command(std::process::Command);

	impl Command {
		pub fn pure(cmd: Utf8PathBuf) -> Result<Command> {
			if !cmd.exists() {
				return Err(Error::ExecutableFileDoesntExist(cmd));
			}
			let mut cmd = std::process::Command::new(cmd);
			cmd.env_clear();
			Ok(Command(cmd))
		}

		pub fn current_dir(&mut self, cwd: Utf8PathBuf) -> &mut Self {
			self.0.current_dir(cwd);
			self
		}

		pub fn with_cwd(mut self, cwd: Utf8PathBuf) -> Self {
			self.current_dir(cwd);
			self
		}

		pub fn with_args(mut self, args: impl IntoIterator<Item = impl AsRef<str>>) -> Self {
			// allocates them all as strings,
			// but what can you do? this is a type-level restriction,
			// it is true that
			// impl AsRef<str>: impl AsRef<OsStr>
			// for all T
			self.0.args(args.into_iter().map(|s| s.as_ref().to_owned()));
			self
		}

		pub fn with_envs(mut self, envs: impl IntoIterator<Item = (&'static str, String)>) -> Self {
			self.0.envs(envs);
			self
		}

		/// Hides PRIVATE_KEY
		fn debug(&self) -> String {
			let mut initial = format!("{:?}", self.0);
			let re = regex::Regex::new(r#"PRIVATE_KEY="([a-zA-z0-9]+)""#).unwrap();
			if let Some(find) = re.find(&initial) {
				initial = initial.replace(find.as_str(), r#"PRIVATE_KEY="redacted""#);
			}
			initial
		}

		fn pre_logging(&self) {
			trace!("Running command {}", self.debug());
		}

		pub fn run_and_wait(mut self) -> Result<()> {
			self.pre_logging();

			let status = self.0.status().map_err(Error::FailedToExecute)?;

			if !status.success() {
				return Err(Error::SubprocessExitedBadly(status));
			}
			Ok(())
		}

		/// Pipes to terminal and collects
		pub fn run_and_wait_for_output(mut self) -> Result<Output> {
			self.pre_logging();

			let output: Output = self
				.0
				.stdout(Stdio::piped())
				.stderr(Stdio::piped())
				.spawn()
				.map_err(Error::FailedToExecute)?
				.wait_with_output()
				.map_err(Error::FailedToExecute)?
				.into();

			if !output.status.success() {
				return Err(Error::SubprocessExitedBadlyWithOutput(output));
			}

			Ok(output)
		}
	}

	#[derive(Debug)]
	pub struct Output {
		pub status: ExitStatus,
		pub stdout: String,
		pub stderr: String,
	}

	/// Display impl is status \n stderr \n stdout
	impl std::fmt::Display for Output {
		fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
			write!(
				f,
				"{:?}:\nStderr:\n{}\nStdout:\n{}",
				self.status, self.stderr, self.stdout
			)
		}
	}

	impl From<std::process::Output> for Output {
		fn from(value: std::process::Output) -> Self {
			let stdout = String::from_utf8_lossy(&value.stdout);
			let stderr = String::from_utf8_lossy(&value.stderr);
			Self {
				status: value.status,
				stdout: stdout.into(),
				stderr: stderr.into(),
			}
		}
	}
}

mod git {
	use url::Url;

	use crate::{cli::Command, prelude::*, which::which};

	pub struct Git {
		project_folder: Utf8PathBuf,
	}

	impl Git {
		pub fn new(path: Utf8PathBuf) -> Result<Self> {
			Ok(Self {
				project_folder: path,
			})
		}

		fn cmd(&self) -> Result<Command> {
			let git = which("git", "required runtime dependency")?;
			let cmd = Command::pure(git)?.with_cwd(self.project_folder.to_owned());
			Ok(cmd)
		}

		pub fn ensure_latest_branch(&self, repository_url: Url, branch: &str) -> Result<()> {
			if self.project_folder.exists() {
				// assume already checked out
				self.pull()?;
			} else {
				self.clone(repository_url)?;
			}
			self.checkout(branch)?;
			Ok(())
		}

		fn pull(&self) -> Result<()> {
			debug!("Running `git pull` in directory {}", &self.project_folder);
			self.cmd()?.with_args(["pull"]).run_and_wait()
		}

		fn clone(&self, repository_url: Url) -> Result<()> {
			let mut parent_folder = self.project_folder.clone();
			if !parent_folder.pop() {
				panic!("self.project_folder has no parent? Why is the data dir at / ?");
			}
			debug!(
				"Running `git clone {}` in directory {}",
				repository_url, &parent_folder
			);
			self.cmd()?
				.with_cwd(parent_folder)
				.with_args([
					"clone".into(),
					repository_url.to_string(),
					self.project_folder.to_string(),
				])
				.run_and_wait()
		}

		fn checkout(&self, branch: &str) -> Result<()> {
			self.cmd()?.with_args(["checkout", branch]).run_and_wait()
		}
	}
}

mod which {
	use crate::prelude::*;

	pub fn which(name: &'static str, err_msg: impl Into<String>) -> Result<Utf8PathBuf> {
		let path = ::which::which(name).map_err(|which| Error::Which {
			bin_name: name.to_owned(),
			err_msg: err_msg.into(),
			which,
		})?;
		Ok(Utf8PathBuf::try_from(path)?)
	}
}