Skip to content

Commit

Permalink
Blockfrost crates
Browse files Browse the repository at this point in the history
Rust and WASM crates for creating tx builders from blockfrost.

The rust crate can be directly used with the `blockfrost` crate when the
feature `direct_api` is enabled. If it is not then various parsing
ability is still exposed for cost models.

The WASM crate due to technical restrictions just exposes an endpoint
that takes in the response JSON and creates the config.

the cml/wasm crate exports this new `cml-blockfrost-wasm` functionality
which only increased compiled size from 896kb -> 911kb so should be fine
to include by default.

TODO: some documentation but this would conflict with #307's
documentation update so can be done at a later date.
  • Loading branch information
rooooooooob committed Mar 1, 2024
1 parent 34742b9 commit 1224706
Show file tree
Hide file tree
Showing 12 changed files with 1,030 additions and 2 deletions.
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)
}
101 changes: 101 additions & 0 deletions blockfrost/rust/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
use cml_chain::{
builders::tx_builder::TxBuilderConfigField,
plutus::{CostModels, Language},
Int,
};
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),
}

#[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<Int>, 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(Int::from(cost));
}
Ok(costs)
} else {
Err(CostModelsError::InvalidFormat(serde_value.clone()))
}
}

pub fn parse_sancho_cost_model(
serde_value: &serde_json::Value,
) -> Result<Vec<Int>, 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(cml_chain::Int::from(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::new();
if let Some(plutus_v1) = costs.get("PlutusV1") {
cost_models.plutus_v1 = Some(
parse_cost_model(plutus_v1, Language::PlutusV1)
.map_err(|e| BlockfrostParamsParseError::CostModels(e, Language::PlutusV1))?,
);
}
if let Some(plutus_v2) = costs.get("PlutusV2") {
cost_models.plutus_v2 = Some(
parse_cost_model(plutus_v2, Language::PlutusV2)
.map_err(|e| BlockfrostParamsParseError::CostModels(e, Language::PlutusV2))?,
);
}
// Sancho testnet has a very different format for some reason
if let Some(plutus_v3) = costs.get("PlutusV3") {
cost_models.plutus_v3 = Some(
parse_sancho_cost_model(plutus_v3)
.map_err(|e| BlockfrostParamsParseError::CostModels(e, 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", direct_api = false }
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

0 comments on commit 1224706

Please sign in to comment.