From fbbd58feb08206fb06037342c06252a284a81967 Mon Sep 17 00:00:00 2001 From: Mitchell Turner Date: Sat, 30 Mar 2024 15:42:46 -0700 Subject: [PATCH] Add nightly rustfmt checks (#171) * Add nightly rustfmt checks * fmt * Add nightly to CI * Try to use basic nightly --- .github/workflows/rust.yml | 20 +- .rustfmt.toml | 8 + README.md | 2 +- nau-scripts/build.rs | 6 +- nau-scripts/src/one_shot.rs | 41 ++-- .../always-succeeds-contract/build.rs | 6 +- .../always-succeeds-contract/src/logic.rs | 18 +- .../src/logic/script.rs | 35 ++- .../src/logic/tests.rs | 12 +- .../always-succeeds-contract/src/main.rs | 9 +- sample-dApps/checking_account/build.rs | 6 +- .../checking_account/checking/aiken.lock | 2 +- sample-dApps/checking_account/src/datum.rs | 11 +- .../src/endpoints/add_puller.rs | 29 ++- .../src/endpoints/fund_account.rs | 16 +- .../src/endpoints/init_account.rs | 27 ++- .../checking_account/src/endpoints/pull.rs | 18 +- .../src/endpoints/remove_puller.rs | 16 +- .../checking_account/src/endpoints/tests.rs | 49 ++-- sample-dApps/checking_account/src/lib.rs | 30 ++- sample-dApps/checking_account/src/lookups.rs | 22 +- sample-dApps/checking_account/src/main.rs | 21 +- .../src/scripts/checking_account_validtor.rs | 55 +++-- .../src/scripts/pull_validator.rs | 122 ++++++---- .../src/scripts/spend_token_policy.rs | 42 ++-- sample-dApps/checking_account/src/withdraw.rs | 19 +- .../free-minting-contract/src/logic.rs | 21 +- .../free-minting-contract/src/logic/script.rs | 22 +- .../free-minting-contract/src/main.rs | 13 +- sample-dApps/game-contract/src/logic.rs | 20 +- .../game-contract/src/logic/script.rs | 42 +++- sample-dApps/game-contract/src/logic/tests.rs | 8 +- sample-dApps/game-contract/src/main.rs | 12 +- sample-dApps/mint_nft/src/logic.rs | 22 +- sample-dApps/mint_nft/src/main.rs | 14 +- sample-dApps/time-locked-contract/build.rs | 6 +- .../time-locked-contract/src/logic.rs | 34 ++- .../time-locked-contract/src/logic/script.rs | 43 ++-- sample-dApps/time-locked-contract/src/main.rs | 10 +- src/error.rs | 9 +- src/ledger_client.rs | 21 +- src/ledger_client/test_ledger_client.rs | 68 ++++-- .../test_ledger_client/in_memory_storage.rs | 35 ++- .../local_persisted_storage.rs | 45 +++- src/ledger_client/test_ledger_client/tests.rs | 47 +++- src/lib.rs | 10 +- src/logic.rs | 13 +- src/logic/error.rs | 10 +- src/output.rs | 12 +- src/policy_id.rs | 5 +- src/scripts.rs | 12 +- src/scripts/context.rs | 48 +++- src/scripts/plutus_minting_policy.rs | 55 +++-- src/scripts/plutus_validator.rs | 85 +++++-- src/scripts/plutus_validator/plutus_data.rs | 42 +++- src/scripts/plutus_validator/tests.rs | 5 +- src/scripts/plutus_validator/tests/game.rs | 5 +- src/scripts/plutus_validator/tests/hello.rs | 14 +- src/scripts/raw_script.rs | 5 +- src/smart_contract.rs | 13 +- src/transaction.rs | 65 +++-- src/transaction/nested_value_map.rs | 10 +- src/trireme_ledger_client.rs | 156 ++++++++---- src/trireme_ledger_client/cml_client.rs | 227 ++++++++++++++---- .../cml_client/blockfrost_ledger.rs | 62 +++-- .../cml_client/issuance_helpers.rs | 139 +++++++---- .../cml_client/key_manager.rs | 28 ++- .../cml_client/ogmios_scrolls_ledger.rs | 50 +++- .../cml_client/plutus_data_interop.rs | 22 +- src/trireme_ledger_client/cml_client/tests.rs | 25 +- .../cml_client/tests/test_helpers.rs | 47 +++- .../raw_secret_phrase.rs | 36 ++- src/trireme_ledger_client/secret_phrase.rs | 20 +- .../terminal_password_phrase.rs | 40 ++- src/values.rs | 22 +- tests/always_mints_contract.rs | 47 ++-- tests/transfer.rs | 20 +- trireme/src/balance.rs | 11 +- trireme/src/environment.rs | 63 +++-- trireme/src/logic.rs | 12 +- trireme/src/main.rs | 29 ++- 81 files changed, 1893 insertions(+), 706 deletions(-) create mode 100644 .rustfmt.toml diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 4ba1979..5ae0dc5 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -20,9 +20,25 @@ jobs: run: cargo build --verbose --workspace - name: Run tests run: cargo test --verbose --workspace - - name: Lint - run: cargo fmt --all -- --check - name: Clippy run: cargo clippy --all-targets --all-features -- -D warnings + + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Install latest nightly + uses: dtolnay/rust-toolchain@master + with: + toolchain: nightly + components: rustfmt + - name: Rustfmt check + run: cargo +nightly fmt --all -- --check + + + audit: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 - name: Audit run: cargo audit diff --git a/.rustfmt.toml b/.rustfmt.toml new file mode 100644 index 0000000..a9f1797 --- /dev/null +++ b/.rustfmt.toml @@ -0,0 +1,8 @@ +max_width = 90 +normalize_comments = true +imports_layout = "Vertical" +imports_granularity = "Crate" +trailing_semicolon = false +edition = "2021" +use_try_shorthand = true +use_field_init_shorthand = true \ No newline at end of file diff --git a/README.md b/README.md index d1961a6..23fbd9f 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ FYI, CI requires these commands to pass. So, try to run them locally to save you ``` cargo build --workspace cargo test --workspace -cargo fmt --all -- --check +cargo +nightly fmt --all -- --check cargo clippy --all-targets --all-features -- -D warnings ``` diff --git a/nau-scripts/build.rs b/nau-scripts/build.rs index 05e7d5c..999ec60 100644 --- a/nau-scripts/build.rs +++ b/nau-scripts/build.rs @@ -1,6 +1,8 @@ use aiken_lang::ast::Tracing; -use aiken_project::telemetry::Terminal; -use aiken_project::Project; +use aiken_project::{ + telemetry::Terminal, + Project, +}; const MINT_NFT_PROJECT: &str = "./aiken/mint_nft"; diff --git a/nau-scripts/src/one_shot.rs b/nau-scripts/src/one_shot.rs index 4e1b168..2b41fe6 100644 --- a/nau-scripts/src/one_shot.rs +++ b/nau-scripts/src/one_shot.rs @@ -1,10 +1,14 @@ -use naumachia::scripts::raw_script::BlueprintFile; use naumachia::{ output::Output as NauOutput, scripts::{ plutus_minting_policy::OneParamPlutusPolicy, - plutus_validator::plutus_data::{Constr, PlutusData}, - ScriptError, ScriptResult, + plutus_validator::plutus_data::{ + Constr, + PlutusData, + }, + raw_script::BlueprintFile, + ScriptError, + ScriptResult, }, }; @@ -53,16 +57,16 @@ impl From for PlutusData { } } -pub fn get_parameterized_script() -> ScriptResult> { +pub fn get_parameterized_script( +) -> ScriptResult> { let script_file: BlueprintFile = serde_json::from_str(BLUEPRINT) .map_err(|e| ScriptError::FailedToConstruct(e.to_string()))?; - let validator_blueprint = - script_file - .get_validator(VALIDATOR_NAME) - .ok_or(ScriptError::FailedToConstruct(format!( - "Validator not listed in Blueprint: {:?}", - VALIDATOR_NAME - )))?; + let validator_blueprint = script_file.get_validator(VALIDATOR_NAME).ok_or( + ScriptError::FailedToConstruct(format!( + "Validator not listed in Blueprint: {:?}", + VALIDATOR_NAME + )), + )?; let raw_script_validator = OneParamPlutusPolicy::from_blueprint(validator_blueprint) .map_err(|e| ScriptError::FailedToConstruct(e.to_string()))?; Ok(raw_script_validator) @@ -72,10 +76,17 @@ pub fn get_parameterized_script() -> ScriptResult SCLogicResult> { match endpoint { - AlwaysSucceedsEndpoints::Lock { amount } => impl_lock(ledger_client, amount).await, + AlwaysSucceedsEndpoints::Lock { amount } => { + impl_lock(ledger_client, amount).await + } AlwaysSucceedsEndpoints::Claim { output_id } => { impl_claim(ledger_client, output_id).await } diff --git a/sample-dApps/always-succeeds-contract/src/logic/script.rs b/sample-dApps/always-succeeds-contract/src/logic/script.rs index 853a55d..1ae6a2f 100644 --- a/sample-dApps/always-succeeds-contract/src/logic/script.rs +++ b/sample-dApps/always-succeeds-contract/src/logic/script.rs @@ -1,6 +1,9 @@ -use naumachia::scripts::plutus_validator::PlutusValidator; -use naumachia::scripts::raw_script::BlueprintFile; -use naumachia::scripts::{ScriptError, ScriptResult}; +use naumachia::scripts::{ + plutus_validator::PlutusValidator, + raw_script::BlueprintFile, + ScriptError, + ScriptResult, +}; const BLUEPRINT: &str = include_str!("../../always_succeeds/plutus.json"); const VALIDATOR_NAME: &str = "always_true.spend"; @@ -8,13 +11,12 @@ const VALIDATOR_NAME: &str = "always_true.spend"; pub fn get_script() -> ScriptResult> { let script_file: BlueprintFile = serde_json::from_str(BLUEPRINT) .map_err(|e| ScriptError::FailedToConstruct(e.to_string()))?; - let validator_blueprint = - script_file - .get_validator(VALIDATOR_NAME) - .ok_or(ScriptError::FailedToConstruct(format!( - "Validator not listed in Blueprint: {:?}", - VALIDATOR_NAME - )))?; + let validator_blueprint = script_file.get_validator(VALIDATOR_NAME).ok_or( + ScriptError::FailedToConstruct(format!( + "Validator not listed in Blueprint: {:?}", + VALIDATOR_NAME + )), + )?; let raw_script_validator = PlutusValidator::from_blueprint(validator_blueprint) .map_err(|e| ScriptError::FailedToConstruct(e.to_string()))?; Ok(raw_script_validator) @@ -23,9 +25,16 @@ pub fn get_script() -> ScriptResult> { #[cfg(test)] mod tests { use super::*; - use naumachia::scripts::context::{pub_key_hash_from_address_if_available, ContextBuilder}; - use naumachia::scripts::Validator; - use naumachia::Address; + use naumachia::{ + scripts::{ + context::{ + pub_key_hash_from_address_if_available, + ContextBuilder, + }, + Validator, + }, + Address, + }; #[test] fn test() { diff --git a/sample-dApps/always-succeeds-contract/src/logic/tests.rs b/sample-dApps/always-succeeds-contract/src/logic/tests.rs index 38322eb..e83bfa6 100644 --- a/sample-dApps/always-succeeds-contract/src/logic/tests.rs +++ b/sample-dApps/always-succeeds-contract/src/logic/tests.rs @@ -1,7 +1,13 @@ use super::*; -use naumachia::ledger_client::test_ledger_client::TestLedgerClientBuilder; -use naumachia::smart_contract::{SmartContract, SmartContractTrait}; -use naumachia::{Address, Network}; +use naumachia::{ + ledger_client::test_ledger_client::TestLedgerClientBuilder, + smart_contract::{ + SmartContract, + SmartContractTrait, + }, + Address, + Network, +}; #[tokio::test] async fn lock_and_claim() { diff --git a/sample-dApps/always-succeeds-contract/src/main.rs b/sample-dApps/always-succeeds-contract/src/main.rs index 33904fd..6ef21f6 100644 --- a/sample-dApps/always-succeeds-contract/src/main.rs +++ b/sample-dApps/always-succeeds-contract/src/main.rs @@ -1,11 +1,16 @@ use always_succeeds_contract::logic::{ - AlwaysSucceedsEndpoints, AlwaysSucceedsLogic, AlwaysSucceedsLookupResponses, + AlwaysSucceedsEndpoints, + AlwaysSucceedsLogic, + AlwaysSucceedsLookupResponses, AlwaysSucceedsLookups, }; use clap::Parser; use naumachia::{ output::OutputId, - smart_contract::{SmartContract, SmartContractTrait}, + smart_contract::{ + SmartContract, + SmartContractTrait, + }, trireme_ledger_client::get_trireme_ledger_client_from_file, }; diff --git a/sample-dApps/checking_account/build.rs b/sample-dApps/checking_account/build.rs index 4e2adbf..63536f0 100644 --- a/sample-dApps/checking_account/build.rs +++ b/sample-dApps/checking_account/build.rs @@ -1,6 +1,8 @@ use aiken_lang::ast::Tracing; -use aiken_project::telemetry::Terminal; -use aiken_project::Project; +use aiken_project::{ + telemetry::Terminal, + Project, +}; const PROJECT: &str = "./checking"; diff --git a/sample-dApps/checking_account/checking/aiken.lock b/sample-dApps/checking_account/checking/aiken.lock index 6a17cc7..acb619d 100644 --- a/sample-dApps/checking_account/checking/aiken.lock +++ b/sample-dApps/checking_account/checking/aiken.lock @@ -13,4 +13,4 @@ requirements = [] source = "github" [etags] -"aiken-lang/stdlib@main" = [{ secs_since_epoch = 1708887379, nanos_since_epoch = 415727333 }, "cf946239d3dd481ed41f20e56bf24910b5229ea35aa171a708edc2a47fc20a7b"] +"aiken-lang/stdlib@main" = [{ secs_since_epoch = 1711836891, nanos_since_epoch = 667346334 }, "2a710731e0127ec3e21c6c3962a0254c98602e7428b33fc4fcaa67ab368ce1b1"] diff --git a/sample-dApps/checking_account/src/datum.rs b/sample-dApps/checking_account/src/datum.rs index 59afb5f..765ae08 100644 --- a/sample-dApps/checking_account/src/datum.rs +++ b/sample-dApps/checking_account/src/datum.rs @@ -1,5 +1,10 @@ -use naumachia::scripts::context::PubKeyHash; -use naumachia::scripts::plutus_validator::plutus_data::{Constr, PlutusData}; +use naumachia::scripts::{ + context::PubKeyHash, + plutus_validator::plutus_data::{ + Constr, + PlutusData, + }, +}; #[derive(Debug, Clone, Eq, PartialEq, Hash)] pub enum CheckingAccountDatums { @@ -149,7 +154,7 @@ fn allowed_puller(fields: &[PlutusData]) -> Result { let datum = CheckingAccountDatums::AllowedPuller(AllowedPuller { owner, puller, - amount_lovelace: amount_lovelace as u64, //TODO + amount_lovelace: amount_lovelace as u64, // TODO next_pull, period, spending_token, diff --git a/sample-dApps/checking_account/src/endpoints/add_puller.rs b/sample-dApps/checking_account/src/endpoints/add_puller.rs index 665a25d..43696e6 100644 --- a/sample-dApps/checking_account/src/endpoints/add_puller.rs +++ b/sample-dApps/checking_account/src/endpoints/add_puller.rs @@ -1,14 +1,26 @@ use crate::{ - pull_validator, spend_token_policy, AllowedPuller, CheckingAccountDatums, CheckingAccountError, + pull_validator, + spend_token_policy, + AllowedPuller, + CheckingAccountDatums, + CheckingAccountError, SPEND_TOKEN_ASSET_NAME, }; -use naumachia::logic::error::{SCLogicError, SCLogicResult}; use naumachia::{ ledger_client::LedgerClient, + logic::error::{ + SCLogicError, + SCLogicResult, + }, policy_id::PolicyId, - scripts::context::{pub_key_hash_from_address_if_available, PubKeyHash}, - scripts::MintingPolicy, - scripts::Validator, + scripts::{ + context::{ + pub_key_hash_from_address_if_available, + PubKeyHash, + }, + MintingPolicy, + Validator, + }, transaction::TxActions, values::Values, }; @@ -29,9 +41,10 @@ pub async fn add_puller>( .signer_base_address() .await .map_err(|e| SCLogicError::Endpoint(Box::new(e)))?; - let owner = pub_key_hash_from_address_if_available(&me).ok_or(SCLogicError::Endpoint( - Box::new(CheckingAccountError::InvalidAddress(me.clone())), - ))?; + let owner = + pub_key_hash_from_address_if_available(&me).ok_or(SCLogicError::Endpoint( + Box::new(CheckingAccountError::InvalidAddress(me.clone())), + ))?; let nft_id_bytes = hex::decode(checking_account_nft_id).unwrap(); let my_pubkey = pub_key_hash_from_address_if_available(&me).unwrap(); diff --git a/sample-dApps/checking_account/src/endpoints/fund_account.rs b/sample-dApps/checking_account/src/endpoints/fund_account.rs index 6f0bb79..af11df6 100644 --- a/sample-dApps/checking_account/src/endpoints/fund_account.rs +++ b/sample-dApps/checking_account/src/endpoints/fund_account.rs @@ -1,7 +1,17 @@ -use crate::{checking_account_validator, CheckingAccountDatums, CheckingAccountError}; -use naumachia::logic::error::{SCLogicError, SCLogicResult}; +use crate::{ + checking_account_validator, + CheckingAccountDatums, + CheckingAccountError, +}; use naumachia::{ - ledger_client::LedgerClient, output::OutputId, policy_id::PolicyId, scripts::Validator, + ledger_client::LedgerClient, + logic::error::{ + SCLogicError, + SCLogicResult, + }, + output::OutputId, + policy_id::PolicyId, + scripts::Validator, transaction::TxActions, }; diff --git a/sample-dApps/checking_account/src/endpoints/init_account.rs b/sample-dApps/checking_account/src/endpoints/init_account.rs index 6949baa..2de8a8d 100644 --- a/sample-dApps/checking_account/src/endpoints/init_account.rs +++ b/sample-dApps/checking_account/src/endpoints/init_account.rs @@ -1,16 +1,29 @@ use crate::{ - checking_account_validator, spend_token_policy, CheckingAccount, CheckingAccountDatums, - CheckingAccountError, CHECKING_ACCOUNT_NFT_ASSET_NAME, + checking_account_validator, + spend_token_policy, + CheckingAccount, + CheckingAccountDatums, + CheckingAccountError, + CHECKING_ACCOUNT_NFT_ASSET_NAME, +}; +use nau_scripts::{ + one_shot, + one_shot::OutputReference, }; -use nau_scripts::{one_shot, one_shot::OutputReference}; -use naumachia::logic::error::{SCLogicError, SCLogicResult}; use naumachia::{ ledger_client::LedgerClient, + logic::error::{ + SCLogicError, + SCLogicResult, + }, output::Output, policy_id::PolicyId, - scripts::context::pub_key_hash_from_address_if_available, - scripts::Validator, - scripts::{MintingPolicy, ScriptError}, + scripts::{ + context::pub_key_hash_from_address_if_available, + MintingPolicy, + ScriptError, + Validator, + }, transaction::TxActions, values::Values, }; diff --git a/sample-dApps/checking_account/src/endpoints/pull.rs b/sample-dApps/checking_account/src/endpoints/pull.rs index 283e43f..e1ebfee 100644 --- a/sample-dApps/checking_account/src/endpoints/pull.rs +++ b/sample-dApps/checking_account/src/endpoints/pull.rs @@ -1,11 +1,21 @@ use crate::{ - checking_account_validator, pull_validator, AllowedPuller, CheckingAccountDatums, + checking_account_validator, + pull_validator, + AllowedPuller, + CheckingAccountDatums, CheckingAccountError, }; -use naumachia::logic::error::{SCLogicError, SCLogicResult}; use naumachia::{ - ledger_client::LedgerClient, output::OutputId, policy_id::PolicyId, scripts::Validator, - transaction::TxActions, values::Values, + ledger_client::LedgerClient, + logic::error::{ + SCLogicError, + SCLogicResult, + }, + output::OutputId, + policy_id::PolicyId, + scripts::Validator, + transaction::TxActions, + values::Values, }; pub async fn pull_from_account>( diff --git a/sample-dApps/checking_account/src/endpoints/remove_puller.rs b/sample-dApps/checking_account/src/endpoints/remove_puller.rs index 8d38431..9baeb05 100644 --- a/sample-dApps/checking_account/src/endpoints/remove_puller.rs +++ b/sample-dApps/checking_account/src/endpoints/remove_puller.rs @@ -1,7 +1,17 @@ -use crate::{pull_validator, CheckingAccountDatums, CheckingAccountError}; -use naumachia::logic::error::{SCLogicError, SCLogicResult}; +use crate::{ + pull_validator, + CheckingAccountDatums, + CheckingAccountError, +}; use naumachia::{ - ledger_client::LedgerClient, output::OutputId, scripts::Validator, transaction::TxActions, + ledger_client::LedgerClient, + logic::error::{ + SCLogicError, + SCLogicResult, + }, + output::OutputId, + scripts::Validator, + transaction::TxActions, }; pub async fn remove_puller>( diff --git a/sample-dApps/checking_account/src/endpoints/tests.rs b/sample-dApps/checking_account/src/endpoints/tests.rs index ce7a8a9..c7b00ab 100644 --- a/sample-dApps/checking_account/src/endpoints/tests.rs +++ b/sample-dApps/checking_account/src/endpoints/tests.rs @@ -1,19 +1,34 @@ -use crate::datum::CheckingAccountDatums; use crate::{ - checking_account_validator, scripts::pull_validator::pull_validator, spend_token_policy, - AllowedPuller, CheckingAccount, CheckingAccountEndpoints, CheckingAccountLogic, - CHECKING_ACCOUNT_NFT_ASSET_NAME, SPEND_TOKEN_ASSET_NAME, + checking_account_validator, + datum::CheckingAccountDatums, + scripts::pull_validator::pull_validator, + spend_token_policy, + AllowedPuller, + CheckingAccount, + CheckingAccountEndpoints, + CheckingAccountLogic, + CHECKING_ACCOUNT_NFT_ASSET_NAME, + SPEND_TOKEN_ASSET_NAME, }; -use naumachia::logic::error::SCLogicError; use naumachia::{ error::Error, - ledger_client::test_ledger_client::TestLedgerClientBuilder, - ledger_client::LedgerClient, + ledger_client::{ + test_ledger_client::TestLedgerClientBuilder, + LedgerClient, + }, + logic::error::SCLogicError, policy_id::PolicyId, - scripts::context::pub_key_hash_from_address_if_available, - scripts::{MintingPolicy, Validator}, - smart_contract::{SmartContract, SmartContractTrait}, - Address, Network, + scripts::{ + context::pub_key_hash_from_address_if_available, + MintingPolicy, + Validator, + }, + smart_contract::{ + SmartContract, + SmartContractTrait, + }, + Address, + Network, }; #[tokio::test] @@ -49,7 +64,8 @@ async fn init_creates_instance_with_correct_balance() { let value = script_output.values().get(&PolicyId::Lovelace).unwrap(); assert_eq!(value, account_amount); let nft = script_output.values().as_iter().find(|(policy_id, amt)| { - policy_id.asset_name() == Some(CHECKING_ACCOUNT_NFT_ASSET_NAME.to_string()) && **amt == 1 + policy_id.asset_name() == Some(CHECKING_ACCOUNT_NFT_ASSET_NAME.to_string()) + && **amt == 1 }); assert!(nft.is_some()); } @@ -242,9 +258,11 @@ async fn withdraw_from_account__replaces_existing_balance_with_updated_amount() } #[tokio::test] -async fn pull_from_account__replaces_existing_balances_with_updated_amounts_and_updates_datum() { +async fn pull_from_account__replaces_existing_balances_with_updated_amounts_and_updates_datum( +) { let owner_address = Address::from_bech32("addr_test1qpuy2q9xel76qxdw8r29skldzc876cdgg9cugfg7mwh0zvpg3292mxuf3kq7nysjumlxjrlsfn9tp85r0l54l29x3qcs7nvyfm").unwrap(); - let owner_pubkey_hash = pub_key_hash_from_address_if_available(&owner_address).unwrap(); + let owner_pubkey_hash = + pub_key_hash_from_address_if_available(&owner_address).unwrap(); let puller = Address::from_bech32("addr_test1qrmezjhpelwzvz83wjl0e6mx766de7j3nksu2338s00yzx870xyxfa97xyz2zn5rknyntu5g0c66s7ktjnx0p6f0an6s3dyxwr").unwrap(); let allow_puller_script = pull_validator().unwrap(); @@ -360,7 +378,8 @@ async fn pull_from_account__replaces_existing_balances_with_updated_amounts_and_ #[tokio::test] async fn pull_from_account__fails_if_time_not_past_next_pull_time() { let owner_address = Address::from_bech32("addr_test1qpuy2q9xel76qxdw8r29skldzc876cdgg9cugfg7mwh0zvpg3292mxuf3kq7nysjumlxjrlsfn9tp85r0l54l29x3qcs7nvyfm").unwrap(); - let owner_pubkey_hash = pub_key_hash_from_address_if_available(&owner_address).unwrap(); + let owner_pubkey_hash = + pub_key_hash_from_address_if_available(&owner_address).unwrap(); let puller = Address::from_bech32("addr_test1qrmezjhpelwzvz83wjl0e6mx766de7j3nksu2338s00yzx870xyxfa97xyz2zn5rknyntu5g0c66s7ktjnx0p6f0an6s3dyxwr").unwrap(); let allow_puller_script = pull_validator().unwrap(); diff --git a/sample-dApps/checking_account/src/lib.rs b/sample-dApps/checking_account/src/lib.rs index 91c3a40..28a9cba 100644 --- a/sample-dApps/checking_account/src/lib.rs +++ b/sample-dApps/checking_account/src/lib.rs @@ -1,21 +1,35 @@ -use crate::lookups::get_my_accounts; use crate::{ + lookups::get_my_accounts, scripts::{ - checking_account_validtor::checking_account_validator, pull_validator::pull_validator, + checking_account_validtor::checking_account_validator, + pull_validator::pull_validator, spend_token_policy::spend_token_policy, }, withdraw::withdraw_from_account, }; use async_trait::async_trait; -use datum::{AllowedPuller, CheckingAccount, CheckingAccountDatums}; +use datum::{ + AllowedPuller, + CheckingAccount, + CheckingAccountDatums, +}; use endpoints::{ - add_puller::add_puller, fund_account::fund_account, init_account::init_account, - pull::pull_from_account, remove_puller::remove_puller, + add_puller::add_puller, + fund_account::fund_account, + init_account::init_account, + pull::pull_from_account, + remove_puller::remove_puller, }; -use naumachia::logic::error::SCLogicResult; use naumachia::{ - ledger_client::LedgerClient, logic::SCLogic, output::OutputId, scripts::context::PubKeyHash, - transaction::TxActions, Address, + ledger_client::LedgerClient, + logic::{ + error::SCLogicResult, + SCLogic, + }, + output::OutputId, + scripts::context::PubKeyHash, + transaction::TxActions, + Address, }; use thiserror::Error; diff --git a/sample-dApps/checking_account/src/lookups.rs b/sample-dApps/checking_account/src/lookups.rs index 3613fed..6b6d983 100644 --- a/sample-dApps/checking_account/src/lookups.rs +++ b/sample-dApps/checking_account/src/lookups.rs @@ -1,11 +1,23 @@ use crate::{ - checking_account_validator, pull_validator, Account, AccountPuller, CheckingAccountDatums, - CheckingAccountLookupResponses, CHECKING_ACCOUNT_NFT_ASSET_NAME, + checking_account_validator, + pull_validator, + Account, + AccountPuller, + CheckingAccountDatums, + CheckingAccountLookupResponses, + CHECKING_ACCOUNT_NFT_ASSET_NAME, }; -use naumachia::logic::error::{SCLogicError, SCLogicResult}; use naumachia::{ - ledger_client::LedgerClient, policy_id::PolicyId, - scripts::context::pub_key_hash_from_address_if_available, scripts::Validator, + ledger_client::LedgerClient, + logic::error::{ + SCLogicError, + SCLogicResult, + }, + policy_id::PolicyId, + scripts::{ + context::pub_key_hash_from_address_if_available, + Validator, + }, }; pub async fn get_my_accounts>( diff --git a/sample-dApps/checking_account/src/main.rs b/sample-dApps/checking_account/src/main.rs index 6779b33..78793c5 100644 --- a/sample-dApps/checking_account/src/main.rs +++ b/sample-dApps/checking_account/src/main.rs @@ -1,13 +1,18 @@ use anyhow::Result; use checking::{ - CheckingAccountEndpoints, CheckingAccountLogic, CheckingAccountLookupResponses, + CheckingAccountEndpoints, + CheckingAccountLogic, + CheckingAccountLookupResponses, CheckingAccountLookups, }; use clap::Parser; -use naumachia::scripts::context::PubKeyHash; -use naumachia::transaction::TxId; use naumachia::{ - smart_contract::{SmartContract, SmartContractTrait}, + scripts::context::PubKeyHash, + smart_contract::{ + SmartContract, + SmartContractTrait, + }, + transaction::TxId, trireme_ledger_client::get_trireme_ledger_client_from_file, }; @@ -36,7 +41,9 @@ async fn main() -> Result<()> { tracing_subscriber::fmt::init(); let args = Args::parse(); match args.action { - ActionParams::Init { starting_ada } => init_checking_account_impl(starting_ada).await?, + ActionParams::Init { starting_ada } => { + init_checking_account_impl(starting_ada).await? + } ActionParams::MyAccounts => my_account_impl().await?, ActionParams::AddPuller => add_puller_impl().await?, } @@ -51,7 +58,9 @@ async fn hit_endpoint(endpoint: CheckingAccountEndpoints) -> Result { Ok(res) } -async fn run_lookup(lookup: CheckingAccountLookups) -> Result { +async fn run_lookup( + lookup: CheckingAccountLookups, +) -> Result { let logic = CheckingAccountLogic; let ledger_client = get_trireme_ledger_client_from_file().await?; let contract = SmartContract::new(logic, ledger_client); diff --git a/sample-dApps/checking_account/src/scripts/checking_account_validtor.rs b/sample-dApps/checking_account/src/scripts/checking_account_validtor.rs index 7712efd..886e6e3 100644 --- a/sample-dApps/checking_account/src/scripts/checking_account_validtor.rs +++ b/sample-dApps/checking_account/src/scripts/checking_account_validtor.rs @@ -1,8 +1,13 @@ use crate::datum::CheckingAccountDatums; -use naumachia::scripts::plutus_validator::plutus_data::PlutusData; -use naumachia::scripts::plutus_validator::PlutusValidator; -use naumachia::scripts::raw_script::BlueprintFile; -use naumachia::scripts::{ScriptError, ScriptResult}; +use naumachia::scripts::{ + plutus_validator::{ + plutus_data::PlutusData, + PlutusValidator, + }, + raw_script::BlueprintFile, + ScriptError, + ScriptResult, +}; const BLUEPRINT: &str = include_str!("../../checking/plutus.json"); const VALIDATOR_NAME: &str = "checking_account_validator.spend"; @@ -23,7 +28,8 @@ impl From for PlutusData { } } -pub fn checking_account_validator() -> ScriptResult> { +pub fn checking_account_validator( +) -> ScriptResult> { let blueprint: BlueprintFile = serde_json::from_str(BLUEPRINT) .map_err(|e| ScriptError::FailedToConstruct(e.to_string()))?; let validator_blueprint = @@ -43,9 +49,16 @@ mod tests { use super::*; use crate::datum::CheckingAccount; use hex; - use naumachia::scripts::context::{pub_key_hash_from_address_if_available, ContextBuilder}; - use naumachia::scripts::Validator; - use naumachia::Address; + use naumachia::{ + scripts::{ + context::{ + pub_key_hash_from_address_if_available, + ContextBuilder, + }, + Validator, + }, + Address, + }; #[test] fn succeeds_if_spending_token_in_inputs() { @@ -55,8 +68,10 @@ mod tests { let signer_pkh = pub_key_hash_from_address_if_available(&signer).unwrap(); let ctx = ContextBuilder::new(signer_pkh) .with_input( - &hex::decode("73d65e0b9b68ebf3971b6ccddc75900dd62f9845f5ab972e469c5d803973015b") - .unwrap(), + &hex::decode( + "73d65e0b9b68ebf3971b6ccddc75900dd62f9845f5ab972e469c5d803973015b", + ) + .unwrap(), 0, &signer, ) @@ -64,9 +79,10 @@ mod tests { .finish_input() .build_spend(&vec![], 0); - let owner = - Address::from_bech32("addr_test1vqm77xl444msdszx9s982zu95hh03ztw4rsp8xcs2ty3xucr40ujs") - .unwrap(); + let owner = Address::from_bech32( + "addr_test1vqm77xl444msdszx9s982zu95hh03ztw4rsp8xcs2ty3xucr40ujs", + ) + .unwrap(); let owner_pubkey_hash = pub_key_hash_from_address_if_available(&owner).unwrap(); let datum = CheckingAccount { owner: owner_pubkey_hash, @@ -85,17 +101,20 @@ mod tests { let signer_pkh = pub_key_hash_from_address_if_available(&signer).unwrap(); let ctx = ContextBuilder::new(signer_pkh) .with_input( - &hex::decode("73d65e0b9b68ebf3971b6ccddc75900dd62f9845f5ab972e469c5d803973015b") - .unwrap(), + &hex::decode( + "73d65e0b9b68ebf3971b6ccddc75900dd62f9845f5ab972e469c5d803973015b", + ) + .unwrap(), 0, &signer, ) .finish_input() .build_spend(&vec![], 0); - let owner = - Address::from_bech32("addr_test1vqm77xl444msdszx9s982zu95hh03ztw4rsp8xcs2ty3xucr40ujs") - .unwrap(); + let owner = Address::from_bech32( + "addr_test1vqm77xl444msdszx9s982zu95hh03ztw4rsp8xcs2ty3xucr40ujs", + ) + .unwrap(); let owner_pubkey_hash = pub_key_hash_from_address_if_available(&owner).unwrap(); let datum = CheckingAccount { owner: owner_pubkey_hash, diff --git a/sample-dApps/checking_account/src/scripts/pull_validator.rs b/sample-dApps/checking_account/src/scripts/pull_validator.rs index 5f26ee8..e2bbe4d 100644 --- a/sample-dApps/checking_account/src/scripts/pull_validator.rs +++ b/sample-dApps/checking_account/src/scripts/pull_validator.rs @@ -1,7 +1,10 @@ use crate::datum::CheckingAccountDatums; -use naumachia::scripts::plutus_validator::PlutusValidator; -use naumachia::scripts::raw_script::BlueprintFile; -use naumachia::scripts::{ScriptError, ScriptResult}; +use naumachia::scripts::{ + plutus_validator::PlutusValidator, + raw_script::BlueprintFile, + ScriptError, + ScriptResult, +}; const SCRIPT_RAW: &str = include_str!("../../checking/plutus.json"); const VALIDATOR_NAME: &str = "pull_validator.spend"; @@ -25,13 +28,26 @@ pub fn pull_validator() -> ScriptResult CheckingAccount { - owner: wrong_owner_pubkey_hash, - ..old_checking_account + CheckingAccountDatums::CheckingAccount(old_checking_account) => { + CheckingAccount { + owner: wrong_owner_pubkey_hash, + ..old_checking_account + } + .into() } - .into(), _ => panic!("wrong variant"), }; ctx_builder.account_output_datum = Some(new_datum); - //then + // then let input_datum = ctx_builder.input_datum.clone().unwrap(); let ctx = ctx_builder.build(); let _eval = script.execute(input_datum, (), ctx).unwrap_err(); @@ -543,16 +566,18 @@ mod tests { // when let new_datum = match ctx_builder.account_output_datum.unwrap() { - CheckingAccountDatums::CheckingAccount(old_checking_account) => CheckingAccount { - spend_token_policy: bad_token_id, - ..old_checking_account + CheckingAccountDatums::CheckingAccount(old_checking_account) => { + CheckingAccount { + spend_token_policy: bad_token_id, + ..old_checking_account + } + .into() } - .into(), _ => panic!("wrong variant"), }; ctx_builder.account_output_datum = Some(new_datum); - //then + // then let input_datum = ctx_builder.input_datum.clone().unwrap(); let ctx = ctx_builder.build(); let _eval = script.execute(input_datum, (), ctx).unwrap_err(); @@ -560,9 +585,10 @@ mod tests { #[test] fn execute__remove_happy_path() { - let account_address = - Address::from_bech32("addr_test1vz3ppzmmzuz0nlsjeyrqjm4pvdxl3cyfe8x06eg6htj2gwgv02qjt") - .unwrap(); + let account_address = Address::from_bech32( + "addr_test1vz3ppzmmzuz0nlsjeyrqjm4pvdxl3cyfe8x06eg6htj2gwgv02qjt", + ) + .unwrap(); let puller_address = Address::from_bech32("addr_test1qrksjmprvgcedgdt6rhg40590vr6exdzdc2hm5wc6pyl9ymkyskmqs55usm57gflrumk9kd63f3ty6r0l2tdfwfm28qs0rurdr").unwrap(); let owner = pub_key_hash_from_address_if_available(&account_address).unwrap(); let puller = pub_key_hash_from_address_if_available(&puller_address).unwrap(); diff --git a/sample-dApps/checking_account/src/scripts/spend_token_policy.rs b/sample-dApps/checking_account/src/scripts/spend_token_policy.rs index aeb7d6a..63dace8 100644 --- a/sample-dApps/checking_account/src/scripts/spend_token_policy.rs +++ b/sample-dApps/checking_account/src/scripts/spend_token_policy.rs @@ -1,8 +1,11 @@ -use naumachia::scripts::context::PubKeyHash; -use naumachia::scripts::plutus_minting_policy::TwoParamMintingPolicy; -use naumachia::scripts::plutus_validator::plutus_data::PlutusData; -use naumachia::scripts::raw_script::BlueprintFile; -use naumachia::scripts::{ScriptError, ScriptResult}; +use naumachia::scripts::{ + context::PubKeyHash, + plutus_minting_policy::TwoParamMintingPolicy, + plutus_validator::plutus_data::PlutusData, + raw_script::BlueprintFile, + ScriptError, + ScriptResult, +}; const BLUEPRINT: &str = include_str!("../../checking/plutus.json"); const VALIDATOR_NAME: &str = "spend_token_policy.mint"; @@ -40,16 +43,16 @@ impl From for PlutusData { } } -pub fn spend_token_policy() -> ScriptResult> { +pub fn spend_token_policy( +) -> ScriptResult> { let script_file: BlueprintFile = serde_json::from_str(BLUEPRINT) .map_err(|e| ScriptError::FailedToConstruct(e.to_string()))?; - let validator_blueprint = - script_file - .get_validator(VALIDATOR_NAME) - .ok_or(ScriptError::FailedToConstruct(format!( - "Validator not listed in Blueprint: {:?}", - VALIDATOR_NAME - )))?; + let validator_blueprint = script_file.get_validator(VALIDATOR_NAME).ok_or( + ScriptError::FailedToConstruct(format!( + "Validator not listed in Blueprint: {:?}", + VALIDATOR_NAME + )), + )?; let raw_script_validator = TwoParamMintingPolicy::from_blueprint(validator_blueprint) .map_err(|e| ScriptError::FailedToConstruct(e.to_string()))?; Ok(raw_script_validator) @@ -59,9 +62,16 @@ pub fn spend_token_policy() -> ScriptResult>( diff --git a/sample-dApps/free-minting-contract/src/logic.rs b/sample-dApps/free-minting-contract/src/logic.rs index f8bfdb9..2fcc0f3 100644 --- a/sample-dApps/free-minting-contract/src/logic.rs +++ b/sample-dApps/free-minting-contract/src/logic.rs @@ -1,7 +1,16 @@ use crate::logic::script::get_policy; use async_trait::async_trait; -use naumachia::logic::error::{SCLogicError, SCLogicResult}; -use naumachia::{ledger_client::LedgerClient, logic::SCLogic, transaction::TxActions}; +use naumachia::{ + ledger_client::LedgerClient, + logic::{ + error::{ + SCLogicError, + SCLogicResult, + }, + SCLogic, + }, + transaction::TxActions, +}; pub mod script; @@ -29,8 +38,12 @@ impl SCLogic for FreeMintingLogic { FreeMintingEndpoints::Mint { amount } => { let inner_policy = get_policy().map_err(SCLogicError::PolicyScript)?; let policy = Box::new(inner_policy); - let actions = - TxActions::v1().with_mint(amount, Some("FREEEEEE".to_string()), (), policy); + let actions = TxActions::v1().with_mint( + amount, + Some("FREEEEEE".to_string()), + (), + policy, + ); Ok(actions) } } diff --git a/sample-dApps/free-minting-contract/src/logic/script.rs b/sample-dApps/free-minting-contract/src/logic/script.rs index 33f999f..abd1cbb 100644 --- a/sample-dApps/free-minting-contract/src/logic/script.rs +++ b/sample-dApps/free-minting-contract/src/logic/script.rs @@ -1,6 +1,9 @@ -use naumachia::scripts::plutus_minting_policy::PlutusMintingPolicy; -use naumachia::scripts::raw_script::PlutusScriptFile; -use naumachia::scripts::{ScriptError, ScriptResult}; +use naumachia::scripts::{ + plutus_minting_policy::PlutusMintingPolicy, + raw_script::PlutusScriptFile, + ScriptError, + ScriptResult, +}; // const SCRIPT_RAW: &str = include_str!("../../plutus/anyone-can-mint.plutus"); // const SCRIPT_RAW: &str = include_str!("../../plutus/free-minting.plutus"); @@ -17,9 +20,16 @@ pub fn get_policy() -> ScriptResult> { #[cfg(test)] mod tests { use super::*; - use naumachia::scripts::context::{pub_key_hash_from_address_if_available, ContextBuilder}; - use naumachia::scripts::MintingPolicy; - use naumachia::Address; + use naumachia::{ + scripts::{ + context::{ + pub_key_hash_from_address_if_available, + ContextBuilder, + }, + MintingPolicy, + }, + Address, + }; #[test] fn can_execute_policy() { diff --git a/sample-dApps/free-minting-contract/src/main.rs b/sample-dApps/free-minting-contract/src/main.rs index 608ebd3..15feda7 100644 --- a/sample-dApps/free-minting-contract/src/main.rs +++ b/sample-dApps/free-minting-contract/src/main.rs @@ -1,9 +1,14 @@ use clap::Parser; -use free_minting_contract::logic::FreeMintingEndpoints; -use free_minting_contract::logic::FreeMintingLogic; -use naumachia::smart_contract::SmartContractTrait; +use free_minting_contract::logic::{ + FreeMintingEndpoints, + FreeMintingLogic, +}; use naumachia::{ - smart_contract::SmartContract, trireme_ledger_client::get_trireme_ledger_client_from_file, + smart_contract::{ + SmartContract, + SmartContractTrait, + }, + trireme_ledger_client::get_trireme_ledger_client_from_file, }; #[derive(Parser, Debug)] diff --git a/sample-dApps/game-contract/src/logic.rs b/sample-dApps/game-contract/src/logic.rs index cc59e59..b9bc4cb 100644 --- a/sample-dApps/game-contract/src/logic.rs +++ b/sample-dApps/game-contract/src/logic.rs @@ -1,10 +1,22 @@ -use crate::logic::script::{get_script, ClearString, HashedString}; +use crate::logic::script::{ + get_script, + ClearString, + HashedString, +}; use async_trait::async_trait; -use naumachia::logic::error::{SCLogicError, SCLogicResult}; use naumachia::{ ledger_client::LedgerClient, - logic::SCLogic, - output::{Output, OutputId}, + logic::{ + error::{ + SCLogicError, + SCLogicResult, + }, + SCLogic, + }, + output::{ + Output, + OutputId, + }, policy_id::PolicyId, scripts::Validator, transaction::TxActions, diff --git a/sample-dApps/game-contract/src/logic/script.rs b/sample-dApps/game-contract/src/logic/script.rs index 44d34c9..6064c1e 100644 --- a/sample-dApps/game-contract/src/logic/script.rs +++ b/sample-dApps/game-contract/src/logic/script.rs @@ -1,10 +1,20 @@ -use naumachia::scripts::plutus_validator::plutus_data::PlutusData; -use naumachia::scripts::plutus_validator::PlutusValidator; -use naumachia::scripts::raw_script::PlutusScriptFile; -use naumachia::scripts::{ScriptError, ScriptResult}; -use serde::{Deserialize, Serialize}; -use sha2::Digest; -use sha2::Sha256; +use naumachia::scripts::{ + plutus_validator::{ + plutus_data::PlutusData, + PlutusValidator, + }, + raw_script::PlutusScriptFile, + ScriptError, + ScriptResult, +}; +use serde::{ + Deserialize, + Serialize, +}; +use sha2::{ + Digest, + Sha256, +}; // const SCRIPT_RAW: &str = include_str!("../../plutus/game_v1.plutus"); const SCRIPT_RAW: &str = include_str!("../../plutus/game_v2.plutus"); @@ -67,8 +77,9 @@ impl TryFrom for ClearString { fn try_from(value: PlutusData) -> Result { match value { PlutusData::BoundedBytes(ref bytes) => { - let inner = String::from_utf8(bytes.clone()) - .map_err(|_| ScriptError::RedeemerDeserialization(format!("{:?}", value)))?; + let inner = String::from_utf8(bytes.clone()).map_err(|_| { + ScriptError::RedeemerDeserialization(format!("{:?}", value)) + })?; Ok(ClearString { inner }) } _ => Err(ScriptError::RedeemerDeserialization(format!("{:?}", value))), @@ -87,9 +98,16 @@ pub fn get_script() -> ScriptResult> #[cfg(test)] mod tests { use super::*; - use naumachia::scripts::context::{pub_key_hash_from_address_if_available, ContextBuilder}; - use naumachia::scripts::Validator; - use naumachia::Address; + use naumachia::{ + scripts::{ + context::{ + pub_key_hash_from_address_if_available, + ContextBuilder, + }, + Validator, + }, + Address, + }; // This is broken. I think it might have to do with the script itself. #[ignore] diff --git a/sample-dApps/game-contract/src/logic/tests.rs b/sample-dApps/game-contract/src/logic/tests.rs index 04f48b2..d23c972 100644 --- a/sample-dApps/game-contract/src/logic/tests.rs +++ b/sample-dApps/game-contract/src/logic/tests.rs @@ -1,8 +1,12 @@ use super::*; use naumachia::{ ledger_client::test_ledger_client::TestLedgerClientBuilder, - smart_contract::{SmartContract, SmartContractTrait}, - Address, Network, + smart_contract::{ + SmartContract, + SmartContractTrait, + }, + Address, + Network, }; // Ignore because the game script is funky with Aiken diff --git a/sample-dApps/game-contract/src/main.rs b/sample-dApps/game-contract/src/main.rs index 6e23ac9..c57daa3 100644 --- a/sample-dApps/game-contract/src/main.rs +++ b/sample-dApps/game-contract/src/main.rs @@ -1,8 +1,16 @@ use clap::Parser; -use game_contract::logic::{GameEndpoints, GameLogic, GameLookupResponses, GameLookups}; +use game_contract::logic::{ + GameEndpoints, + GameLogic, + GameLookupResponses, + GameLookups, +}; use naumachia::{ output::OutputId, - smart_contract::{SmartContract, SmartContractTrait}, + smart_contract::{ + SmartContract, + SmartContractTrait, + }, trireme_ledger_client::get_trireme_ledger_client_from_file, }; diff --git a/sample-dApps/mint_nft/src/logic.rs b/sample-dApps/mint_nft/src/logic.rs index 93a73c4..1cdcd79 100644 --- a/sample-dApps/mint_nft/src/logic.rs +++ b/sample-dApps/mint_nft/src/logic.rs @@ -1,13 +1,23 @@ // use crate::logic::script::{get_parameterized_script, OutputReference}; use async_trait::async_trait; -use naumachia::output::Output; -use naumachia::policy_id::PolicyId; -use naumachia::scripts::ScriptError; -use naumachia::{ledger_client::LedgerClient, logic::SCLogic, transaction::TxActions}; +use naumachia::{ + ledger_client::LedgerClient, + logic::SCLogic, + output::Output, + policy_id::PolicyId, + scripts::ScriptError, + transaction::TxActions, +}; use thiserror::Error; -use nau_scripts::one_shot::{get_parameterized_script, OutputReference}; -use naumachia::logic::error::{SCLogicError, SCLogicResult}; +use nau_scripts::one_shot::{ + get_parameterized_script, + OutputReference, +}; +use naumachia::logic::error::{ + SCLogicError, + SCLogicResult, +}; #[derive(Debug, Clone, Eq, PartialEq)] pub struct MintNFTLogic; diff --git a/sample-dApps/mint_nft/src/main.rs b/sample-dApps/mint_nft/src/main.rs index 3589d80..6a1f583 100644 --- a/sample-dApps/mint_nft/src/main.rs +++ b/sample-dApps/mint_nft/src/main.rs @@ -1,7 +1,13 @@ use clap::Parser; -use mint_nft::logic::{MintNFTEndpoints, MintNFTLogic}; +use mint_nft::logic::{ + MintNFTEndpoints, + MintNFTLogic, +}; use naumachia::{ - smart_contract::{SmartContract, SmartContractTrait}, + smart_contract::{ + SmartContract, + SmartContractTrait, + }, trireme_ledger_client::get_trireme_ledger_client_from_file, }; @@ -27,7 +33,9 @@ async fn main() { let contract = SmartContract::new(logic, ledger_client); let tx_id = match args.action { - ActionParams::Mint => contract.hit_endpoint(MintNFTEndpoints::Mint).await.unwrap(), + ActionParams::Mint => { + contract.hit_endpoint(MintNFTEndpoints::Mint).await.unwrap() + } }; println!("TxId: {:?}", tx_id); } diff --git a/sample-dApps/time-locked-contract/build.rs b/sample-dApps/time-locked-contract/build.rs index f1c05f5..c12113a 100644 --- a/sample-dApps/time-locked-contract/build.rs +++ b/sample-dApps/time-locked-contract/build.rs @@ -1,6 +1,8 @@ use aiken_lang::ast::Tracing; -use aiken_project::telemetry::Terminal; -use aiken_project::Project; +use aiken_project::{ + telemetry::Terminal, + Project, +}; const PROJECT: &str = "./time_locked"; diff --git a/sample-dApps/time-locked-contract/src/logic.rs b/sample-dApps/time-locked-contract/src/logic.rs index d7d81f5..ceecb79 100644 --- a/sample-dApps/time-locked-contract/src/logic.rs +++ b/sample-dApps/time-locked-contract/src/logic.rs @@ -1,11 +1,19 @@ use crate::logic::script::get_script; use async_trait::async_trait; -use naumachia::logic::error::{SCLogicError, SCLogicResult}; -use naumachia::output::DatumKind; use naumachia::{ ledger_client::LedgerClient, - logic::SCLogic, - output::{Output, OutputId}, + logic::{ + error::{ + SCLogicError, + SCLogicResult, + }, + SCLogic, + }, + output::{ + DatumKind, + Output, + OutputId, + }, policy_id::PolicyId, scripts::Validator, transaction::TxActions, @@ -59,7 +67,9 @@ impl SCLogic for TimeLockedLogic { amount, after_secs: timestamp, } => impl_lock(ledger_client, amount, timestamp).await, - TimeLockedEndpoints::Claim { output_id } => impl_claim(ledger_client, output_id).await, + TimeLockedEndpoints::Claim { output_id } => { + impl_claim(ledger_client, output_id).await + } } } @@ -140,10 +150,16 @@ mod tests { use super::*; use naumachia::{ error::Error, - ledger_client::test_ledger_client::TestLedgerClientBuilder, - ledger_client::LedgerClientError, - smart_contract::{SmartContract, SmartContractTrait}, - Address, Network, + ledger_client::{ + test_ledger_client::TestLedgerClientBuilder, + LedgerClientError, + }, + smart_contract::{ + SmartContract, + SmartContractTrait, + }, + Address, + Network, }; #[tokio::test] diff --git a/sample-dApps/time-locked-contract/src/logic/script.rs b/sample-dApps/time-locked-contract/src/logic/script.rs index 479204b..136fef1 100644 --- a/sample-dApps/time-locked-contract/src/logic/script.rs +++ b/sample-dApps/time-locked-contract/src/logic/script.rs @@ -1,7 +1,16 @@ -use naumachia::scripts::plutus_validator::plutus_data::{BigInt, Constr, PlutusData}; -use naumachia::scripts::plutus_validator::PlutusValidator; -use naumachia::scripts::raw_script::BlueprintFile; -use naumachia::scripts::{ScriptError, ScriptResult}; +use naumachia::scripts::{ + plutus_validator::{ + plutus_data::{ + BigInt, + Constr, + PlutusData, + }, + PlutusValidator, + }, + raw_script::BlueprintFile, + ScriptError, + ScriptResult, +}; const BLUEPRINT: &str = include_str!("../../time_locked/plutus.json"); const VALIDATOR_NAME: &str = "time_lock.spend"; @@ -61,13 +70,12 @@ impl TryFrom for Timestamp { pub fn get_script() -> ScriptResult> { let script_file: BlueprintFile = serde_json::from_str(BLUEPRINT) .map_err(|e| ScriptError::FailedToConstruct(e.to_string()))?; - let validator_blueprint = - script_file - .get_validator(VALIDATOR_NAME) - .ok_or(ScriptError::FailedToConstruct(format!( - "Validator not listed in Blueprint: {:?}", - VALIDATOR_NAME - )))?; + let validator_blueprint = script_file.get_validator(VALIDATOR_NAME).ok_or( + ScriptError::FailedToConstruct(format!( + "Validator not listed in Blueprint: {:?}", + VALIDATOR_NAME + )), + )?; let raw_script_validator = PlutusValidator::from_blueprint(validator_blueprint) .map_err(|e| ScriptError::FailedToConstruct(e.to_string()))?; Ok(raw_script_validator) @@ -76,9 +84,16 @@ pub fn get_script() -> ScriptResult> { #[cfg(test)] mod tests { use super::*; - use naumachia::scripts::context::{pub_key_hash_from_address_if_available, ContextBuilder}; - use naumachia::scripts::Validator; - use naumachia::Address; + use naumachia::{ + scripts::{ + context::{ + pub_key_hash_from_address_if_available, + ContextBuilder, + }, + Validator, + }, + Address, + }; #[test] fn test_in_range_succeeds() { diff --git a/sample-dApps/time-locked-contract/src/main.rs b/sample-dApps/time-locked-contract/src/main.rs index 04e06bf..45b5e26 100644 --- a/sample-dApps/time-locked-contract/src/main.rs +++ b/sample-dApps/time-locked-contract/src/main.rs @@ -1,11 +1,17 @@ use clap::Parser; use naumachia::{ output::OutputId, - smart_contract::{SmartContract, SmartContractTrait}, + smart_contract::{ + SmartContract, + SmartContractTrait, + }, trireme_ledger_client::get_trireme_ledger_client_from_file, }; use time_locked_contract::logic::{ - TimeLockedEndpoints, TimeLockedLogic, TimeLockedLookupResponses, TimeLockedLookups, + TimeLockedEndpoints, + TimeLockedLogic, + TimeLockedLookupResponses, + TimeLockedLookups, }; #[derive(Parser, Debug)] diff --git a/src/error.rs b/src/error.rs index 3bee348..799cdd1 100644 --- a/src/error.rs +++ b/src/error.rs @@ -2,9 +2,12 @@ use pallas_addresses::Address; use thiserror::Error; -use crate::logic::error::SCLogicError; -use crate::scripts::ScriptError; -use crate::{ledger_client::LedgerClientError, policy_id::PolicyId}; +use crate::{ + ledger_client::LedgerClientError, + logic::error::SCLogicError, + policy_id::PolicyId, + scripts::ScriptError, +}; pub type Result = std::result::Result; diff --git a/src/ledger_client.rs b/src/ledger_client.rs index e6f31a4..d351b20 100644 --- a/src/ledger_client.rs +++ b/src/ledger_client.rs @@ -6,12 +6,20 @@ pub mod test_ledger_client; use async_trait::async_trait; use crate::{ - output::{Output, OutputId}, - transaction::TxId, - transaction::UnbuiltTransaction, + output::{ + Output, + OutputId, + }, + transaction::{ + TxId, + UnbuiltTransaction, + }, PolicyId, }; -use pallas_addresses::{Address, Network}; +use pallas_addresses::{ + Address, + Network, +}; use std::error; /// Interface defining interactions with your specific ledger--AKA the Cardano blockchain. The @@ -60,7 +68,10 @@ pub trait LedgerClient: Send + Sync { } /// Issue a transaction to the ledger signed by the signer key owned by the instance of `LedgerClient` - async fn issue(&self, tx: UnbuiltTransaction) -> LedgerClientResult; + async fn issue( + &self, + tx: UnbuiltTransaction, + ) -> LedgerClientResult; /// Get the network identifier for the ledger async fn network(&self) -> LedgerClientResult; diff --git a/src/ledger_client/test_ledger_client.rs b/src/ledger_client/test_ledger_client.rs index fec1d7f..065f27f 100644 --- a/src/ledger_client/test_ledger_client.rs +++ b/src/ledger_client/test_ledger_client.rs @@ -3,29 +3,49 @@ use std::{ hash::Hash, marker::PhantomData, path::Path, - sync::{Arc, Mutex}, + sync::{ + Arc, + Mutex, + }, }; use crate::{ ledger_client::{ - test_ledger_client::in_memory_storage::InMemoryStorage, LedgerClient, LedgerClientError, + test_ledger_client::in_memory_storage::InMemoryStorage, + LedgerClient, + LedgerClientError, LedgerClientResult, }, - output::{DatumKind, Output, UnbuiltOutput}, - scripts::context::{ - pub_key_hash_from_address_if_available, CtxDatum, CtxOutput, CtxOutputReference, + output::{ + DatumKind, + Output, + UnbuiltOutput, }, scripts::{ - context::{CtxScriptPurpose, CtxValue, Input, TxContext, ValidRange}, + context::{ + pub_key_hash_from_address_if_available, + CtxDatum, + CtxOutput, + CtxOutputReference, + CtxScriptPurpose, + CtxValue, + Input, + TxContext, + ValidRange, + }, plutus_validator::plutus_data::PlutusData, }, transaction::TxId, values::Values, - PolicyId, UnbuiltTransaction, + PolicyId, + UnbuiltTransaction, }; use async_trait::async_trait; use local_persisted_storage::LocalPersistedStorage; -use pallas_addresses::{Address, Network}; +use pallas_addresses::{ + Address, + Network, +}; use rand::Rng; use thiserror::Error; @@ -107,7 +127,9 @@ where } /// Build the [`TestLedgerClient`] with an _ephemeral_ [`InMemoryStorage`] for [`TestLedgerStorage`] - pub fn build_in_memory(&self) -> TestLedgerClient> { + pub fn build_in_memory( + &self, + ) -> TestLedgerClient> { TestLedgerClient::new_in_memory( self.signer.clone(), self.outputs.clone(), @@ -119,8 +141,10 @@ where /// Sub-builder type of [`TestLedgerClientBuilder`] for building outputs that will be added to the /// parent [`TestLedgerClient`] -pub struct OutputBuilder -{ +pub struct OutputBuilder< + Datum: PartialEq + Debug, + Redeemer: Clone + Eq + PartialEq + Debug + Hash, +> { inner: TestLedgerClientBuilder, owner: Address, values: Values, @@ -133,7 +157,11 @@ where Redeemer: Clone + Eq + PartialEq + Debug + Hash + Send + Sync, { /// Add another value to current output - pub fn with_value(mut self, policy: PolicyId, amount: u64) -> OutputBuilder { + pub fn with_value( + mut self, + policy: PolicyId, + amount: u64, + ) -> OutputBuilder { let mut new_total = amount; if let Some(total) = self.values.get(&policy) { new_total += total; @@ -200,7 +228,10 @@ pub trait TestLedgerStorage { count: usize, ) -> LedgerClientResult>>; /// Get all UTxOs at the given address - async fn all_outputs(&self, address: &Address) -> LedgerClientResult>>; + async fn all_outputs( + &self, + address: &Address, + ) -> LedgerClientResult>>; /// Remove the given output from the storage async fn remove_output(&self, output: &Output) -> LedgerClientResult<()>; /// Add the given output to the storage @@ -248,7 +279,8 @@ where } } } -impl TestLedgerClient> +impl + TestLedgerClient> where Datum: Clone + Send + Sync + PartialEq + Into + TryFrom, T: AsRef + Send + Sync, @@ -343,7 +375,10 @@ where self.storage.all_outputs(address).await } - async fn issue(&self, tx: UnbuiltTransaction) -> LedgerClientResult { + async fn issue( + &self, + tx: UnbuiltTransaction, + ) -> LedgerClientResult { // Setup let valid_range = tx.valid_range; let current_time = self.current_time_secs().await?; @@ -558,7 +593,8 @@ fn mint_tx_context + Clone, Redeemer>( signer_address: &Address, policy_id: &str, ) -> LedgerClientResult { - let id = hex::decode(policy_id).map_err(|e| LedgerClientError::FailedToIssueTx(Box::new(e)))?; + let id = hex::decode(policy_id) + .map_err(|e| LedgerClientError::FailedToIssueTx(Box::new(e)))?; let purpose = CtxScriptPurpose::Mint(id); tx_context(tx, signer_address, purpose) } diff --git a/src/ledger_client/test_ledger_client/in_memory_storage.rs b/src/ledger_client/test_ledger_client/in_memory_storage.rs index 8acd6cc..f86bbcd 100644 --- a/src/ledger_client/test_ledger_client/in_memory_storage.rs +++ b/src/ledger_client/test_ledger_client/in_memory_storage.rs @@ -1,9 +1,23 @@ -use crate::ledger_client::test_ledger_client::{TestLCError, TestLedgerStorage}; -use crate::ledger_client::LedgerClientError::FailedToIssueTx; -use crate::ledger_client::{LedgerClientError, LedgerClientResult}; -use crate::output::Output; -use pallas_addresses::{Address, Network}; -use std::sync::{Arc, Mutex}; +use crate::{ + ledger_client::{ + test_ledger_client::{ + TestLCError, + TestLedgerStorage, + }, + LedgerClientError, + LedgerClientError::FailedToIssueTx, + LedgerClientResult, + }, + output::Output, +}; +use pallas_addresses::{ + Address, + Network, +}; +use std::sync::{ + Arc, + Mutex, +}; /// A mutable, shared reference to a vector of `Output`s. type MutableData = Arc)>>>; @@ -24,7 +38,9 @@ pub struct InMemoryStorage { } #[async_trait::async_trait] -impl TestLedgerStorage for InMemoryStorage { +impl TestLedgerStorage + for InMemoryStorage +{ async fn signer(&self) -> LedgerClientResult
{ Ok(self.signer.clone()) } @@ -49,7 +65,10 @@ impl TestLedgerStorage for InMemo Ok(outputs) } - async fn all_outputs(&self, address: &Address) -> LedgerClientResult>> { + async fn all_outputs( + &self, + address: &Address, + ) -> LedgerClientResult>> { let outputs = self .outputs .lock() diff --git a/src/ledger_client/test_ledger_client/local_persisted_storage.rs b/src/ledger_client/test_ledger_client/local_persisted_storage.rs index 651f797..0e09558 100644 --- a/src/ledger_client/test_ledger_client/local_persisted_storage.rs +++ b/src/ledger_client/test_ledger_client/local_persisted_storage.rs @@ -1,21 +1,38 @@ -use pallas_addresses::{Address, Network}; -use serde::{Deserialize, Serialize}; -use std::collections::HashMap; -use std::path::Path; +use pallas_addresses::{ + Address, + Network, +}; +use serde::{ + Deserialize, + Serialize, +}; use std::{ + collections::HashMap, fmt::Debug, fs::File, - io::{Read, Write}, + io::{ + Read, + Write, + }, marker::PhantomData, + path::Path, }; use thiserror::Error; -use crate::ledger_client::test_ledger_client::arbitrary_tx_id; -use crate::output::OutputId; -use crate::scripts::plutus_validator::plutus_data::PlutusData; use crate::{ - ledger_client::{test_ledger_client::TestLedgerStorage, LedgerClientError, LedgerClientResult}, - output::Output, + ledger_client::{ + test_ledger_client::{ + arbitrary_tx_id, + TestLedgerStorage, + }, + LedgerClientError, + LedgerClientResult, + }, + output::{ + Output, + OutputId, + }, + scripts::plutus_validator::plutus_data::PlutusData, values::Values, PolicyId, }; @@ -251,7 +268,8 @@ where { async fn signer(&self) -> LedgerClientResult
{ let signer = self.get_data().active_signer; - Address::from_bech32(&signer).map_err(|e| LedgerClientError::BadAddress(Box::new(e))) + Address::from_bech32(&signer) + .map_err(|e| LedgerClientError::BadAddress(Box::new(e))) } async fn outputs_by_count( @@ -271,7 +289,10 @@ where Ok(outputs) } - async fn all_outputs(&self, address: &Address) -> LedgerClientResult>> { + async fn all_outputs( + &self, + address: &Address, + ) -> LedgerClientResult>> { let data = self.get_data(); let outputs = data .outputs diff --git a/src/ledger_client/test_ledger_client/tests.rs b/src/ledger_client/test_ledger_client/tests.rs index f400dce..3a50519 100644 --- a/src/ledger_client/test_ledger_client/tests.rs +++ b/src/ledger_client/test_ledger_client/tests.rs @@ -1,15 +1,25 @@ #![allow(non_snake_case)] use super::*; -use crate::scripts::{ExecutionCost, MintingPolicy, ScriptError, ScriptResult, Validator}; -use crate::transaction::TransactionVersion; use crate::{ ledger_client::{ - test_ledger_client::{local_persisted_storage::starting_output, TestLedgerClient}, + test_ledger_client::{ + local_persisted_storage::starting_output, + TestLedgerClient, + }, LedgerClient, }, output::UnbuiltOutput, - PolicyId, UnbuiltTransaction, + scripts::{ + ExecutionCost, + MintingPolicy, + ScriptError, + ScriptResult, + Validator, + }, + transaction::TransactionVersion, + PolicyId, + UnbuiltTransaction, }; const ALICE: &str = "addr_test1qrmezjhpelwzvz83wjl0e6mx766de7j3nksu2338s00yzx870xyxfa97xyz2zn5rknyntu5g0c66s7ktjnx0p6f0an6s3dyxwr"; @@ -210,15 +220,20 @@ async fn cannot_transfer_after_valid_range() { struct AlwaysTrueFakeValidator; impl Validator<(), ()> for AlwaysTrueFakeValidator { - fn execute(&self, _datum: (), _redeemer: (), _ctx: TxContext) -> ScriptResult { + fn execute( + &self, + _datum: (), + _redeemer: (), + _ctx: TxContext, + ) -> ScriptResult { Ok(ExecutionCost::default()) } fn address(&self, _network: Network) -> ScriptResult
{ - Ok( - Address::from_bech32("addr_test1wrme5jjggy97th309h2dwpv57wsphxskuc8jkw00c2kn47gu8mkzu") - .unwrap(), + Ok(Address::from_bech32( + "addr_test1wrme5jjggy97th309h2dwpv57wsphxskuc8jkw00c2kn47gu8mkzu", ) + .unwrap()) } fn script_hex(&self) -> ScriptResult { @@ -302,17 +317,22 @@ async fn redeeming_datum() { struct AlwaysFailsFakeValidator; impl Validator<(), ()> for AlwaysFailsFakeValidator { - fn execute(&self, _datum: (), _redeemer: (), _ctx: TxContext) -> ScriptResult { + fn execute( + &self, + _datum: (), + _redeemer: (), + _ctx: TxContext, + ) -> ScriptResult { Err(ScriptError::FailedToExecute( "Should always fail!".to_string(), )) } fn address(&self, _network: Network) -> ScriptResult
{ - Ok( - Address::from_bech32("addr_test1wrme5jjggy97th309h2dwpv57wsphxskuc8jkw00c2kn47gu8mkzu") - .unwrap(), + Ok(Address::from_bech32( + "addr_test1wrme5jjggy97th309h2dwpv57wsphxskuc8jkw00c2kn47gu8mkzu", ) + .unwrap()) } fn script_hex(&self) -> ScriptResult { @@ -583,7 +603,8 @@ async fn spends_specific_script_value() { let mut values = Values::default(); let policy = PolicyId::NativeToken(nft_policy_id.clone(), None); values.add_one_value(&policy, 1); - let input = Output::new_validator(vec![1, 2, 3, 4], 0, val_address.clone(), values, ()); + let input = + Output::new_validator(vec![1, 2, 3, 4], 0, val_address.clone(), values, ()); let output = starting_output::<()>(&minter, starting_amount); let outputs = vec![(minter.clone(), output), (val_address, input.clone())]; diff --git a/src/lib.rs b/src/lib.rs index 5d247eb..6afc354 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,10 +4,16 @@ use crate::{ policy_id::PolicyId, - transaction::{TxActions, UnbuiltTransaction}, + transaction::{ + TxActions, + UnbuiltTransaction, + }, }; -pub use pallas_addresses::{Address, Network}; +pub use pallas_addresses::{ + Address, + Network, +}; pub mod error; diff --git a/src/logic.rs b/src/logic.rs index c9a9d79..e5fc4ce 100644 --- a/src/logic.rs +++ b/src/logic.rs @@ -1,10 +1,14 @@ -use crate::ledger_client::LedgerClient; -use crate::TxActions; +use crate::{ + ledger_client::LedgerClient, + TxActions, +}; use async_trait::async_trait; use error::SCLogicResult; -use std::fmt::Debug; -use std::hash::Hash; +use std::{ + fmt::Debug, + hash::Hash, +}; #[allow(missing_docs)] pub mod error; @@ -35,7 +39,6 @@ pub trait SCLogic: Send + Sync { /// auction_id: String /// } /// } - /// type Endpoints: Send + Sync; /// Represents the domain-specific data the consumer of a Smart Contract can query. diff --git a/src/logic/error.rs b/src/logic/error.rs index b67184b..bd7a8ef 100644 --- a/src/logic/error.rs +++ b/src/logic/error.rs @@ -1,5 +1,7 @@ -use crate::ledger_client::LedgerClientError; -use crate::scripts::ScriptError; +use crate::{ + ledger_client::LedgerClientError, + scripts::ScriptError, +}; use std::error; use thiserror::Error; @@ -21,7 +23,9 @@ pub enum SCLogicError { pub type SCLogicResult = crate::error::Result; -pub fn as_endpoint_err(error: E) -> SCLogicError { +pub fn as_endpoint_err( + error: E, +) -> SCLogicError { SCLogicError::Endpoint(Box::new(error)) } diff --git a/src/output.rs b/src/output.rs index 603c441..2c3da73 100644 --- a/src/output.rs +++ b/src/output.rs @@ -1,6 +1,9 @@ use crate::scripts::plutus_validator::plutus_data::PlutusData; use pallas_addresses::Address; -use serde::{Deserialize, Serialize}; +use serde::{ + Deserialize, + Serialize, +}; use crate::values::Values; @@ -147,7 +150,12 @@ impl OutputId { impl Output { /// Constructor for wallet output - pub fn new_wallet(tx_hash: Vec, index: u64, owner: Address, values: Values) -> Self { + pub fn new_wallet( + tx_hash: Vec, + index: u64, + owner: Address, + values: Values, + ) -> Self { let id = OutputId::new(tx_hash, index); let addr = owner.to_bech32().expect("Already Validated"); Output { diff --git a/src/policy_id.rs b/src/policy_id.rs index 2212906..b92c72f 100644 --- a/src/policy_id.rs +++ b/src/policy_id.rs @@ -1,4 +1,7 @@ -use serde::{Deserialize, Serialize}; +use serde::{ + Deserialize, + Serialize, +}; /// Token identity. #[derive(PartialEq, Eq, Hash, Clone, Debug, Serialize, Deserialize)] diff --git a/src/scripts.rs b/src/scripts.rs index cebd916..88425be 100644 --- a/src/scripts.rs +++ b/src/scripts.rs @@ -1,5 +1,8 @@ use context::TxContext; -use pallas_addresses::{Address, Network}; +use pallas_addresses::{ + Address, + Network, +}; use std::fmt::Debug; use thiserror::Error; @@ -15,7 +18,12 @@ pub mod raw_script; /// Interface for a script locking UTxOs at a script address pub trait Validator: Send + Sync { /// Execute the script with specified datum, redeemer, and tx context - fn execute(&self, datum: D, redeemer: R, ctx: TxContext) -> ScriptResult; + fn execute( + &self, + datum: D, + redeemer: R, + ctx: TxContext, + ) -> ScriptResult; /// Address of Outputs locked by this script fn address(&self, network: Network) -> ScriptResult
; /// Hex bytes of the script diff --git a/src/scripts/context.rs b/src/scripts/context.rs index de9ef32..e155a0f 100644 --- a/src/scripts/context.rs +++ b/src/scripts/context.rs @@ -1,8 +1,14 @@ use crate::{ - output::Output, scripts::plutus_validator::plutus_data::PlutusData, values::Values, PolicyId, + output::Output, + scripts::plutus_validator::plutus_data::PlutusData, + values::Values, + PolicyId, }; use pallas_addresses::Address; -use serde::{Deserialize, Serialize}; +use serde::{ + Deserialize, + Serialize, +}; use std::collections::HashMap; // TODO: Flesh out and probably move https://github.com/MitchTurner/naumachia/issues/39 @@ -210,7 +216,11 @@ impl ContextBuilder { } /// Add specific valid range for the `TxContext` - pub fn with_range(mut self, lower: Option<(i64, bool)>, upper: Option<(i64, bool)>) -> Self { + pub fn with_range( + mut self, + lower: Option<(i64, bool)>, + upper: Option<(i64, bool)>, + ) -> Self { let valid_range = ValidRange { lower, upper }; self.range = Some(valid_range); self @@ -241,7 +251,10 @@ impl ContextBuilder { } /// Add specific [`Output`] as an input, rather than using `with_input` - pub fn add_specific_input>(mut self, input: &Output) -> Self { + pub fn add_specific_input>( + mut self, + input: &Output, + ) -> Self { let id = input.id(); let transaction_id = id.tx_hash().to_vec(); let output_index = id.index(); @@ -278,7 +291,10 @@ impl ContextBuilder { } /// Add specific [`Output`] as an output, rather than using `with_input` - pub fn add_specific_output>(mut self, input: &Output) -> Self { + pub fn add_specific_output>( + mut self, + input: &Output, + ) -> Self { let address = input.owner(); let value = CtxValue::from(input.values().to_owned()); let datum = input.typed_datum().into(); @@ -316,7 +332,10 @@ impl ContextBuilder { } }; TxContext { - purpose: CtxScriptPurpose::Spend(CtxOutputReference::new(tx_id.to_vec(), index)), + purpose: CtxScriptPurpose::Spend(CtxOutputReference::new( + tx_id.to_vec(), + index, + )), signer: self.signer.clone(), range, inputs: self.inputs.clone(), @@ -361,13 +380,21 @@ pub struct CtxInputBuilder { impl CtxInputBuilder { /// Add single value to the `CtxInput` - pub fn with_value(mut self, policy_id: &str, asset_name: &str, amt: u64) -> CtxInputBuilder { + pub fn with_value( + mut self, + policy_id: &str, + asset_name: &str, + amt: u64, + ) -> CtxInputBuilder { add_to_nested(&mut self.value, policy_id, asset_name, amt); self } /// Add an inline `Datum` to the `CtxInput`. Will override previous value - pub fn with_inline_datum>(mut self, datum: Datum) -> CtxInputBuilder { + pub fn with_inline_datum>( + mut self, + datum: Datum, + ) -> CtxInputBuilder { self.datum = CtxDatum::InlineDatum(datum.into()); self } @@ -431,7 +458,10 @@ impl CtxOutputBuilder { } /// Add a `Datum` that will be stored on the `CtxOutput` as a datum hash. - pub fn with_datum_hash_from_datum>(mut self, datum: Datum) -> Self { + pub fn with_datum_hash_from_datum>( + mut self, + datum: Datum, + ) -> Self { self.datum = CtxDatum::DatumHash(datum.into().hash()); self } diff --git a/src/scripts/plutus_minting_policy.rs b/src/scripts/plutus_minting_policy.rs index 649fef8..6d0a839 100644 --- a/src/scripts/plutus_minting_policy.rs +++ b/src/scripts/plutus_minting_policy.rs @@ -1,23 +1,43 @@ -use crate::scripts::ExecutionCost; use crate::{ - scripts::context::TxContext, - scripts::raw_script::ValidatorBlueprint, - scripts::ScriptError, scripts::{ as_failed_to_execute, + context::TxContext, plutus_validator::plutus_data::PlutusData, - raw_script::{PlutusScriptError, PlutusScriptFile, RawPlutusScriptResult}, - MintingPolicy, ScriptResult, + raw_script::{ + PlutusScriptError, + PlutusScriptFile, + RawPlutusScriptResult, + ValidatorBlueprint, + }, + ExecutionCost, + MintingPolicy, + ScriptError, + ScriptResult, }, transaction::TransactionVersion, }; -use cardano_multiplatform_lib::plutus::{PlutusScript, PlutusV1Script, PlutusV2Script}; -use minicbor::{Decoder, Encoder}; +use cardano_multiplatform_lib::plutus::{ + PlutusScript, + PlutusV1Script, + PlutusV2Script, +}; +use minicbor::{ + Decoder, + Encoder, +}; use pallas_primitives::babbage::Language; -use std::marker::PhantomData; -use std::rc::Rc; +use std::{ + marker::PhantomData, + rc::Rc, +}; use uplc::{ - ast::{Constant, FakeNamedDeBruijn, NamedDeBruijn, Program, Term}, + ast::{ + Constant, + FakeNamedDeBruijn, + NamedDeBruijn, + Program, + Term, + }, machine::cost_model::ExBudget, }; @@ -75,7 +95,8 @@ impl PlutusMintingPolicy { /// Constructor for new V2 [`PlutusMintingPolicy`] from a CBOR hex string pub fn v2_from_cbor(cbor: String) -> RawPlutusScriptResult { - let cbor = hex::decode(cbor).map_err(|e| PlutusScriptError::AikenApply(e.to_string()))?; + let cbor = hex::decode(cbor) + .map_err(|e| PlutusScriptError::AikenApply(e.to_string()))?; let v2_policy = PlutusMintingPolicy { version: TransactionVersion::V2, cbor, @@ -228,7 +249,7 @@ where let program = program.apply_term(&ctx_term); let mut eval_result = match self.version { TransactionVersion::V1 => program.eval_version(&Language::PlutusV1), - TransactionVersion::V2 => program.eval(ExBudget::default()), // TODO: parameterize + TransactionVersion::V2 => program.eval(ExBudget::default()), /* TODO: parameterize */ }; let logs = eval_result.logs(); let cost = eval_result.cost(); @@ -246,15 +267,15 @@ where let cbor = self.script_hex().unwrap(); let script = match self.version { TransactionVersion::V1 => { - let script_bytes = - hex::decode(&cbor).map_err(|e| ScriptError::IdRetrieval(e.to_string()))?; + let script_bytes = hex::decode(&cbor) + .map_err(|e| ScriptError::IdRetrieval(e.to_string()))?; let v1 = PlutusV1Script::from_bytes(script_bytes) .map_err(|e| ScriptError::IdRetrieval(e.to_string()))?; PlutusScript::from_v1(&v1) } TransactionVersion::V2 => { - let script_bytes = - hex::decode(&cbor).map_err(|e| ScriptError::IdRetrieval(e.to_string()))?; + let script_bytes = hex::decode(&cbor) + .map_err(|e| ScriptError::IdRetrieval(e.to_string()))?; let v2 = PlutusV2Script::from_bytes(script_bytes) .map_err(|e| ScriptError::IdRetrieval(e.to_string()))?; PlutusScript::from_v2(&v2) diff --git a/src/scripts/plutus_validator.rs b/src/scripts/plutus_validator.rs index 56de37c..a2c94da 100644 --- a/src/scripts/plutus_validator.rs +++ b/src/scripts/plutus_validator.rs @@ -2,30 +2,64 @@ use crate::{ scripts::{ as_failed_to_execute, context::TxContext, - plutus_validator::plutus_data::{BigInt, Constr, PlutusData}, + plutus_validator::plutus_data::{ + BigInt, + Constr, + PlutusData, + }, raw_script::{ - PlutusScriptError, PlutusScriptFile, RawPlutusScriptResult, ValidatorBlueprint, + PlutusScriptError, + PlutusScriptFile, + RawPlutusScriptResult, + ValidatorBlueprint, }, - ScriptError, ScriptResult, Validator, + ScriptError, + ScriptResult, + Validator, }, transaction::TransactionVersion, }; use cardano_multiplatform_lib::{ - address::{EnterpriseAddress, StakeCredential}, - plutus::{PlutusScript, PlutusV1Script}, + address::{ + EnterpriseAddress, + StakeCredential, + }, + plutus::{ + PlutusScript, + PlutusV1Script, + }, +}; +use minicbor::{ + Decoder, + Encoder, }; -use minicbor::{Decoder, Encoder}; use crate::scripts::ExecutionCost; use cardano_multiplatform_lib::plutus::PlutusV2Script; -use pallas_addresses::{Address, Network}; +use pallas_addresses::{ + Address, + Network, +}; use pallas_primitives::babbage::Language; -use std::marker::PhantomData; -use std::rc::Rc; +use std::{ + marker::PhantomData, + rc::Rc, +}; use uplc::{ - ast::{Constant, FakeNamedDeBruijn, NamedDeBruijn, Program, Term}, - machine::{cost_model::ExBudget, runtime::convert_constr_to_tag}, - BigInt as AikenBigInt, Constr as AikenConstr, PlutusData as AikenPlutusData, + ast::{ + Constant, + FakeNamedDeBruijn, + NamedDeBruijn, + Program, + Term, + }, + machine::{ + cost_model::ExBudget, + runtime::convert_constr_to_tag, + }, + BigInt as AikenBigInt, + Constr as AikenConstr, + PlutusData as AikenPlutusData, }; #[allow(missing_docs)] @@ -93,7 +127,8 @@ impl PlutusValidator { /// Create a new V2 `PlutusValidator` from a CBOR string pub fn v2_from_cbor(cbor: String) -> RawPlutusScriptResult { - let cbor = hex::decode(cbor).map_err(|e| PlutusScriptError::AikenApply(e.to_string()))?; + let cbor = hex::decode(cbor) + .map_err(|e| PlutusScriptError::AikenApply(e.to_string()))?; let v2_policy = PlutusValidator { version: TransactionVersion::V2, cbor, @@ -175,12 +210,16 @@ impl From for AikenPlutusData { PlutusData::Constr(constr) => AikenPlutusData::Constr(constr.into()), PlutusData::Map(map) => AikenPlutusData::Map( map.into_iter() - .map(|(key, value)| (AikenPlutusData::from(key), AikenPlutusData::from(value))) + .map(|(key, value)| { + (AikenPlutusData::from(key), AikenPlutusData::from(value)) + }) .collect::>() .into(), ), PlutusData::BigInt(big_int) => AikenPlutusData::BigInt(big_int.into()), - PlutusData::BoundedBytes(bytes) => AikenPlutusData::BoundedBytes(bytes.into()), + PlutusData::BoundedBytes(bytes) => { + AikenPlutusData::BoundedBytes(bytes.into()) + } PlutusData::Array(data) => { AikenPlutusData::Array(data.into_iter().map(Into::into).collect()) } @@ -208,9 +247,9 @@ impl From for AikenBigInt { BigInt::Int { neg, val } => { let new_val = val as i128; let final_val = if neg { -new_val } else { new_val }; - let inner = final_val - .try_into() - .expect("Since this was converted from a u64, it should always be valid 🤞"); + let inner = final_val.try_into().expect( + "Since this was converted from a u64, it should always be valid 🤞", + ); AikenBigInt::Int(inner) } BigInt::BigUInt(bytes) => AikenBigInt::BigUInt(bytes.into()), @@ -246,7 +285,7 @@ where let program = program.apply_term(&ctx_term); let mut eval_result = match self.version { TransactionVersion::V1 => program.eval_version(&Language::PlutusV1), - TransactionVersion::V2 => program.eval(ExBudget::default()), // TODO: parameterize + TransactionVersion::V2 => program.eval(ExBudget::default()), /* TODO: parameterize */ }; let logs = eval_result.logs(); let cost = eval_result.cost(); @@ -270,15 +309,15 @@ where let cbor = self.script_hex().unwrap(); // TODO let script = match self.version { TransactionVersion::V1 => { - let script_bytes = - hex::decode(&cbor).map_err(|e| ScriptError::IdRetrieval(e.to_string()))?; + let script_bytes = hex::decode(&cbor) + .map_err(|e| ScriptError::IdRetrieval(e.to_string()))?; let v1 = PlutusV1Script::from_bytes(script_bytes) .map_err(|e| ScriptError::IdRetrieval(e.to_string()))?; PlutusScript::from_v1(&v1) } TransactionVersion::V2 => { - let script_bytes = - hex::decode(&cbor).map_err(|e| ScriptError::IdRetrieval(e.to_string()))?; + let script_bytes = hex::decode(&cbor) + .map_err(|e| ScriptError::IdRetrieval(e.to_string()))?; let v2 = PlutusV2Script::from_bytes(script_bytes) .map_err(|e| ScriptError::IdRetrieval(e.to_string()))?; PlutusScript::from_v2(&v2) diff --git a/src/scripts/plutus_validator/plutus_data.rs b/src/scripts/plutus_validator/plutus_data.rs index 93453a2..bc4f87f 100644 --- a/src/scripts/plutus_validator/plutus_data.rs +++ b/src/scripts/plutus_validator/plutus_data.rs @@ -1,11 +1,27 @@ -use crate::scripts::context::{ - CtxDatum, CtxOutput, CtxOutputReference, CtxScriptPurpose, CtxValue, Input, PubKeyHash, - TxContext, ValidRange, +use crate::scripts::{ + context::{ + CtxDatum, + CtxOutput, + CtxOutputReference, + CtxScriptPurpose, + CtxValue, + Input, + PubKeyHash, + TxContext, + ValidRange, + }, + ScriptError, }; -use crate::scripts::ScriptError; use cardano_multiplatform_lib::ledger::common::hash::hash_plutus_data; -use pallas_addresses::{Address, ShelleyDelegationPart, ShelleyPaymentPart}; -use serde::{Deserialize, Serialize}; +use pallas_addresses::{ + Address, + ShelleyDelegationPart, + ShelleyPaymentPart, +}; +use serde::{ + Deserialize, + Serialize, +}; use std::collections::BTreeMap; #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Serialize, Deserialize)] @@ -117,7 +133,8 @@ impl From for PlutusData { fn from(ctx: TxContext) -> Self { let inputs = PlutusData::Array(ctx.inputs.into_iter().map(Into::into).collect()); let reference_inputs = PlutusData::Array(vec![]); - let outputs = PlutusData::Array(ctx.outputs.into_iter().map(Into::into).collect()); + let outputs = + PlutusData::Array(ctx.outputs.into_iter().map(Into::into).collect()); let fee = PlutusData::Map(BTreeMap::from([( PlutusData::BoundedBytes(Vec::new()), PlutusData::Map(BTreeMap::from([( @@ -135,7 +152,8 @@ impl From for PlutusData { let dcert = PlutusData::Array(vec![]); let wdrl = PlutusData::Map(BTreeMap::new()); let valid_range = ctx.range.into(); - let mut signers: Vec<_> = ctx.extra_signatories.into_iter().map(Into::into).collect(); + let mut signers: Vec<_> = + ctx.extra_signatories.into_iter().map(Into::into).collect(); signers.push(ctx.signer.into()); let signatories = PlutusData::Array(signers); let redeemers = PlutusData::Map(BTreeMap::new()); @@ -217,7 +235,8 @@ impl From
for PlutusData { wrap_with_constr(0, inner) } ShelleyDelegationPart::Script(script_keyhash) => { - let bytes_data = PlutusData::BoundedBytes(script_keyhash.to_vec()); + let bytes_data = + PlutusData::BoundedBytes(script_keyhash.to_vec()); let inner = wrap_with_constr(1, bytes_data); wrap_with_constr(0, inner) } @@ -235,7 +254,10 @@ impl From
for PlutusData { ShelleyDelegationPart::Null => empty_constr(1), }; - wrap_multiple_with_constr(0, vec![payment_part_plutus_data, stake_part_plutus_data]) + wrap_multiple_with_constr( + 0, + vec![payment_part_plutus_data, stake_part_plutus_data], + ) } _ => todo!(), } diff --git a/src/scripts/plutus_validator/tests.rs b/src/scripts/plutus_validator/tests.rs index 968816d..e5d6dc6 100644 --- a/src/scripts/plutus_validator/tests.rs +++ b/src/scripts/plutus_validator/tests.rs @@ -1,5 +1,8 @@ use super::*; -use crate::scripts::context::{pub_key_hash_from_address_if_available, ContextBuilder}; +use crate::scripts::context::{ + pub_key_hash_from_address_if_available, + ContextBuilder, +}; mod game; mod hello; diff --git a/src/scripts/plutus_validator/tests/game.rs b/src/scripts/plutus_validator/tests/game.rs index 92caf06..bfcf3aa 100644 --- a/src/scripts/plutus_validator/tests/game.rs +++ b/src/scripts/plutus_validator/tests/game.rs @@ -1,6 +1,9 @@ use super::*; use crate::scripts::context::pub_key_hash_from_address_if_available; -use sha2::{Digest, Sha256}; +use sha2::{ + Digest, + Sha256, +}; struct HashedString { inner: Vec, diff --git a/src/scripts/plutus_validator/tests/hello.rs b/src/scripts/plutus_validator/tests/hello.rs index 3379a77..b8e7aa2 100644 --- a/src/scripts/plutus_validator/tests/hello.rs +++ b/src/scripts/plutus_validator/tests/hello.rs @@ -1,7 +1,13 @@ -use crate::scripts::context::{pub_key_hash_from_address_if_available, ContextBuilder}; -use crate::scripts::plutus_validator::PlutusValidator; -use crate::scripts::raw_script::PlutusScriptFile; -use crate::scripts::{ScriptError, Validator}; +use crate::scripts::{ + context::{ + pub_key_hash_from_address_if_available, + ContextBuilder, + }, + plutus_validator::PlutusValidator, + raw_script::PlutusScriptFile, + ScriptError, + Validator, +}; use pallas_addresses::Address; /// run :: HelloDatum -> HelloRedeemer -> ScriptContext -> Bool diff --git a/src/scripts/raw_script.rs b/src/scripts/raw_script.rs index dbb4459..63fba86 100644 --- a/src/scripts/raw_script.rs +++ b/src/scripts/raw_script.rs @@ -1,5 +1,8 @@ use crate::scripts::ExecutionCost; -use serde::{Deserialize, Serialize}; +use serde::{ + Deserialize, + Serialize, +}; use thiserror::Error; use uplc::machine::cost_model::ExBudget; diff --git a/src/smart_contract.rs b/src/smart_contract.rs index c6242a9..0623f6a 100644 --- a/src/smart_contract.rs +++ b/src/smart_contract.rs @@ -1,8 +1,12 @@ use async_trait::async_trait; use std::fmt::Debug; -use crate::transaction::TxId; -use crate::{error::Result, ledger_client::LedgerClient, logic::SCLogic}; +use crate::{ + error::Result, + ledger_client::LedgerClient, + logic::SCLogic, + transaction::TxId, +}; /// Interface defining how to interact with your smart contract #[async_trait] @@ -77,7 +81,10 @@ where let tx = tx_actions.to_unbuilt_tx()?; match self.ledger_client.issue(tx).await { Ok(tx_id) => { - tracing::info!("Successfully submitted transaction with id: {:?}", &tx_id); + tracing::info!( + "Successfully submitted transaction with id: {:?}", + &tx_id + ); Ok(tx_id) } Err(err) => { diff --git a/src/transaction.rs b/src/transaction.rs index f11b6f4..cb0d9d5 100644 --- a/src/transaction.rs +++ b/src/transaction.rs @@ -1,15 +1,26 @@ -use crate::transaction::nested_value_map::{add_amount_to_nested_map, nested_map_to_vecs}; use crate::{ error::*, - output::{Output, UnbuiltOutput}, + output::{ + Output, + UnbuiltOutput, + }, policy_id::PolicyId, - scripts::{MintingPolicy, Validator}, + scripts::{ + MintingPolicy, + Validator, + }, + transaction::nested_value_map::{ + add_amount_to_nested_map, + nested_map_to_vecs, + }, values::Values, }; use pallas_addresses::Address; -use std::cell::RefCell; -use std::collections::HashMap; -use std::fmt::Debug; +use std::{ + cell::RefCell, + collections::HashMap, + fmt::Debug, +}; pub(crate) mod nested_value_map; @@ -75,7 +86,7 @@ pub enum Action { /// Redeemer used with the validator redeemer: Redeemer, /// Validator used to validate the transaction - script: Box>, // Is there a way to do this without `dyn`? + script: Box>, /* Is there a way to do this without `dyn`? */ }, /// Specify a specific input to use in the transaction SpecificInput { @@ -120,7 +131,12 @@ impl TxActions { /// Add a transfer to the actions. /// This will transfer `amount` of `policy_id` to `recipient` without specifying specific inputs /// and outputs. - pub fn with_transfer(mut self, amount: u64, recipient: Address, policy_id: PolicyId) -> Self { + pub fn with_transfer( + mut self, + amount: u64, + recipient: Address, + policy_id: PolicyId, + ) -> Self { let action = Action::Transfer { amount, recipient, @@ -152,7 +168,12 @@ impl TxActions { /// Add a script init to the actions. /// This will lock the `values` at the `address` with the `datum`. - pub fn with_script_init(mut self, datum: Datum, values: Values, address: Address) -> Self { + pub fn with_script_init( + mut self, + datum: Datum, + values: Values, + address: Address, + ) -> Self { let action = Action::InitScript { datum, values, @@ -191,7 +212,11 @@ impl TxActions { } /// Specify valid range in seconds since the Unix epoch - pub fn with_valid_range_secs(mut self, lower: Option, upper: Option) -> Self { + pub fn with_valid_range_secs( + mut self, + lower: Option, + upper: Option, + ) -> Self { self.valid_range = (lower, upper); self } @@ -217,7 +242,12 @@ impl TxActions { recipient, policy_id: policy, } => { - add_amount_to_nested_map(&mut min_output_values, amount, &recipient, &policy); + add_amount_to_nested_map( + &mut min_output_values, + amount, + &recipient, + &policy, + ); } Action::Mint { amount, @@ -273,12 +303,13 @@ fn create_outputs_for( let outputs: Result> = values .into_iter() .map(|(owner, val_vec)| { - let values = val_vec - .iter() - .fold(Values::default(), |mut acc, (policy, amt)| { - acc.add_one_value(policy, *amt); - acc - }); + let values = + val_vec + .iter() + .fold(Values::default(), |mut acc, (policy, amt)| { + acc.add_one_value(policy, *amt); + acc + }); let addr = Address::from_bech32(&owner) .map_err(|e| Error::Address(format!("Bad Bech32: {e:?}")))?; Ok(UnbuiltOutput::new_wallet(addr, values)) diff --git a/src/transaction/nested_value_map.rs b/src/transaction/nested_value_map.rs index d9ed2f4..10fe594 100644 --- a/src/transaction/nested_value_map.rs +++ b/src/transaction/nested_value_map.rs @@ -1,6 +1,12 @@ -use crate::{values::Values, PolicyId}; +use crate::{ + values::Values, + PolicyId, +}; use pallas_addresses::Address; -use std::{cell::RefCell, collections::HashMap}; +use std::{ + cell::RefCell, + collections::HashMap, +}; pub(crate) fn nested_map_to_vecs( nested_map: HashMap>, diff --git a/src/trireme_ledger_client.rs b/src/trireme_ledger_client.rs index be071f2..c31fbb7 100644 --- a/src/trireme_ledger_client.rs +++ b/src/trireme_ledger_client.rs @@ -1,38 +1,70 @@ use crate::{ error::*, ledger_client::{ - test_ledger_client::local_persisted_storage::LocalPersistedStorage, - test_ledger_client::TestLedgerClient, LedgerClient, LedgerClientError, LedgerClientResult, + test_ledger_client::{ + local_persisted_storage::LocalPersistedStorage, + TestLedgerClient, + }, + LedgerClient, + LedgerClientError, + LedgerClientResult, }, output::Output, scripts::plutus_validator::plutus_data::PlutusData, transaction::TxId, - trireme_ledger_client::cml_client::blockfrost_ledger::BlockfrostApiKey, - trireme_ledger_client::raw_secret_phrase::RawSecretPhraseKeys, + trireme_ledger_client::{ + cml_client::blockfrost_ledger::BlockfrostApiKey, + raw_secret_phrase::RawSecretPhraseKeys, + }, UnbuiltTransaction, }; -use crate::trireme_ledger_client::cml_client::network_settings::NetworkSettings; -use crate::trireme_ledger_client::cml_client::ogmios_scrolls_ledger::OgmiosScrollsLedger; -use crate::trireme_ledger_client::cml_client::Keys; -use crate::trireme_ledger_client::terminal_password_phrase::{ - PasswordProtectedPhraseKeys, TerminalPasswordUpfront, +use crate::trireme_ledger_client::{ + cml_client::{ + network_settings::NetworkSettings, + ogmios_scrolls_ledger::OgmiosScrollsLedger, + Keys, + }, + terminal_password_phrase::{ + PasswordProtectedPhraseKeys, + TerminalPasswordUpfront, + }, }; use async_trait::async_trait; -use blockfrost_http_client::{MAINNET_URL, PREPROD_NETWORK_URL}; -use cardano_multiplatform_lib::address::BaseAddress; -use cardano_multiplatform_lib::crypto::PrivateKey; +use blockfrost_http_client::{ + MAINNET_URL, + PREPROD_NETWORK_URL, +}; +use cardano_multiplatform_lib::{ + address::BaseAddress, + crypto::PrivateKey, +}; use cml_client::{ - blockfrost_ledger::BlockFrostLedger, plutus_data_interop::PlutusDataInterop, CMLLedgerCLient, + blockfrost_ledger::BlockFrostLedger, + plutus_data_interop::PlutusDataInterop, + CMLLedgerCLient, }; use dirs::home_dir; use ogmios_client::OgmiosClient; use pallas_addresses::Address; use scrolls_client::ScrollsClient; -use serde::{de::DeserializeOwned, ser, Deserialize, Serialize}; -use std::{fmt::Debug, hash::Hash, marker::PhantomData, path::PathBuf}; +use serde::{ + de::DeserializeOwned, + ser, + Deserialize, + Serialize, +}; +use std::{ + fmt::Debug, + hash::Hash, + marker::PhantomData, + path::PathBuf, +}; use thiserror::Error; -use tokio::{fs, io::AsyncWriteExt}; +use tokio::{ + fs, + io::AsyncWriteExt, +}; /// CML CLient module pub mod cml_client; @@ -52,8 +84,8 @@ pub const CLIENT_CONFIG_FILE: &str = "config.toml"; /// Default Trireme config folder pub fn path_to_trireme_config_dir() -> Result { - let mut dir = - home_dir().ok_or_else(|| Error::Trireme("Could not find home directory :(".to_string()))?; + let mut dir = home_dir() + .ok_or_else(|| Error::Trireme("Could not find home directory :(".to_string()))?; dir.push(TRIREME_CONFIG_FOLDER); Ok(dir) } @@ -348,7 +380,8 @@ impl ClientConfig { let network = inner.network; let keys = match inner.key_source { KeySource::RawSecretPhrase { phrase_file } => { - let keys = RawSecretPhraseKeys::new(phrase_file, network.clone().into()); + let keys = + RawSecretPhraseKeys::new(phrase_file, network.clone().into()); SecretPhraseKeys::RawSecretPhraseKeys(keys) } KeySource::TerminalPasswordUpfrontSecretPhrase { @@ -401,7 +434,8 @@ impl ClientConfig { ogmios_ip, ogmios_port, } => { - let scrolls_client = ScrollsClient::new_redis(scrolls_ip, scrolls_port); + let scrolls_client = + ScrollsClient::new_redis(scrolls_ip, scrolls_port); let ogmios_client = OgmiosClient::new(ogmios_ip, ogmios_port); let network_settings: NetworkSettings = network.into(); let ledger = OgmiosScrollsLedger::new( @@ -459,7 +493,9 @@ impl Keys for SecretPhraseKeys { async fn private_key(&self) -> cml_client::error::Result { match self { SecretPhraseKeys::RawSecretPhraseKeys(keys) => keys.private_key().await, - SecretPhraseKeys::PasswordProtectedPhraseKeys(keys) => keys.private_key().await, + SecretPhraseKeys::PasswordProtectedPhraseKeys(keys) => { + keys.private_key().await + } } } } @@ -479,7 +515,9 @@ where /// BlockFrost client BlockFrost(CMLLedgerCLient), /// Ogmios + Scrolls client - OgmiosScrolls(CMLLedgerCLient), + OgmiosScrolls( + CMLLedgerCLient, + ), /// Test client Mocked(TestLedgerClient>), } @@ -515,13 +553,17 @@ where /// Get current time within context of current ledger pub async fn current_time(&self) -> LedgerClientResult { match &self.inner_client { - InnerClient::BlockFrost(_cml_client) => Err(LedgerClientError::CurrentTime(Box::new( - Error::Trireme("Not implemented for Blockfrost client".to_string()), - ))), + InnerClient::BlockFrost(_cml_client) => { + Err(LedgerClientError::CurrentTime(Box::new(Error::Trireme( + "Not implemented for Blockfrost client".to_string(), + )))) + } InnerClient::Mocked(test_client) => test_client.current_time_secs().await, - InnerClient::OgmiosScrolls(_) => Err(LedgerClientError::CurrentTime(Box::new( - Error::Trireme("Not implemented for Ogmios/Scrolls client".to_string()), - ))), + InnerClient::OgmiosScrolls(_) => { + Err(LedgerClientError::CurrentTime(Box::new(Error::Trireme( + "Not implemented for Ogmios/Scrolls client".to_string(), + )))) + } } } @@ -530,19 +572,26 @@ where /// **NOTE:** This is only implemented for the test client. pub async fn advance_blocks(&self, count: i64) -> LedgerClientResult<()> { match &self.inner_client { - InnerClient::BlockFrost(_cml_client) => Err(LedgerClientError::CurrentTime(Box::new( - Error::Trireme("Not implemented for Blockfrost client".to_string()), - ))), - InnerClient::Mocked(test_client) => test_client.advance_time_n_blocks(count).await, - InnerClient::OgmiosScrolls(_) => Err(LedgerClientError::CurrentTime(Box::new( - Error::Trireme("Not implemented for Ogmios/Scrolls client".to_string()), - ))), + InnerClient::BlockFrost(_cml_client) => { + Err(LedgerClientError::CurrentTime(Box::new(Error::Trireme( + "Not implemented for Blockfrost client".to_string(), + )))) + } + InnerClient::Mocked(test_client) => { + test_client.advance_time_n_blocks(count).await + } + InnerClient::OgmiosScrolls(_) => { + Err(LedgerClientError::CurrentTime(Box::new(Error::Trireme( + "Not implemented for Ogmios/Scrolls client".to_string(), + )))) + } } } } #[async_trait] -impl LedgerClient for TriremeLedgerClient +impl LedgerClient + for TriremeLedgerClient where Datum: PlutusDataInterop + Clone @@ -569,9 +618,15 @@ where count: usize, ) -> LedgerClientResult>> { match &self.inner_client { - InnerClient::BlockFrost(cml_client) => cml_client.outputs_at_address(address, count), - InnerClient::Mocked(test_client) => test_client.outputs_at_address(address, count), - InnerClient::OgmiosScrolls(cml_client) => cml_client.outputs_at_address(address, count), + InnerClient::BlockFrost(cml_client) => { + cml_client.outputs_at_address(address, count) + } + InnerClient::Mocked(test_client) => { + test_client.outputs_at_address(address, count) + } + InnerClient::OgmiosScrolls(cml_client) => { + cml_client.outputs_at_address(address, count) + } } .await } @@ -581,14 +636,23 @@ where address: &Address, ) -> LedgerClientResult>> { match &self.inner_client { - InnerClient::BlockFrost(cml_client) => cml_client.all_outputs_at_address(address), - InnerClient::Mocked(test_client) => test_client.all_outputs_at_address(address), - InnerClient::OgmiosScrolls(cml_client) => cml_client.all_outputs_at_address(address), + InnerClient::BlockFrost(cml_client) => { + cml_client.all_outputs_at_address(address) + } + InnerClient::Mocked(test_client) => { + test_client.all_outputs_at_address(address) + } + InnerClient::OgmiosScrolls(cml_client) => { + cml_client.all_outputs_at_address(address) + } } .await } - async fn issue(&self, tx: UnbuiltTransaction) -> LedgerClientResult { + async fn issue( + &self, + tx: UnbuiltTransaction, + ) -> LedgerClientResult { match &self.inner_client { InnerClient::BlockFrost(cml_client) => cml_client.issue(tx), InnerClient::Mocked(test_client) => test_client.issue(tx), @@ -643,7 +707,8 @@ pub async fn write_toml_struct_to_file( file_path: &PathBuf, toml_struct: &Toml, ) -> Result<()> { - let serialized = toml::to_string(&toml_struct).map_err(|e| Error::TOML(Box::new(e)))?; + let serialized = + toml::to_string(&toml_struct).map_err(|e| Error::TOML(Box::new(e)))?; let parent_dir = file_path .parent() .ok_or_else(|| TomlError::NoParentDir(format!("{file_path:?}"))) @@ -672,7 +737,8 @@ pub async fn read_toml_struct_from_file( let contents = fs::read_to_string(file_path) .await .map_err(|e| Error::TOML(Box::new(e)))?; - let toml_struct = toml::from_str(&contents).map_err(|e| Error::TOML(Box::new(e)))?; + let toml_struct = + toml::from_str(&contents).map_err(|e| Error::TOML(Box::new(e)))?; Ok(Some(toml_struct)) } else { Ok(None) diff --git a/src/trireme_ledger_client/cml_client.rs b/src/trireme_ledger_client/cml_client.rs index aa3f190..e33cabb 100644 --- a/src/trireme_ledger_client/cml_client.rs +++ b/src/trireme_ledger_client/cml_client.rs @@ -1,44 +1,106 @@ -use crate::trireme_ledger_client::cml_client::network_settings::NetworkSettings; use crate::{ - ledger_client::{LedgerClient, LedgerClientError, LedgerClientResult}, - output::{Output, UnbuiltOutput}, + ledger_client::{ + LedgerClient, + LedgerClientError, + LedgerClientResult, + }, + output::{ + Output, + UnbuiltOutput, + }, scripts::Validator, - transaction::{TransactionVersion, TxId}, - trireme_ledger_client::cml_client::issuance_helpers::{ - cml_v1_script_from_nau_policy, cml_v2_script_from_nau_policy, - cml_v2_script_from_nau_script, vasil_v2_tx_builder, + transaction::{ + TransactionVersion, + TxId, }, trireme_ledger_client::cml_client::{ issuance_helpers::{ - add_collateral, build_tx_for_signing, cml_v1_script_from_nau_script, input_tx_hash, - partial_script_witness, select_inputs_from_utxos, sign_tx, - specify_utxos_available_for_input_selection, utxo_to_nau_utxo, vasil_v1_tx_builder, + add_collateral, + build_tx_for_signing, + cml_v1_script_from_nau_policy, + cml_v1_script_from_nau_script, + cml_v2_script_from_nau_policy, + cml_v2_script_from_nau_script, + input_tx_hash, + partial_script_witness, + select_inputs_from_utxos, + sign_tx, + specify_utxos_available_for_input_selection, + utxo_to_nau_utxo, + vasil_v1_tx_builder, + vasil_v2_tx_builder, }, + network_settings::NetworkSettings, plutus_data_interop::PlutusDataInterop, }, UnbuiltTransaction, }; use async_trait::async_trait; use cardano_multiplatform_lib::{ - address::{Address as CMLAddress, BaseAddress, EnterpriseAddress, StakeCredential}, + address::{ + Address as CMLAddress, + BaseAddress, + EnterpriseAddress, + StakeCredential, + }, builders::{ - input_builder::{InputBuilderResult, SingleInputBuilder}, - mint_builder::{MintBuilderResult, SingleMintBuilder}, + input_builder::{ + InputBuilderResult, + SingleInputBuilder, + }, + mint_builder::{ + MintBuilderResult, + SingleMintBuilder, + }, output_builder::SingleOutputBuilderResult, redeemer_builder::RedeemerWitnessKey, - tx_builder::{ChangeSelectionAlgo, TransactionBuilder}, - witness_builder::{PartialPlutusWitness, PlutusScriptWitness}, + tx_builder::{ + ChangeSelectionAlgo, + TransactionBuilder, + }, + witness_builder::{ + PartialPlutusWitness, + PlutusScriptWitness, + }, }, - crypto::{PrivateKey, TransactionHash}, - ledger::common::{hash::hash_plutus_data, value::BigNum, value::Int, value::Value as CMLValue}, - plutus::{ExUnits, PlutusData, PlutusScript, RedeemerTag}, - AssetName, Datum as CMLDatum, MintAssets, RequiredSigners, Transaction as CMLTransaction, - TransactionInput, TransactionOutput, + crypto::{ + PrivateKey, + TransactionHash, + }, + ledger::common::{ + hash::hash_plutus_data, + value::{ + BigNum, + Int, + Value as CMLValue, + }, + }, + plutus::{ + ExUnits, + PlutusData, + PlutusScript, + RedeemerTag, + }, + AssetName, + Datum as CMLDatum, + MintAssets, + RequiredSigners, + Transaction as CMLTransaction, + TransactionInput, + TransactionOutput, }; use error::*; -use pallas_addresses::{Address, Network as CMLNetwork}; -use std::time::UNIX_EPOCH; -use std::{collections::HashMap, fmt::Debug, marker::PhantomData, ops::Deref}; +use pallas_addresses::{ + Address, + Network as CMLNetwork, +}; +use std::{ + collections::HashMap, + fmt::Debug, + marker::PhantomData, + ops::Deref, + time::UNIX_EPOCH, +}; /// Blockfrost Ledger module pub mod blockfrost_ledger; @@ -217,11 +279,18 @@ pub trait Ledger { /// Get the last block time in seconds async fn last_block_time_secs(&self) -> Result; /// Get the UTxOs for an address - async fn get_utxos_for_addr(&self, addr: &CMLAddress, count: usize) -> Result>; + async fn get_utxos_for_addr( + &self, + addr: &CMLAddress, + count: usize, + ) -> Result>; /// Get all the UTxOs for an address async fn get_all_utxos_for_addr(&self, addr: &CMLAddress) -> Result>; /// Calculate the execution units for a transaction - async fn calculate_ex_units(&self, tx: &CMLTransaction) -> Result>; + async fn calculate_ex_units( + &self, + tx: &CMLTransaction, + ) -> Result>; /// Submit a transaction async fn submit_transaction(&self, tx: &CMLTransaction) -> Result; } @@ -244,7 +313,10 @@ where } } - async fn add_outputs_for_tx( + async fn add_outputs_for_tx< + Datum: PlutusDataInterop + Debug, + Redeemer: PlutusDataInterop, + >( &self, tx_builder: &mut TransactionBuilder, tx: &UnbuiltTransaction, @@ -256,8 +328,8 @@ where .try_into() .map_err(as_failed_to_issue_tx)?; let recipient = unbuilt_output.owner(); - let recp_addr = - addr_from_bech_32(&recipient.to_string()).map_err(as_failed_to_issue_tx)?; + let recp_addr = addr_from_bech_32(&recipient.to_string()) + .map_err(as_failed_to_issue_tx)?; let mut output = TransactionOutput::new(&recp_addr, &cml_values); let res = if let UnbuiltOutput::Validator { datum, .. } = unbuilt_output { let data = datum.to_plutus_data(); @@ -281,7 +353,8 @@ where async fn cml_script_address(&self, cml_script: &PlutusScript) -> CMLAddress { let script_hash = cml_script.hash(); let stake_cred = StakeCredential::from_scripthash(&script_hash); - let enterprise_addr = EnterpriseAddress::new(self.network_settings.network(), &stake_cred); + let enterprise_addr = + EnterpriseAddress::new(self.network_settings.network(), &stake_cred); enterprise_addr.to_address() } @@ -357,7 +430,10 @@ where Ok(cml_input) } - async fn add_v1_script_input( + async fn add_v1_script_input< + Datum: PlutusDataInterop + Clone, + Redeemer: PlutusDataInterop, + >( &self, tx_builder: &mut TransactionBuilder, input: &Output, @@ -374,7 +450,10 @@ where Ok(()) } - async fn add_v2_script_input( + async fn add_v2_script_input< + Datum: PlutusDataInterop + Clone, + Redeemer: PlutusDataInterop, + >( &self, tx_builder: &mut TransactionBuilder, input: &Output, @@ -391,7 +470,10 @@ where Ok(()) } - async fn add_tokens_for_v1_minting( + async fn add_tokens_for_v1_minting< + Datum: PlutusDataInterop, + Redeemer: PlutusDataInterop, + >( &self, tx_builder: &mut TransactionBuilder, tx: &UnbuiltTransaction, @@ -406,7 +488,10 @@ where Ok(()) } - async fn add_tokens_for_v2_minting( + async fn add_tokens_for_v2_minting< + Datum: PlutusDataInterop, + Redeemer: PlutusDataInterop, + >( &self, tx_builder: &mut TransactionBuilder, tx: &UnbuiltTransaction, @@ -448,7 +533,10 @@ where Ok(res) } - async fn add_v1_script_inputs( + async fn add_v1_script_inputs< + Datum: PlutusDataInterop + Clone, + Redeemer: PlutusDataInterop, + >( &self, tx_builder: &mut TransactionBuilder, tx: &UnbuiltTransaction, @@ -460,7 +548,10 @@ where Ok(()) } - async fn add_v2_script_inputs( + async fn add_v2_script_inputs< + Datum: PlutusDataInterop + Clone, + Redeemer: PlutusDataInterop, + >( &self, tx_builder: &mut TransactionBuilder, tx: &UnbuiltTransaction, @@ -514,7 +605,10 @@ where Ok(TxId::new(&submit_res)) } - async fn issue_v1_tx( + async fn issue_v1_tx< + Datum: PlutusDataInterop + Debug + Clone, + Redeemer: PlutusDataInterop, + >( &self, tx: UnbuiltTransaction, my_utxos: Vec, @@ -524,19 +618,27 @@ where let mut tx_builder = vasil_v1_tx_builder()?; self.add_v1_script_inputs(&mut tx_builder, &tx).await?; self.add_tokens_for_v1_minting(&mut tx_builder, &tx).await?; - specify_utxos_available_for_input_selection(&mut tx_builder, &my_address, &my_utxos) - .await?; + specify_utxos_available_for_input_selection( + &mut tx_builder, + &my_address, + &my_utxos, + ) + .await?; self.add_outputs_for_tx(&mut tx_builder, &tx).await?; add_collateral(&mut tx_builder, &my_address, &my_utxos).await?; select_inputs_from_utxos(&mut tx_builder).await?; self.update_ex_units(&mut tx_builder, &my_address).await?; - let mut signed_tx_builder = build_tx_for_signing(&mut tx_builder, &my_address).await?; + let mut signed_tx_builder = + build_tx_for_signing(&mut tx_builder, &my_address).await?; let tx = sign_tx(&mut signed_tx_builder, &priv_key).await?; let tx_id = self.submit_tx(&tx).await?; Ok(tx_id) } - async fn issue_v2_tx( + async fn issue_v2_tx< + Datum: PlutusDataInterop + Debug + Clone, + Redeemer: PlutusDataInterop, + >( &self, tx: UnbuiltTransaction, my_utxos: Vec, @@ -547,20 +649,28 @@ where self.set_valid_range(&mut tx_builder, &tx).await?; self.add_v2_script_inputs(&mut tx_builder, &tx).await?; self.add_tokens_for_v2_minting(&mut tx_builder, &tx).await?; - specify_utxos_available_for_input_selection(&mut tx_builder, &my_address, &my_utxos) - .await?; + specify_utxos_available_for_input_selection( + &mut tx_builder, + &my_address, + &my_utxos, + ) + .await?; self.add_specific_inputs(&mut tx_builder, &tx).await?; self.add_outputs_for_tx(&mut tx_builder, &tx).await?; add_collateral(&mut tx_builder, &my_address, &my_utxos).await?; select_inputs_from_utxos(&mut tx_builder).await?; self.update_ex_units(&mut tx_builder, &my_address).await?; - let mut signed_tx_builder = build_tx_for_signing(&mut tx_builder, &my_address).await?; + let mut signed_tx_builder = + build_tx_for_signing(&mut tx_builder, &my_address).await?; let tx = sign_tx(&mut signed_tx_builder, &priv_key).await?; let tx_id = self.submit_tx(&tx).await?; Ok(tx_id) } - async fn set_valid_range( + async fn set_valid_range< + Datum: PlutusDataInterop + Debug, + Redeemer: PlutusDataInterop, + >( &self, tx_builder: &mut TransactionBuilder, tx: &UnbuiltTransaction, @@ -587,7 +697,10 @@ where Ok(()) } - async fn add_specific_inputs( + async fn add_specific_inputs< + Datum: PlutusDataInterop + Debug, + Redeemer: PlutusDataInterop, + >( &self, tx_builder: &mut TransactionBuilder, tx: &UnbuiltTransaction, @@ -620,7 +733,8 @@ where } #[async_trait] -impl LedgerClient for CMLLedgerCLient +impl LedgerClient + for CMLLedgerCLient where L: Ledger + Send + Sync, K: Keys + Send + Sync, @@ -651,8 +765,8 @@ where let addr_string = address .to_bech32() .map_err(|e| LedgerClientError::BadAddress(Box::new(e)))?; - let cml_addr = - addr_from_bech_32(&addr_string).map_err(as_failed_to_retrieve_by_address(address))?; + let cml_addr = addr_from_bech_32(&addr_string) + .map_err(as_failed_to_retrieve_by_address(address))?; let bf_utxos = self .ledger @@ -673,8 +787,8 @@ where address: &Address, ) -> LedgerClientResult>> { let addr_string = address.to_bech32().expect("Already Validated"); - let cml_addr = - addr_from_bech_32(&addr_string).map_err(as_failed_to_retrieve_by_address(address))?; + let cml_addr = addr_from_bech_32(&addr_string) + .map_err(as_failed_to_retrieve_by_address(address))?; let bf_utxos = self .ledger @@ -690,7 +804,10 @@ where Ok(utxos) } - async fn issue(&self, tx: UnbuiltTransaction) -> LedgerClientResult { + async fn issue( + &self, + tx: UnbuiltTransaction, + ) -> LedgerClientResult { let my_address = self .keys .base_addr() @@ -710,8 +827,12 @@ where .map_err(as_failed_to_issue_tx)?; match tx.script_version { - TransactionVersion::V1 => self.issue_v1_tx(tx, my_utxos, my_address, priv_key).await, - TransactionVersion::V2 => self.issue_v2_tx(tx, my_utxos, my_address, priv_key).await, + TransactionVersion::V1 => { + self.issue_v1_tx(tx, my_utxos, my_address, priv_key).await + } + TransactionVersion::V2 => { + self.issue_v2_tx(tx, my_utxos, my_address, priv_key).await + } } } diff --git a/src/trireme_ledger_client/cml_client/blockfrost_ledger.rs b/src/trireme_ledger_client/cml_client/blockfrost_ledger.rs index ef70c54..390f914 100644 --- a/src/trireme_ledger_client/cml_client/blockfrost_ledger.rs +++ b/src/trireme_ledger_client/cml_client/blockfrost_ledger.rs @@ -1,20 +1,47 @@ use super::error::*; -use crate::trireme_ledger_client::cml_client::{error::CMLLCError, ExecutionCost, Ledger, UTxO}; +use crate::trireme_ledger_client::cml_client::{ + error::CMLLCError, + ExecutionCost, + Ledger, + UTxO, +}; use async_trait::async_trait; -use blockfrost_http_client::error::Error; use blockfrost_http_client::{ - models::ExecutionType, models::UTxO as BFUTxO, models::Value as BFValue, BlockFrostHttp, + error::Error, + models::{ + ExecutionType, + UTxO as BFUTxO, + Value as BFValue, + }, + BlockFrostHttp, BlockFrostHttpTrait, }; use cardano_multiplatform_lib::{ - address::Address as CMLAddress, crypto::TransactionHash, ledger::common::value::BigNum, - ledger::common::value::Value as CMLValue, plutus::encode_json_str_to_plutus_datum, - plutus::PlutusDatumSchema, AssetName, Assets, MultiAsset, PolicyID, + address::Address as CMLAddress, + crypto::TransactionHash, + ledger::common::value::{ + BigNum, + Value as CMLValue, + }, + plutus::{ + encode_json_str_to_plutus_datum, + PlutusDatumSchema, + }, + AssetName, + Assets, + MultiAsset, + PolicyID, Transaction as CMLTransaction, }; use futures::future; -use serde::{Deserialize, Serialize}; -use std::{collections::HashMap, str::FromStr}; +use serde::{ + Deserialize, + Serialize, +}; +use std::{ + collections::HashMap, + str::FromStr, +}; use thiserror::Error; /// A Ledger implementation that uses Blockfrost as a backend @@ -83,13 +110,13 @@ pub fn cmlvalue_from_bfvalues(values: &[BFValue]) -> Result { let asset_name_hex = &unit .get(56..) .ok_or(CMLLCError::InvalidPolicyId(unit.to_string()))?; - let asset_name_bytes = - hex::decode(asset_name_hex).map_err(|e| CMLLCError::JsError(e.to_string()))?; + let asset_name_bytes = hex::decode(asset_name_hex) + .map_err(|e| CMLLCError::JsError(e.to_string()))?; let asset_name = AssetName::new(asset_name_bytes) .map_err(|e| CMLLCError::JsError(e.to_string()))?; let mut assets = Assets::new(); - let big_number = - BigNum::from_str(quantity).map_err(|e| CMLLCError::JsError(e.to_string()))?; + let big_number = BigNum::from_str(quantity) + .map_err(|e| CMLLCError::JsError(e.to_string()))?; assets.insert(&asset_name, &big_number); let mut multi_assets = MultiAsset::new(); multi_assets.insert(&policy_id, &assets); @@ -112,7 +139,11 @@ impl Ledger for BlockFrostLedger { Ok(res.time() as i64) } - async fn get_utxos_for_addr(&self, addr: &CMLAddress, count: usize) -> Result> { + async fn get_utxos_for_addr( + &self, + addr: &CMLAddress, + count: usize, + ) -> Result> { let addr_string = addr .to_bech32(None) .map_err(|e| CMLLCError::JsError(e.to_string()))?; @@ -170,7 +201,10 @@ impl Ledger for BlockFrostLedger { Ok(utxos) } - async fn calculate_ex_units(&self, tx: &CMLTransaction) -> Result> { + async fn calculate_ex_units( + &self, + tx: &CMLTransaction, + ) -> Result> { let bytes = tx.to_bytes(); let res = self .client diff --git a/src/trireme_ledger_client/cml_client/issuance_helpers.rs b/src/trireme_ledger_client/cml_client/issuance_helpers.rs index fb35411..fcd50d5 100644 --- a/src/trireme_ledger_client/cml_client/issuance_helpers.rs +++ b/src/trireme_ledger_client/cml_client/issuance_helpers.rs @@ -1,11 +1,18 @@ use super::error::*; -use crate::scripts::MintingPolicy; use crate::{ - ledger_client::{LedgerClientError, LedgerClientResult}, + ledger_client::{ + LedgerClientError, + LedgerClientResult, + }, output::Output, - scripts::Validator, + scripts::{ + MintingPolicy, + Validator, + }, trireme_ledger_client::cml_client::{ - error::CMLLCError::JsError, plutus_data_interop::PlutusDataInterop, UTxO, + error::CMLLCError::JsError, + plutus_data_interop::PlutusDataInterop, + UTxO, }, values::Values, PolicyId, @@ -13,25 +20,55 @@ use crate::{ use cardano_multiplatform_lib::{ address::Address as CMLAddress, builders::{ - input_builder::{InputBuilderResult, SingleInputBuilder}, + input_builder::{ + InputBuilderResult, + SingleInputBuilder, + }, output_builder::TransactionOutputBuilder, - tx_builder::{ChangeSelectionAlgo, CoinSelectionStrategyCIP2, SignedTxBuilder}, - tx_builder::{TransactionBuilder, TransactionBuilderConfigBuilder}, - witness_builder::{PartialPlutusWitness, PlutusScriptWitness}, + tx_builder::{ + ChangeSelectionAlgo, + CoinSelectionStrategyCIP2, + SignedTxBuilder, + TransactionBuilder, + TransactionBuilderConfigBuilder, + }, + witness_builder::{ + PartialPlutusWitness, + PlutusScriptWitness, + }, + }, + crypto::{ + PrivateKey, + ScriptHash, + TransactionHash, }, - crypto::ScriptHash, - crypto::{PrivateKey, TransactionHash}, ledger::{ alonzo::fees::LinearFee, - common::hash::hash_transaction, - common::value::{Int, Value as CMLValue}, + common::{ + hash::hash_transaction, + value::{ + Int, + Value as CMLValue, + }, + }, shelley::witness::make_vkey_witness, }, - plutus::PlutusV2Script, - plutus::{CostModel, Costmdls, ExUnitPrices, Language}, - plutus::{PlutusScript, PlutusV1Script}, - AssetName, Assets, MultiAsset, Transaction as CMLTransaction, TransactionInput, - TransactionOutput, UnitInterval, + plutus::{ + CostModel, + Costmdls, + ExUnitPrices, + Language, + PlutusScript, + PlutusV1Script, + PlutusV2Script, + }, + AssetName, + Assets, + MultiAsset, + Transaction as CMLTransaction, + TransactionInput, + TransactionOutput, + UnitInterval, }; use pallas_addresses::Address; use std::collections::BTreeMap; @@ -55,16 +92,18 @@ pub fn vasil_v1_tx_builder() -> LedgerClientResult { let step_price = UnitInterval::new(&step_num, &step_den); let ex_unit_prices = ExUnitPrices::new(&mem_price, &step_price); let vasil_v1_cost_models = vec![ - 205665, 812, 1, 1, 1000, 571, 0, 1, 1000, 24177, 4, 1, 1000, 32, 117366, 10475, 4, 23000, - 100, 23000, 100, 23000, 100, 23000, 100, 23000, 100, 23000, 100, 100, 100, 23000, 100, - 19537, 32, 175354, 32, 46417, 4, 221973, 511, 0, 1, 89141, 32, 497525, 14068, 4, 2, 196500, - 453240, 220, 0, 1, 1, 1000, 28662, 4, 2, 245000, 216773, 62, 1, 1060367, 12586, 1, 208512, - 421, 1, 187000, 1000, 52998, 1, 80436, 32, 43249, 32, 1000, 32, 80556, 1, 57667, 4, 1000, - 10, 197145, 156, 1, 197145, 156, 1, 204924, 473, 1, 208896, 511, 1, 52467, 32, 64832, 32, - 65493, 32, 22558, 32, 16563, 32, 76511, 32, 196500, 453240, 220, 0, 1, 1, 69522, 11687, 0, - 1, 60091, 32, 196500, 453240, 220, 0, 1, 1, 196500, 453240, 220, 0, 1, 1, 806990, 30482, 4, - 1927926, 82523, 4, 265318, 0, 4, 0, 85931, 32, 205665, 812, 1, 1, 41182, 32, 212342, 32, - 31220, 32, 32696, 32, 43357, 32, 32247, 32, 38314, 32, 9462713, 1021, 10, + 205665, 812, 1, 1, 1000, 571, 0, 1, 1000, 24177, 4, 1, 1000, 32, 117366, 10475, + 4, 23000, 100, 23000, 100, 23000, 100, 23000, 100, 23000, 100, 23000, 100, 100, + 100, 23000, 100, 19537, 32, 175354, 32, 46417, 4, 221973, 511, 0, 1, 89141, 32, + 497525, 14068, 4, 2, 196500, 453240, 220, 0, 1, 1, 1000, 28662, 4, 2, 245000, + 216773, 62, 1, 1060367, 12586, 1, 208512, 421, 1, 187000, 1000, 52998, 1, 80436, + 32, 43249, 32, 1000, 32, 80556, 1, 57667, 4, 1000, 10, 197145, 156, 1, 197145, + 156, 1, 204924, 473, 1, 208896, 511, 1, 52467, 32, 64832, 32, 65493, 32, 22558, + 32, 16563, 32, 76511, 32, 196500, 453240, 220, 0, 1, 1, 69522, 11687, 0, 1, + 60091, 32, 196500, 453240, 220, 0, 1, 1, 196500, 453240, 220, 0, 1, 1, 806990, + 30482, 4, 1927926, 82523, 4, 265318, 0, 4, 0, 85931, 32, 205665, 812, 1, 1, + 41182, 32, 212342, 32, 31220, 32, 32696, 32, 43357, 32, 32247, 32, 38314, 32, + 9462713, 1021, 10, ]; let cm = CostModel::new( &Language::new_plutus_v1(), @@ -109,17 +148,18 @@ pub fn vasil_v2_tx_builder() -> LedgerClientResult { let step_price = UnitInterval::new(&step_num, &step_den); let ex_unit_prices = ExUnitPrices::new(&mem_price, &step_price); let vasil_v2_cost_models: Vec = vec![ - 205665, 812, 1, 1, 1000, 571, 0, 1, 1000, 24177, 4, 1, 1000, 32, 117366, 10475, 4, 23000, - 100, 23000, 100, 23000, 100, 23000, 100, 23000, 100, 23000, 100, 100, 100, 23000, 100, - 19537, 32, 175354, 32, 46417, 4, 221973, 511, 0, 1, 89141, 32, 497525, 14068, 4, 2, 196500, - 453240, 220, 0, 1, 1, 1000, 28662, 4, 2, 245000, 216773, 62, 1, 1060367, 12586, 1, 208512, - 421, 1, 187000, 1000, 52998, 1, 80436, 32, 43249, 32, 1000, 32, 80556, 1, 57667, 4, 1000, - 10, 197145, 156, 1, 197145, 156, 1, 204924, 473, 1, 208896, 511, 1, 52467, 32, 64832, 32, - 65493, 32, 22558, 32, 16563, 32, 76511, 32, 196500, 453240, 220, 0, 1, 1, 69522, 11687, 0, - 1, 60091, 32, 196500, 453240, 220, 0, 1, 1, 196500, 453240, 220, 0, 1, 1, 1159724, 392670, - 0, 2, 806990, 30482, 4, 1927926, 82523, 4, 265318, 0, 4, 0, 85931, 32, 205665, 812, 1, 1, - 41182, 32, 212342, 32, 31220, 32, 32696, 32, 43357, 32, 32247, 32, 38314, 32, 35892428, 10, - 57996947, 18975, 10, 38887044, 32947, 10, + 205665, 812, 1, 1, 1000, 571, 0, 1, 1000, 24177, 4, 1, 1000, 32, 117366, 10475, + 4, 23000, 100, 23000, 100, 23000, 100, 23000, 100, 23000, 100, 23000, 100, 100, + 100, 23000, 100, 19537, 32, 175354, 32, 46417, 4, 221973, 511, 0, 1, 89141, 32, + 497525, 14068, 4, 2, 196500, 453240, 220, 0, 1, 1, 1000, 28662, 4, 2, 245000, + 216773, 62, 1, 1060367, 12586, 1, 208512, 421, 1, 187000, 1000, 52998, 1, 80436, + 32, 43249, 32, 1000, 32, 80556, 1, 57667, 4, 1000, 10, 197145, 156, 1, 197145, + 156, 1, 204924, 473, 1, 208896, 511, 1, 52467, 32, 64832, 32, 65493, 32, 22558, + 32, 16563, 32, 76511, 32, 196500, 453240, 220, 0, 1, 1, 69522, 11687, 0, 1, + 60091, 32, 196500, 453240, 220, 0, 1, 1, 196500, 453240, 220, 0, 1, 1, 1159724, + 392670, 0, 2, 806990, 30482, 4, 1927926, 82523, 4, 265318, 0, 4, 0, 85931, 32, + 205665, 812, 1, 1, 41182, 32, 212342, 32, 31220, 32, 32696, 32, 43357, 32, 32247, + 32, 38314, 32, 35892428, 10, 57996947, 18975, 10, 38887044, 32947, 10, ]; let cm = CostModel::new( &Language::new_plutus_v2(), @@ -128,7 +168,9 @@ pub fn vasil_v2_tx_builder() -> LedgerClientResult { .map(|&i| Int::from_str(&i.to_string())) .collect::, _>>() .map_err(|e| { - LedgerClientError::ConfigError(format!("Cost models misconfigured: {e:?}")) + LedgerClientError::ConfigError(format!( + "Cost models misconfigured: {e:?}" + )) })?, ); let mut cost_models = Costmdls::new(); @@ -180,7 +222,8 @@ impl TryFrom for CMLValue { // 1155080. Please look into // let mut ada = 1120600u64; // TODO: This is kinda buried. Maybe ref the CML value let mut ada = 1155080u64; // TODO: This is kinda buried. Maybe ref the CML value - let mut nau_assets: BTreeMap, u64>> = BTreeMap::new(); + let mut nau_assets: BTreeMap, u64>> = + BTreeMap::new(); for (policy_id, amount) in vals.as_iter() { match policy_id { PolicyId::Lovelace => ada = *amount, @@ -257,10 +300,12 @@ fn as_nau_values(cml_value: &CMLValue) -> LedgerClientResult { let asset = assets_names.get(i); if let Some(amt) = assets.get(&asset) { let asset_bytes = asset.name(); - let asset_text = - std::str::from_utf8(&asset_bytes).map_err(as_failed_to_issue_tx)?; - let policy_id = - PolicyId::native_token(&id.to_string(), &Some(asset_text.to_string())); + let asset_text = std::str::from_utf8(&asset_bytes) + .map_err(as_failed_to_issue_tx)?; + let policy_id = PolicyId::native_token( + &id.to_string(), + &Some(asset_text.to_string()), + ); values.add_one_value(&policy_id, amt.into()); } } @@ -290,7 +335,8 @@ pub(crate) async fn add_collateral( ) -> LedgerClientResult<()> { const MIN_COLLATERAL_AMT: u64 = 5_000_000; - let collateral_utxo = select_collateral_utxo(my_address, my_utxos, MIN_COLLATERAL_AMT)?; + let collateral_utxo = + select_collateral_utxo(my_address, my_utxos, MIN_COLLATERAL_AMT)?; tx_builder .add_collateral(&collateral_utxo) @@ -330,7 +376,8 @@ pub(crate) fn select_collateral_utxo( } } let res = if let Some(utxo) = smallest_utxo_meets_qual { - let transaction_input = TransactionInput::new(utxo.tx_hash(), &utxo.output_index()); + let transaction_input = + TransactionInput::new(utxo.tx_hash(), &utxo.output_index()); let input_utxo = TransactionOutputBuilder::new() .with_address(my_cml_address) .next() diff --git a/src/trireme_ledger_client/cml_client/key_manager.rs b/src/trireme_ledger_client/cml_client/key_manager.rs index 11105ba..c6c4d78 100644 --- a/src/trireme_ledger_client/cml_client/key_manager.rs +++ b/src/trireme_ledger_client/cml_client/key_manager.rs @@ -1,11 +1,26 @@ -use super::{error::*, Keys}; +use super::{ + error::*, + Keys, +}; use async_trait::async_trait; -use bip39::{Language, Mnemonic}; +use bip39::{ + Language, + Mnemonic, +}; use cardano_multiplatform_lib::{ - address::{BaseAddress, StakeCredential}, - crypto::{Bip32PrivateKey, PrivateKey}, + address::{ + BaseAddress, + StakeCredential, + }, + crypto::{ + Bip32PrivateKey, + PrivateKey, + }, +}; +use std::{ + fs, + path::Path, }; -use std::{fs, path::Path}; use thiserror::Error; /// Standard implementation of the [`Keys`] trait @@ -66,7 +81,8 @@ impl KeyManager { let pub_key = account_key.derive(0).derive(0).to_public(); let stake_key = account_key.derive(2).derive(0).to_public(); let pub_key_creds = StakeCredential::from_keyhash(&pub_key.to_raw_key().hash()); - let stake_key_creds = StakeCredential::from_keyhash(&stake_key.to_raw_key().hash()); + let stake_key_creds = + StakeCredential::from_keyhash(&stake_key.to_raw_key().hash()); let base_addr = BaseAddress::new(self.network, &pub_key_creds, &stake_key_creds); Ok(base_addr) } diff --git a/src/trireme_ledger_client/cml_client/ogmios_scrolls_ledger.rs b/src/trireme_ledger_client/cml_client/ogmios_scrolls_ledger.rs index 97150cb..0cc6f2d 100644 --- a/src/trireme_ledger_client/cml_client/ogmios_scrolls_ledger.rs +++ b/src/trireme_ledger_client/cml_client/ogmios_scrolls_ledger.rs @@ -1,18 +1,37 @@ -use crate::trireme_ledger_client::cml_client::network_settings::NetworkSettings; use crate::trireme_ledger_client::cml_client::{ - error::{CMLLCError, Result}, - ExecutionCost, Ledger, UTxO, + error::{ + CMLLCError, + Result, + }, + network_settings::NetworkSettings, + ExecutionCost, + Ledger, + UTxO, }; use async_trait::async_trait; use cardano_multiplatform_lib::{ - address::Address as CMLAddress, crypto::TransactionHash, - ledger::common::value::Value as CMLValue, plutus::PlutusData, AssetName, Assets, MultiAsset, - PolicyID, Transaction as CMLTransaction, + address::Address as CMLAddress, + crypto::TransactionHash, + ledger::common::value::Value as CMLValue, + plutus::PlutusData, + AssetName, + Assets, + MultiAsset, + PolicyID, + Transaction as CMLTransaction, +}; +use ogmios_client::{ + EvaluationResult, + OgmiosClient, + OgmiosLocalTxSubmission, + OgmiosResponse, }; -use ogmios_client::{EvaluationResult, OgmiosClient, OgmiosLocalTxSubmission, OgmiosResponse}; use pallas_addresses::Address; use scrolls_client::{ - Amount as ScrollClientAmount, LastBlockInfo, ScrollsClient, UTxO as ScrollsClientUTxO, + Amount as ScrollClientAmount, + LastBlockInfo, + ScrollsClient, + UTxO as ScrollsClientUTxO, UTxOsByAddress, }; use std::collections::HashMap; @@ -49,8 +68,8 @@ fn cml_value_from_scroll_amount(amount: &[ScrollClientAmount]) -> Result Result> { + async fn get_utxos_for_addr( + &self, + addr: &CMLAddress, + count: usize, + ) -> Result> { let outputs = self .get_utxos(addr) .await? @@ -130,7 +153,10 @@ impl Ledger for OgmiosScrollsLedger { self.get_utxos(addr).await } - async fn calculate_ex_units(&self, tx: &CMLTransaction) -> Result> { + async fn calculate_ex_units( + &self, + tx: &CMLTransaction, + ) -> Result> { let bytes = tx.to_bytes(); let res = self.ogmios_client.evaluate_tx(&bytes, vec![]).await?; check_for_error(&res)?; diff --git a/src/trireme_ledger_client/cml_client/plutus_data_interop.rs b/src/trireme_ledger_client/cml_client/plutus_data_interop.rs index d978b33..b7b2a0e 100644 --- a/src/trireme_ledger_client/cml_client/plutus_data_interop.rs +++ b/src/trireme_ledger_client/cml_client/plutus_data_interop.rs @@ -1,9 +1,17 @@ -use crate::scripts::plutus_validator::plutus_data::{BigInt, Constr, PlutusData}; +use crate::scripts::plutus_validator::plutus_data::{ + BigInt, + Constr, + PlutusData, +}; use cardano_multiplatform_lib::{ ledger::common::value::BigInt as CMLBigInt, plutus::{ - ConstrPlutusData as CMLConstrPlutusData, PlutusData as CMLPlutusData, PlutusDataKind, - PlutusList as CMLPlutusList, PlutusList, PlutusMap as CMLPlutusMap, + ConstrPlutusData as CMLConstrPlutusData, + PlutusData as CMLPlutusData, + PlutusDataKind, + PlutusList as CMLPlutusList, + PlutusList, + PlutusMap as CMLPlutusMap, }, }; use std::collections::BTreeMap; @@ -47,11 +55,15 @@ where impl From for CMLPlutusData { fn from(data: PlutusData) -> Self { match data { - PlutusData::Constr(constr) => CMLPlutusData::new_constr_plutus_data(&constr.into()), + PlutusData::Constr(constr) => { + CMLPlutusData::new_constr_plutus_data(&constr.into()) + } PlutusData::Map(map) => { let mut plutus_map = CMLPlutusMap::new(); map.into_iter() - .map(|(key, value)| (CMLPlutusData::from(key), CMLPlutusData::from(value))) + .map(|(key, value)| { + (CMLPlutusData::from(key), CMLPlutusData::from(value)) + }) .for_each(|(key, value)| { plutus_map.insert(&key, &value); }); diff --git a/src/trireme_ledger_client/cml_client/tests.rs b/src/trireme_ledger_client/cml_client/tests.rs index 951dbc4..53d6c23 100644 --- a/src/trireme_ledger_client/cml_client/tests.rs +++ b/src/trireme_ledger_client/cml_client/tests.rs @@ -1,15 +1,26 @@ use super::*; -use crate::trireme_ledger_client::cml_client::{ - blockfrost_ledger::BlockFrostLedger, key_manager::KeyManager, +use crate::{ + trireme_ledger_client::{ + cml_client::{ + blockfrost_ledger::BlockFrostLedger, + key_manager::KeyManager, + }, + Network, + }, + PolicyId, +}; +use blockfrost_http_client::{ + load_key_from_file, + PREPROD_NETWORK_URL, }; -use crate::trireme_ledger_client::Network; -use crate::PolicyId; -use blockfrost_http_client::{load_key_from_file, PREPROD_NETWORK_URL}; use cardano_multiplatform_lib::address::BaseAddress; use std::time::Duration; use test_helpers::{ - always_succeeds_script_address, claim_always_succeeds_datum_tx, lock_at_always_succeeds_tx, - output_from_tx, transfer_tx, + always_succeeds_script_address, + claim_always_succeeds_datum_tx, + lock_at_always_succeeds_tx, + output_from_tx, + transfer_tx, }; use tokio::time::sleep; diff --git a/src/trireme_ledger_client/cml_client/tests/test_helpers.rs b/src/trireme_ledger_client/cml_client/tests/test_helpers.rs index 984a4f5..9468204 100644 --- a/src/trireme_ledger_client/cml_client/tests/test_helpers.rs +++ b/src/trireme_ledger_client/cml_client/tests/test_helpers.rs @@ -1,19 +1,35 @@ -use crate::scripts::plutus_validator::PlutusValidator; -use crate::scripts::raw_script::PlutusScriptFile; -use crate::transaction::TransactionVersion; -use crate::trireme_ledger_client::Network; use crate::{ - output::{Output, UnbuiltOutput}, - scripts::Validator, + output::{ + Output, + UnbuiltOutput, + }, + scripts::{ + plutus_validator::PlutusValidator, + raw_script::PlutusScriptFile, + Validator, + }, + transaction::TransactionVersion, + trireme_ledger_client::Network, values::Values, - Address, PolicyId, UnbuiltTransaction, + Address, + PolicyId, + UnbuiltTransaction, }; use cardano_multiplatform_lib::{ - address::Address as CMLAddress, - address::{EnterpriseAddress, StakeCredential}, - plutus::{PlutusScript, PlutusV1Script}, + address::{ + Address as CMLAddress, + EnterpriseAddress, + StakeCredential, + }, + plutus::{ + PlutusScript, + PlutusV1Script, + }, +}; +use std::{ + fs::File, + io::Read, }; -use std::{fs::File, io::Read}; pub fn transfer_tx(recipient: Address, amount: u64) -> UnbuiltTransaction<(), ()> { let mut values = Values::default(); @@ -77,7 +93,9 @@ pub fn read_script_from_file(file_path: &str) -> PlutusScriptFile { serde_json::from_str(&data).unwrap() } -pub fn claim_always_succeeds_datum_tx(script_input: &Output<()>) -> UnbuiltTransaction<(), ()> { +pub fn claim_always_succeeds_datum_tx( + script_input: &Output<()>, +) -> UnbuiltTransaction<(), ()> { let script = PlutusValidator::new_v1(always_succeeds_hex()).unwrap(); let script = Box::new(script) as Box>; UnbuiltTransaction { @@ -90,7 +108,10 @@ pub fn claim_always_succeeds_datum_tx(script_input: &Output<()>) -> UnbuiltTrans } } -pub fn output_from_tx<'a, D>(tx_id: &'a str, outputs: &'a Vec>) -> Option<&'a Output> { +pub fn output_from_tx<'a, D>( + tx_id: &'a str, + outputs: &'a Vec>, +) -> Option<&'a Output> { for output in outputs { let id = output.id(); let tx_hash = id.tx_hash(); diff --git a/src/trireme_ledger_client/raw_secret_phrase.rs b/src/trireme_ledger_client/raw_secret_phrase.rs index 116a861..229a416 100644 --- a/src/trireme_ledger_client/raw_secret_phrase.rs +++ b/src/trireme_ledger_client/raw_secret_phrase.rs @@ -1,14 +1,32 @@ -use crate::trireme_ledger_client::cml_client::error::{CMLLCError, Result as CMLLCResult}; -use crate::trireme_ledger_client::cml_client::Keys; -use crate::trireme_ledger_client::secret_phrase::{ - private_key_to_base_address, secret_phrase_to_account_key, +use crate::trireme_ledger_client::{ + cml_client::{ + error::{ + CMLLCError, + Result as CMLLCResult, + }, + Keys, + }, + secret_phrase::{ + private_key_to_base_address, + secret_phrase_to_account_key, + }, }; use async_trait::async_trait; -use cardano_multiplatform_lib::address::BaseAddress; -use cardano_multiplatform_lib::crypto::{Bip32PrivateKey, PrivateKey}; -use serde::{Deserialize, Serialize}; -use std::path::PathBuf; -use std::str::FromStr; +use cardano_multiplatform_lib::{ + address::BaseAddress, + crypto::{ + Bip32PrivateKey, + PrivateKey, + }, +}; +use serde::{ + Deserialize, + Serialize, +}; +use std::{ + path::PathBuf, + str::FromStr, +}; use thiserror::Error; use tokio::fs; diff --git a/src/trireme_ledger_client/secret_phrase.rs b/src/trireme_ledger_client/secret_phrase.rs index 920befb..9b66e9b 100644 --- a/src/trireme_ledger_client/secret_phrase.rs +++ b/src/trireme_ledger_client/secret_phrase.rs @@ -1,10 +1,19 @@ use crate::trireme_ledger_client::{ - cml_client::error::{CMLLCError, Result as CMLLCResult}, + cml_client::error::{ + CMLLCError, + Result as CMLLCResult, + }, raw_secret_phrase::RawSecretPhraseKeysError, }; -use bip39::{Language, Mnemonic}; +use bip39::{ + Language, + Mnemonic, +}; use cardano_multiplatform_lib::{ - address::{BaseAddress, StakeCredential}, + address::{ + BaseAddress, + StakeCredential, + }, crypto::Bip32PrivateKey, }; @@ -25,7 +34,10 @@ pub fn secret_phrase_to_account_key(phrase: &str) -> CMLLCResult BaseAddress { +pub fn private_key_to_base_address( + account_key: &Bip32PrivateKey, + network: u8, +) -> BaseAddress { let pub_key = account_key.derive(0).derive(0).to_public(); let stake_key = account_key.derive(2).derive(0).to_public(); let pub_key_creds = StakeCredential::from_keyhash(&pub_key.to_raw_key().hash()); diff --git a/src/trireme_ledger_client/terminal_password_phrase.rs b/src/trireme_ledger_client/terminal_password_phrase.rs index ce2195f..71cb152 100644 --- a/src/trireme_ledger_client/terminal_password_phrase.rs +++ b/src/trireme_ledger_client/terminal_password_phrase.rs @@ -1,20 +1,44 @@ -use crate::trireme_ledger_client::secret_phrase::{ - private_key_to_base_address, secret_phrase_to_account_key, +use crate::{ + error::{ + Error, + Result, + }, + trireme_ledger_client::{ + cml_client::Keys, + secret_phrase::{ + private_key_to_base_address, + secret_phrase_to_account_key, + }, + }, }; -use crate::{error::Error, error::Result, trireme_ledger_client::cml_client::Keys}; use async_trait::async_trait; -use cardano_multiplatform_lib::{address::BaseAddress, crypto::PrivateKey}; +use cardano_multiplatform_lib::{ + address::BaseAddress, + crypto::PrivateKey, +}; use chacha20::{ - cipher::{KeyIvInit, StreamCipher}, + cipher::{ + KeyIvInit, + StreamCipher, + }, ChaCha20, }; use dialoguer::Password as InputPassword; -use secrecy::{ExposeSecret, Secret}; -use serde::{Deserialize, Serialize}; +use secrecy::{ + ExposeSecret, + Secret, +}; +use serde::{ + Deserialize, + Serialize, +}; use std::path::PathBuf; use tokio::fs; -use crate::trireme_ledger_client::cml_client::error::{CMLLCError, Result as CMLResult}; +use crate::trireme_ledger_client::cml_client::error::{ + CMLLCError, + Result as CMLResult, +}; /// Type for representing a password protected phrase pub struct PasswordProtectedPhraseKeys { diff --git a/src/values.rs b/src/values.rs index f72f73f..40bf1dd 100644 --- a/src/values.rs +++ b/src/values.rs @@ -1,11 +1,19 @@ use crate::{ - error::{Error, Result}, + error::{ + Error, + Result, + }, output::Output, PolicyId, }; -use serde::{Deserialize, Serialize}; -use std::cmp::Ordering; -use std::collections::HashMap; +use serde::{ + Deserialize, + Serialize, +}; +use std::{ + cmp::Ordering, + collections::HashMap, +}; /// Domain representation of value on the Cardano blockchain #[serde_with::serde_as] @@ -106,7 +114,11 @@ impl Values { } } -pub(crate) fn add_to_map(h_map: &mut HashMap, policy: PolicyId, amount: u64) { +pub(crate) fn add_to_map( + h_map: &mut HashMap, + policy: PolicyId, + amount: u64, +) { let mut new_total = amount; if let Some(total) = h_map.get(&policy) { new_total += total; diff --git a/tests/always_mints_contract.rs b/tests/always_mints_contract.rs index c4eee55..5045e3a 100644 --- a/tests/always_mints_contract.rs +++ b/tests/always_mints_contract.rs @@ -1,17 +1,31 @@ use async_trait::async_trait; -use naumachia::ledger_client::test_ledger_client::{ - in_memory_storage::InMemoryStorage, TestLedgerClient, TestLedgerClientBuilder, -}; -use naumachia::logic::error::{SCLogicError, SCLogicResult}; -use naumachia::policy_id::PolicyId; -use naumachia::scripts::context::TxContext; -use naumachia::scripts::ExecutionCost; use naumachia::{ - ledger_client::LedgerClient, - logic::SCLogic, - scripts::{MintingPolicy, ScriptResult}, - smart_contract::SmartContract, - smart_contract::SmartContractTrait, + ledger_client::{ + test_ledger_client::{ + in_memory_storage::InMemoryStorage, + TestLedgerClient, + TestLedgerClientBuilder, + }, + LedgerClient, + }, + logic::{ + error::{ + SCLogicError, + SCLogicResult, + }, + SCLogic, + }, + policy_id::PolicyId, + scripts::{ + context::TxContext, + ExecutionCost, + MintingPolicy, + ScriptResult, + }, + smart_contract::{ + SmartContract, + SmartContractTrait, + }, transaction::TxActions, }; use pallas_addresses::Address; @@ -92,11 +106,10 @@ async fn can_mint_from_always_true_minting_policy() { // Check my balance for minted tokens let expected = amount; - let actual = > as LedgerClient<(), ()>>::balance_at_address( - contract.ledger_client(), - &me, - &policy, - ) + let actual = > as LedgerClient< + (), + (), + >>::balance_at_address(contract.ledger_client(), &me, &policy) .await .unwrap(); assert_eq!(expected, actual) diff --git a/tests/transfer.rs b/tests/transfer.rs index a48ee57..89e1d45 100644 --- a/tests/transfer.rs +++ b/tests/transfer.rs @@ -1,11 +1,18 @@ use async_trait::async_trait; -use naumachia::logic::error::SCLogicResult; use naumachia::{ - ledger_client::test_ledger_client::TestLedgerClientBuilder, - ledger_client::LedgerClient, - logic::SCLogic, + ledger_client::{ + test_ledger_client::TestLedgerClientBuilder, + LedgerClient, + }, + logic::{ + error::SCLogicResult, + SCLogic, + }, policy_id::PolicyId, - smart_contract::{SmartContract, SmartContractTrait}, + smart_contract::{ + SmartContract, + SmartContractTrait, + }, transaction::TxActions, }; use pallas_addresses::Address; @@ -32,7 +39,8 @@ impl SCLogic for TransferADASmartContract { ) -> SCLogicResult> { match endpoint { Endpoint::Transfer { amount, recipient } => { - let u_tx = TxActions::v1().with_transfer(amount, recipient, PolicyId::Lovelace); + let u_tx = + TxActions::v1().with_transfer(amount, recipient, PolicyId::Lovelace); Ok(u_tx) } } diff --git a/trireme/src/balance.rs b/trireme/src/balance.rs index 15086c8..d031536 100644 --- a/trireme/src/balance.rs +++ b/trireme/src/balance.rs @@ -1,9 +1,16 @@ -use crate::{TriremeLogic, TriremeLookups, TriremeResponses}; +use crate::{ + TriremeLogic, + TriremeLookups, + TriremeResponses, +}; use anyhow::Result; use naumachia::{ error::Error, policy_id::PolicyId, - smart_contract::{SmartContract, SmartContractTrait}, + smart_contract::{ + SmartContract, + SmartContractTrait, + }, trireme_ledger_client::get_trireme_ledger_client_from_file, }; diff --git a/trireme/src/environment.rs b/trireme/src/environment.rs index 0263056..428e527 100644 --- a/trireme/src/environment.rs +++ b/trireme/src/environment.rs @@ -1,27 +1,46 @@ use crate::Error; use anyhow::Result; -use dialoguer::{Input, Password as InputPassword, Select}; -use hex; -use naumachia::scripts::context::pub_key_hash_from_address_if_available; -use naumachia::trireme_ledger_client::get_current_client_config_from_file; -use naumachia::trireme_ledger_client::terminal_password_phrase::{ - encrypt_phrase, normalize_password, +use dialoguer::{ + Input, + Password as InputPassword, + Select, }; +use hex; use naumachia::{ ledger_client::{ - test_ledger_client::local_persisted_storage::LocalPersistedStorage, LedgerClient, + test_ledger_client::local_persisted_storage::LocalPersistedStorage, + LedgerClient, }, + scripts::context::pub_key_hash_from_address_if_available, trireme_ledger_client::{ - cml_client::blockfrost_ledger::BlockfrostApiKey, get_trireme_config_from_file, - get_trireme_ledger_client_from_file, path_to_client_config_file, - path_to_trireme_config_dir, path_to_trireme_config_file, read_toml_struct_from_file, - write_toml_struct_to_file, ClientConfig, ClientVariant, KeySource, LedgerSource, Network, - TriremeConfig, TriremeLedgerClient, + cml_client::blockfrost_ledger::BlockfrostApiKey, + get_current_client_config_from_file, + get_trireme_config_from_file, + get_trireme_ledger_client_from_file, + path_to_client_config_file, + path_to_trireme_config_dir, + path_to_trireme_config_file, + read_toml_struct_from_file, + terminal_password_phrase::{ + encrypt_phrase, + normalize_password, + }, + write_toml_struct_to_file, + ClientConfig, + ClientVariant, + KeySource, + LedgerSource, + Network, + TriremeConfig, + TriremeLedgerClient, }, Address, }; use rand::Rng; -use std::{path::PathBuf, str::FromStr}; +use std::{ + path::PathBuf, + str::FromStr, +}; use tokio::fs; #[derive(Clone, Copy)] @@ -332,7 +351,8 @@ pub async fn active_signer_impl() -> Result<()> { } pub async fn get_address_impl() -> Result<()> { - let ledger_client: TriremeLedgerClient<(), ()> = get_trireme_ledger_client_from_file().await?; + let ledger_client: TriremeLedgerClient<(), ()> = + get_trireme_ledger_client_from_file().await?; let address = ledger_client.signer_base_address().await?; let address_string = address.to_bech32()?; println!("Address: {address_string}"); @@ -340,11 +360,12 @@ pub async fn get_address_impl() -> Result<()> { } pub async fn get_pubkey_hash_impl() -> Result<()> { - let ledger_client: TriremeLedgerClient<(), ()> = get_trireme_ledger_client_from_file().await?; + let ledger_client: TriremeLedgerClient<(), ()> = + get_trireme_ledger_client_from_file().await?; let address = ledger_client.signer_base_address().await?; - let pubkey_hash = pub_key_hash_from_address_if_available(&address).ok_or(Error::CLI( - "Could not derive Pubkey Hash from Address".to_string(), - ))?; + let pubkey_hash = pub_key_hash_from_address_if_available(&address).ok_or( + Error::CLI("Could not derive Pubkey Hash from Address".to_string()), + )?; let pubkey_hash_string = hex::encode(pubkey_hash.bytes()); println!("Pubkey Hash: {pubkey_hash_string}"); Ok(()) @@ -408,14 +429,16 @@ pub async fn current_time_impl() -> Result<()> { } pub async fn last_block_time_impl() -> Result<()> { - let ledger_client: TriremeLedgerClient<(), ()> = get_trireme_ledger_client_from_file().await?; + let ledger_client: TriremeLedgerClient<(), ()> = + get_trireme_ledger_client_from_file().await?; let last_block_time = ledger_client.last_block_time_secs().await?; println!("Last block time: {}", last_block_time); Ok(()) } pub async fn advance_blocks(count: i64) -> Result<()> { - let ledger_client: TriremeLedgerClient<(), ()> = get_trireme_ledger_client_from_file().await?; + let ledger_client: TriremeLedgerClient<(), ()> = + get_trireme_ledger_client_from_file().await?; ledger_client.advance_blocks(count).await?; println!("Advancing blocks by: {}", count); let block_time = ledger_client.current_time().await?; diff --git a/trireme/src/logic.rs b/trireme/src/logic.rs index 3300728..959ea40 100644 --- a/trireme/src/logic.rs +++ b/trireme/src/logic.rs @@ -1,7 +1,15 @@ use async_trait::async_trait; -use naumachia::logic::error::{as_lookup_err, SCLogicResult}; use naumachia::{ - ledger_client::LedgerClient, logic::SCLogic, policy_id::PolicyId, transaction::TxActions, + ledger_client::LedgerClient, + logic::{ + error::{ + as_lookup_err, + SCLogicResult, + }, + SCLogic, + }, + policy_id::PolicyId, + transaction::TxActions, values::Values, }; diff --git a/trireme/src/main.rs b/trireme/src/main.rs index 2ddd49e..4a690a0 100644 --- a/trireme/src/main.rs +++ b/trireme/src/main.rs @@ -1,11 +1,26 @@ -use crate::environment::{ - active_signer_impl, advance_blocks, current_time_impl, get_address_impl, get_pubkey_hash_impl, - last_block_time_impl, switch_signer_impl, -}; use crate::{ - balance::{ada_balance_impl, balance_impl}, - environment::{env_impl, new_env_impl, remove_env_impl, switch_env_impl}, - logic::{TriremeLogic, TriremeLookups, TriremeResponses}, + balance::{ + ada_balance_impl, + balance_impl, + }, + environment::{ + active_signer_impl, + advance_blocks, + current_time_impl, + env_impl, + get_address_impl, + get_pubkey_hash_impl, + last_block_time_impl, + new_env_impl, + remove_env_impl, + switch_env_impl, + switch_signer_impl, + }, + logic::{ + TriremeLogic, + TriremeLookups, + TriremeResponses, + }, }; use anyhow::Result; use clap::Parser;