Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Blockfrost crates #313

Open
wants to merge 7 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

# this is for the new crate structure. The legacy code (current CML) still resides in the `rust` directory.
members = [
"blockfrost/rust",
"blockfrost/wasm",
"chain/rust",
"chain/wasm",
"chain/wasm/json-gen",
Expand Down
20 changes: 20 additions & 0 deletions blockfrost/rust/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[package]
name = "cml-blockfrost"
version = "0.1.0"
edition = "2018"

[lib]
crate-type = ["cdylib", "rlib"]

[dependencies]
cml-chain = { path = "../../chain/rust", version = "5.1.0" }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.57"
thiserror = "1.0.37"

# only used for direct_api
blockfrost = { version = "1.0.1", optional = true }

[features]
# This allows directly hooking into the blockfrost-rust crate
direct_api = ["blockfrost"]
93 changes: 93 additions & 0 deletions blockfrost/rust/src/direct_api.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
use blockfrost::{BlockfrostAPI, BlockfrostError};
use cml_chain::{
builders::tx_builder::{TransactionBuilderConfigBuilder, TxBuilderConfigField},
fees::LinearFee,
plutus::ExUnitPrices,
Coin, SubCoin,
};
use std::str::FromStr;

use crate::{parse_cost_models, BlockfrostParamsParseError};

#[derive(Debug, thiserror::Error)]
pub enum BlockfrostTxBuilderConfigError {
#[error("Parsing: {0}")]
Parsing(#[from] BlockfrostParamsParseError),
#[error("Blockfrost: {0}")]
Blockfrost(#[from] BlockfrostError),
}

/**
* Completely automated config creation via supplied blockfrost API.
* Both calls blockfrost via the passed API to get enough information
* and also parses the information to make a TransactionBuilderConfigBuilder
* with all necessary protocol parameter information set
*/
pub async fn make_tx_builder_cfg(
api: &BlockfrostAPI,
) -> Result<TransactionBuilderConfigBuilder, BlockfrostTxBuilderConfigError> {
let params = api.epochs_latest_parameters().await?;
let coins_per_utxo_byte = params
.coins_per_utxo_word
.ok_or(BlockfrostParamsParseError::MissingField(
TxBuilderConfigField::CoinsPerUtxoBytes,
))
.and_then(|c| {
Coin::from_str(&c).map_err(|_| {
BlockfrostParamsParseError::IncorrectFormat(TxBuilderConfigField::CoinsPerUtxoBytes)
})
})?;
let pool_deposit = Coin::from_str(&params.pool_deposit).map_err(|_| {
BlockfrostParamsParseError::IncorrectFormat(TxBuilderConfigField::PoolDeposit)
})?;
let key_deposit = Coin::from_str(&params.key_deposit).map_err(|_| {
BlockfrostParamsParseError::IncorrectFormat(TxBuilderConfigField::KeyDeposit)
})?;
let max_value_size = params
.max_val_size
.ok_or(BlockfrostParamsParseError::MissingField(
TxBuilderConfigField::MaxValueSize,
))
.and_then(|c| {
u32::from_str(&c).map_err(|_| {
BlockfrostParamsParseError::IncorrectFormat(TxBuilderConfigField::MaxValueSize)
})
})?;
let ex_unit_prices = match (params.price_mem, params.price_step) {
(Some(price_mem), Some(price_step)) => Ok(ExUnitPrices::new(
SubCoin::from_base10_f32(price_mem),
SubCoin::from_base10_f32(price_step),
)),
_ => Err(BlockfrostParamsParseError::MissingField(
TxBuilderConfigField::ExUnitPrices,
)),
}?;
let fee_algo = LinearFee::new(params.min_fee_a as u64, params.min_fee_b as u64);
let max_tx_size = params.max_tx_size as u32;
let collateral_percentage =
params
.collateral_percent
.ok_or(BlockfrostParamsParseError::MissingField(
TxBuilderConfigField::CollateralPercentage,
))? as u32;
let max_collateral_inputs =
params
.max_collateral_inputs
.ok_or(BlockfrostParamsParseError::MissingField(
TxBuilderConfigField::MaxCollateralInputs,
))? as u32;
let mut config_builder = TransactionBuilderConfigBuilder::new()
.fee_algo(fee_algo)
.coins_per_utxo_byte(coins_per_utxo_byte)
.pool_deposit(pool_deposit)
.key_deposit(key_deposit)
.max_value_size(max_value_size)
.max_tx_size(max_tx_size)
.ex_unit_prices(ex_unit_prices)
.collateral_percentage(collateral_percentage)
.max_collateral_inputs(max_collateral_inputs);
if let Some(cost_models) = params.cost_models {
config_builder = config_builder.cost_models(parse_cost_models(&cost_models)?);
}
Ok(config_builder)
}
110 changes: 110 additions & 0 deletions blockfrost/rust/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
use cml_chain::{
builders::tx_builder::TxBuilderConfigField,
plutus::{CostModels, Language},
DeserializeError,
};
use std::collections::HashMap;

#[cfg(feature = "direct_api")]
pub mod direct_api;

#[derive(Debug, thiserror::Error)]
pub enum CostModelsError {
#[error("Invalid object format: {0:?}")]
InvalidFormat(serde_json::Value),
#[error("Invalid cost format: {0:?}")]
InvalidCost(Option<serde_json::Value>),
#[error("Invalid op count: {0}")]
OpCount(usize),
// likely shouldn't happen as this would be checked earlier
#[error("Couldn't set: {0}")]
Setting(#[from] DeserializeError),
}

#[derive(Debug, thiserror::Error)]
pub enum BlockfrostParamsParseError {
#[error("Missing field: {0:?}")]
MissingField(TxBuilderConfigField),
#[error("Incorrect format in field: {0:?}")]
IncorrectFormat(TxBuilderConfigField),
#[error("Invalid cost models {0:?} for language {1:?}")]
CostModels(CostModelsError, Language),
}

pub fn parse_cost_model(
serde_value: &serde_json::Value,
language: Language,
) -> Result<Vec<i64>, CostModelsError> {
if let serde_json::Value::Object(cost_obj) = serde_value {
let mut costs = vec![];
// bad idea to assume it's ordered - depends on feature enabled
// and could possibly change
let mut keys: Vec<String> = cost_obj.keys().cloned().collect();
if keys.len() != CostModels::op_count(language) {
return Err(CostModelsError::OpCount(keys.len()));
}
keys.sort();
for key in keys {
let cost = cost_obj
.get(&key)
.and_then(|c| c.as_i64())
.ok_or_else(|| CostModelsError::InvalidCost(cost_obj.get(&key).cloned()))?;
costs.push(cost);
}
Ok(costs)
} else {
Err(CostModelsError::InvalidFormat(serde_value.clone()))
}
}

pub fn parse_sancho_cost_model(
serde_value: &serde_json::Value,
) -> Result<Vec<i64>, CostModelsError> {
if let serde_json::Value::Object(cost_obj) = serde_value {
let mut costs = vec![];
for i in 0..CostModels::PLUTUS_V3_COUNT {
let cost = cost_obj
.get(&i.to_string())
.and_then(|val| val.as_i64())
.ok_or_else(|| {
CostModelsError::InvalidCost(cost_obj.get(&i.to_string()).cloned())
})?;
costs.push(cost);
}
Ok(costs)
} else {
Err(CostModelsError::InvalidFormat(serde_value.clone()))
}
}

pub fn parse_cost_models(
costs: &HashMap<String, serde_json::Value>,
) -> Result<CostModels, BlockfrostParamsParseError> {
let mut cost_models = CostModels::default();
if let Some(plutus_v1) = costs.get("PlutusV1") {
cost_models
.set_plutus_v1(
parse_cost_model(plutus_v1, Language::PlutusV1)
.map_err(|e| BlockfrostParamsParseError::CostModels(e, Language::PlutusV1))?,
)
.map_err(|e| BlockfrostParamsParseError::CostModels(e.into(), Language::PlutusV1))?;
}
if let Some(plutus_v2) = costs.get("PlutusV2") {
cost_models
.set_plutus_v2(
parse_cost_model(plutus_v2, Language::PlutusV2)
.map_err(|e| BlockfrostParamsParseError::CostModels(e, Language::PlutusV2))?,
)
.map_err(|e| BlockfrostParamsParseError::CostModels(e.into(), Language::PlutusV2))?;
}
// Sancho testnet has a very different format for some reason
if let Some(plutus_v3) = costs.get("PlutusV3") {
cost_models
.set_plutus_v3(
parse_sancho_cost_model(plutus_v3)
.map_err(|e| BlockfrostParamsParseError::CostModels(e, Language::PlutusV3))?,
)
.map_err(|e| BlockfrostParamsParseError::CostModels(e.into(), Language::PlutusV3))?;
}
Ok(cost_models)
}
15 changes: 15 additions & 0 deletions blockfrost/wasm/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[package]
name = "cml-blockfrost-wasm"
version = "0.1.0"
edition = "2018"

[lib]
crate-type = ["cdylib", "rlib"]

[dependencies]
cml-blockfrost = { path = "../rust", version = "0.1.0" }
cml-chain = { path = "../../chain/rust", version = "5.1.0" }
cml-chain-wasm = { path = "../../chain/wasm", version = "5.1.0" }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.57"
wasm-bindgen = { version = "0.2", features=["serde-serialize"] }
Loading
Loading