use aiken_project::{
blueprint::{
self, Blueprint,
definitions::Definitions,
schema::{Annotated, Constructor, Data, Declaration, Items, Schema},
},
error::Error,
pretty::multiline,
watch::{with_project, without_project},
};
use inquire;
use num_bigint::BigInt;
use ordinal::Ordinal;
use owo_colors::{OwoColorize, Stream::Stderr};
use pallas_primitives::alonzo::PlutusData;
use std::{
fs::{self, File},
io::BufReader,
path::PathBuf,
str::FromStr,
};
use uplc::ast::Data as UplcData;
#[derive(clap::Args)]
#[clap(disable_version_flag(true))]
pub struct Args {
#[clap(value_name = "CBOR")]
parameter: Option<String>,
#[clap(
short,
long = "in",
value_parser,
value_name = "FILEPATH",
verbatim_doc_comment
)]
input: Option<PathBuf>,
#[clap(short, long("out"), value_parser, value_name = "FILEPATH")]
output: Option<PathBuf>,
#[clap(short, long)]
module: Option<String>,
#[clap(short, long)]
validator: Option<String>,
}
pub fn exec(
Args {
parameter,
input,
output,
module,
validator,
}: Args,
) -> miette::Result<()> {
eprintln!(
"{} blueprint",
" Analyzing"
.if_supports_color(Stderr, |s| s.purple())
.if_supports_color(Stderr, |s| s.bold()),
);
let apply = |blueprint_input_path: PathBuf| {
let blueprint = File::open(&blueprint_input_path)
.map_err(|_| blueprint::error::Error::InvalidOrMissingFile)
.map_err(|err| Error::Blueprint(err.into()))?;
let mut blueprint: Blueprint =
serde_json::from_reader(BufReader::new(blueprint)).map_err(Error::from)?;
let data: PlutusData = match ¶meter {
Some(param) => {
eprintln!(
"{} inputs",
" Parsing"
.if_supports_color(Stderr, |s| s.purple())
.if_supports_color(Stderr, |s| s.bold()),
);
let bytes = hex::decode(param)
.map_err(|e| blueprint::error::Error::MalformedParameter {
hint: format!("Invalid hex-encoded string: {e}"),
})
.map_err(|err| Error::Blueprint(err.into()))?;
uplc::plutus_data(&bytes).map_err(|e| blueprint::error::Error::MalformedParameter {
hint: format!("Invalid Plutus data; malformed CBOR encoding: {e}"),
})
}
None => blueprint.construct_parameter_incrementally(
module.as_deref(),
validator.as_deref(),
ask_schema,
),
}
.map_err(|err| Error::Blueprint(err.into()))?;
eprintln!(
"{} {}",
" Applying"
.if_supports_color(Stderr, |s| s.purple())
.if_supports_color(Stderr, |s| s.bold()),
{
let padding = "\n ";
multiline(48, UplcData::to_hex(data.clone())).join(padding)
}
);
blueprint
.apply_parameter(module.as_deref(), validator.as_deref(), &data)
.map_err(|err| Error::Blueprint(err.into()))?;
let json = serde_json::to_string_pretty(&blueprint).unwrap();
match output {
None => {
println!("\n{json}\n");
}
Some(ref path) => {
fs::write(path, json).map_err(|error| Error::FileIo {
error,
path: path.clone(),
})?;
}
};
eprintln!(
"{}",
" Done"
.if_supports_color(Stderr, |s| s.purple())
.if_supports_color(Stderr, |s| s.bold()),
);
Ok(())
};
match input {
Some(path) => without_project(|| apply(path.clone())).map_err(|_| std::process::exit(1)),
None => with_project(None, false, false, false, |p| {
let path = p.blueprint_path(None);
apply(path)
})
.map_err(|_| std::process::exit(1)),
}
}
#[allow(clippy::result_large_err)]
fn ask_schema(
schema: &Annotated<Schema>,
definitions: &Definitions<Annotated<Schema>>,
) -> Result<PlutusData, blueprint::error::Error> {
match schema.annotated {
Schema::Data(Data::Integer) => {
let input = prompt_primitive("an integer", schema)?;
let n = BigInt::from_str(input.as_str()).map_err(|e| {
blueprint::error::Error::MalformedParameter {
hint: format!("Unable to convert input to integer: {e}"),
}
})?;
Ok(UplcData::integer(n))
}
Schema::Data(Data::Bytes) => {
let input = prompt_primitive("a byte-array", schema)?;
let bytes =
hex::decode(input).map_err(|e| blueprint::error::Error::MalformedParameter {
hint: format!("Invalid hex-encoded string: {e}"),
})?;
Ok(UplcData::bytestring(bytes))
}
Schema::Data(Data::List(Items::Many(ref decls))) => {
eprintln!(
" {}",
asking(schema, "Found", &format!("a {}-tuple", decls.len()))
);
let mut elems = vec![];
for (ix, decl) in decls.iter().enumerate() {
eprintln!(
" {} Tuple's {}{} element",
"Asking"
.if_supports_color(Stderr, |s| s.purple())
.if_supports_color(Stderr, |s| s.bold()),
ix + 1,
Ordinal::<usize>(ix + 1).suffix()
);
let inner_schema = lookup_declaration(&decl.clone(), definitions);
elems.push(ask_schema(&inner_schema, definitions)?);
}
Ok(UplcData::list(elems))
}
Schema::Data(Data::List(Items::One(ref decl))) => {
eprintln!(" {}", asking(schema, "Found", "a list"));
let inner_schema = lookup_declaration(&decl.clone().into(), definitions);
let mut elems = vec![];
while prompt_iterable(schema, "item")? {
elems.push(ask_schema(&inner_schema, definitions)?);
}
Ok(UplcData::list(elems))
}
Schema::Data(Data::Map(ref key_decl, ref value_decl)) => {
eprintln!(" {}", asking(schema, "Found", "an associative map"));
let key_schema = lookup_declaration(&key_decl.clone().into(), definitions);
let value_schema = lookup_declaration(&value_decl.clone().into(), definitions);
let mut elems = vec![];
while prompt_iterable(schema, "key/value entry")? {
elems.push((
ask_schema(&key_schema, definitions)?,
ask_schema(&value_schema, definitions)?,
));
}
Ok(UplcData::map(elems))
}
Schema::Data(Data::AnyOf(ref constructors)) => {
eprintln!(
" {}",
asking(
schema,
"Found",
if constructors.len() == 1 {
"a record"
} else {
"a data-type"
}
)
);
let ix = prompt_constructor(constructors, schema)?;
let mut fields = Vec::new();
for field in &constructors[ix].annotated.fields {
let inner_schema = lookup_declaration(field, definitions);
fields.push(ask_schema(&inner_schema, definitions)?);
}
Ok(UplcData::constr(ix.try_into().unwrap(), fields))
}
_ => unimplemented!(
"Hey! You've found a case that we haven't implemented yet. Yes, we've been a bit lazy on that one... If that use-case is important to you, please let us know on Discord or on Github."
),
}
}
fn lookup_declaration(
decl: &Annotated<Declaration<Data>>,
definitions: &Definitions<Annotated<Schema>>,
) -> Annotated<Schema> {
match decl.annotated {
Declaration::Inline(ref data) => Annotated {
title: decl.title.clone(),
description: decl.description.clone(),
annotated: Schema::Data(*(*data).clone()),
},
Declaration::Referenced(ref reference) => {
let schema = definitions
.lookup(reference)
.expect("reference to unknown type in blueprint?");
Annotated {
title: decl.title.clone().or_else(|| schema.title.clone()),
description: decl
.description
.clone()
.or_else(|| schema.description.clone()),
annotated: schema.annotated.clone(),
}
}
}
}
fn asking(schema: &Annotated<Schema>, verb: &str, type_name: &str) -> String {
let subject = get_subject(schema, type_name);
format!(
"{} {subject}",
verb.if_supports_color(Stderr, |s| s.purple())
.if_supports_color(Stderr, |s| s.bold()),
subject = subject,
)
}
#[allow(clippy::result_large_err)]
fn prompt_primitive(
type_name: &str,
schema: &Annotated<Schema>,
) -> Result<String, blueprint::error::Error> {
inquire::Text::new(&format!(" {}:", asking(schema, "Asking", type_name)))
.with_description(schema.description.as_ref())
.prompt()
.map_err(|e| blueprint::error::Error::MalformedParameter {
hint: format!("Invalid input received from prompt: {e}"),
})
}
#[allow(clippy::result_large_err)]
fn prompt_iterable(
schema: &Annotated<Schema>,
elem_name: &str,
) -> Result<bool, blueprint::error::Error> {
inquire::Confirm::new(&format!(
" {} one more {elem_name}?",
"Adding"
.if_supports_color(Stderr, |s| s.purple())
.if_supports_color(Stderr, |s| s.bold())
))
.with_description(schema.description.as_ref())
.with_default(true)
.prompt()
.map_err(|e| blueprint::error::Error::MalformedParameter {
hint: format!("Invalid input received from prompt: {e}"),
})
}
#[allow(clippy::result_large_err)]
fn prompt_constructor(
constructors: &[Annotated<Constructor>],
schema: &Annotated<Schema>,
) -> Result<usize, blueprint::error::Error> {
let mut choices = Vec::new();
for c in constructors {
let name = c
.title
.as_ref()
.cloned()
.unwrap_or_else(|| format!("{}", c.annotated.index));
choices.push(name);
}
let mut choice = choices
.first()
.expect("Data-type with no constructor?")
.to_string();
if choices.len() > 1 {
choice = inquire::Select::new(
&format!(
" {} constructor",
"Selecting"
.if_supports_color(Stderr, |s| s.purple())
.if_supports_color(Stderr, |s| s.bold())
),
choices.clone(),
)
.with_description(schema.description.as_ref())
.prompt()
.map_err(|e| blueprint::error::Error::MalformedParameter {
hint: format!("Invalid input received from prompt: {e}"),
})?;
}
Ok(choices.into_iter().position(|c| c == choice).unwrap())
}
fn get_subject<T>(schema: &Annotated<T>, type_name: &str) -> String {
schema
.title
.as_ref()
.map(|title| format!("{title} ({type_name})"))
.unwrap_or_else(|| type_name.to_string())
}
trait WithDescription<'a> {
fn with_description(self, opt: Option<&'a String>) -> Self;
}
impl<'a> WithDescription<'a> for inquire::Confirm<'a> {
fn with_description(
self: inquire::Confirm<'a>,
opt: Option<&'a String>,
) -> inquire::Confirm<'a> {
match opt {
Some(description) => self.with_help_message(description),
None => self,
}
}
}
impl<'a> WithDescription<'a> for inquire::Text<'a> {
fn with_description(self: inquire::Text<'a>, opt: Option<&'a String>) -> inquire::Text<'a> {
match opt {
Some(description) => self.with_help_message(description),
None => self,
}
}
}
impl<'a, T> WithDescription<'a> for inquire::Select<'a, T>
where
T: std::fmt::Display,
{
fn with_description(
self: inquire::Select<'a, T>,
opt: Option<&'a String>,
) -> inquire::Select<'a, T> {
match opt {
Some(description) => self.with_help_message(description),
None => self,
}
}
}