Skip to content

Commit

Permalink
Merge pull request #74 from logical-mechanism/clippy-fix
Browse files Browse the repository at this point in the history
cargo clippy fixes
  • Loading branch information
logicalmechanism authored Jan 9, 2025
2 parents 6c40be9 + 37b3f20 commit 7ff9f4f
Show file tree
Hide file tree
Showing 37 changed files with 956 additions and 765 deletions.
3 changes: 3 additions & 0 deletions RELEASE.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ Publish to crates.io with this command.

```bash
cd seedelf-cli
cargo test
cargo clippy
cargo fmt
cargo package
cargo publish --dry-run
cd ..
Expand Down
50 changes: 30 additions & 20 deletions seedelf-cli/src/assets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ impl Asset {
.expect("Incorrect Length"),
),
token_name: hex::decode(token_name).unwrap(),
amount: amount,
amount,
}
}

Expand All @@ -45,12 +45,12 @@ impl Asset {
/// * `Err(String)` - If the `policy_id` or `token_name` do not match.
pub fn add(&self, other: &Asset) -> Result<Self, String> {
if self.policy_id != other.policy_id || self.token_name != other.token_name {
return Err(format!(
"Assets must have the same policy_id and token_name to be subtracted"
));
return Err(
"Assets must have the same policy_id and token_name to be subtracted".to_string(),
);
}
Ok(Self {
policy_id: self.policy_id.clone(),
policy_id: self.policy_id,
token_name: self.token_name.clone(),
amount: self.amount + other.amount,
})
Expand All @@ -68,12 +68,12 @@ impl Asset {
/// * `Err(String)` - If the `policy_id` or `token_name` do not match.
pub fn sub(&self, other: &Asset) -> Result<Self, String> {
if self.policy_id != other.policy_id || self.token_name != other.token_name {
return Err(format!(
"Assets must have the same policy_id and token_name to be subtracted"
));
return Err(
"Assets must have the same policy_id and token_name to be subtracted".to_string(),
);
}
Ok(Self {
policy_id: self.policy_id.clone(),
policy_id: self.policy_id,
token_name: self.token_name.clone(),
amount: self.amount - other.amount,
})
Expand Down Expand Up @@ -105,6 +105,12 @@ pub struct Assets {
pub items: Vec<Asset>,
}

impl Default for Assets {
fn default() -> Self {
Self::new()
}
}

impl Assets {
/// Creates a new, empty `Assets` instance.
pub fn new() -> Self {
Expand Down Expand Up @@ -158,8 +164,8 @@ impl Assets {
let filtered_items: Vec<Asset> = self
.items
.iter()
.cloned()
.filter(|asset| asset.amount > 0)
.cloned()
.collect();
Self {
items: filtered_items,
Expand All @@ -181,7 +187,7 @@ impl Assets {
}
// if we didnt find it then false
if !found {
return false
return false;
}
}
// we found all the other tokens
Expand All @@ -191,15 +197,17 @@ impl Assets {
/// Checks if any asset in `other` exists in this collection.
pub fn any(&self, other: Assets) -> bool {
if other.items.is_empty() {
return true
return true;
}
// search all other tokens and make sure they exist in these assets
for other_token in other.items {
// lets check all the assets in these assets
for token in self.items.clone() {
// if its greater than or equal then break
if token.policy_id == other_token.policy_id && token.token_name == other_token.token_name {
return true
if token.policy_id == other_token.policy_id
&& token.token_name == other_token.token_name
{
return true;
}
}
}
Expand All @@ -210,22 +218,22 @@ impl Assets {
/// Merges two collections of assets, combining amounts of matching assets.
pub fn merge(&self, other: Assets) -> Self {
let mut merged: Assets = self.clone(); // Clone the current `Assets` as a starting point

for other_asset in other.items {
merged = merged.add(other_asset); // Use `add` to handle merging logic
}

merged
}

/// Separates two collections of assets, subtracting amounts of matching assets.
pub fn separate(&self, other: Assets) -> Self {
let mut separated: Assets = self.clone(); // Clone the current `Assets` as a starting point

for other_asset in other.items {
separated = separated.sub(other_asset); // Use `add` to handle merging logic
}

separated
}

Expand All @@ -240,7 +248,9 @@ impl Assets {
pub fn split(&self, k: usize) -> Vec<Self> {
self.items
.chunks(k) // Divide the `items` into slices of at most `k` elements
.map(|chunk| Assets { items: chunk.to_vec() }) // Convert each slice into an `Assets` struct
.map(|chunk| Assets {
items: chunk.to_vec(),
}) // Convert each slice into an `Assets` struct
.collect()
}
}
Expand All @@ -260,4 +270,4 @@ pub fn string_to_u64(input: String) -> Result<u64, String> {
Ok(value) => Ok(value),
Err(e) => Err(format!("Failed to convert: {}", e)),
}
}
}
23 changes: 17 additions & 6 deletions seedelf-cli/src/commands/balance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,32 @@ pub async fn run(network_flag: bool) -> Result<(), Error> {
display::block_number_and_time(network_flag).await;

println!("{}", "\nSeedelf Wallet Information:".bright_white());

let scalar: Scalar = setup::load_wallet();

display::all_seedelfs(scalar, network_flag).await;

let all_utxos: Vec<UtxoResponse> = utxos::collect_all_wallet_utxos(scalar, network_flag).await;
let (total_lovelace, tokens) = utxos::assets_of(all_utxos.clone());

println!("\nWallet Has {} UTxOs", all_utxos.len().to_string().bright_yellow());
println!("\nBalance: {} ₳", format!("{:.6}", total_lovelace as f64 / 1_000_000.0).bright_yellow());
println!(
"\nWallet Has {} UTxOs",
all_utxos.len().to_string().bright_yellow()
);
println!(
"\nBalance: {} ₳",
format!("{:.6}", total_lovelace as f64 / 1_000_000.0).bright_yellow()
);

if tokens.items.len() > 0 {
if !tokens.items.is_empty() {
println!("{}", "\nTokens:\n".bright_magenta());
for asset in tokens.items.clone() {
println!("{} {}.{}", asset.amount.to_string().white(), hex::encode(asset.policy_id.as_ref()).white(), hex::encode(asset.token_name).white());
println!(
"{} {}.{}",
asset.amount.to_string().white(),
hex::encode(asset.policy_id.as_ref()).white(),
hex::encode(asset.token_name).white()
);
}
}

Expand Down
81 changes: 56 additions & 25 deletions seedelf-cli/src/commands/create.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use seedelf_cli::setup;
use blstrs::Scalar;
use clap::Args;
use colored::Colorize;
Expand All @@ -11,22 +10,33 @@ use pallas_wallet::PrivateKey;
use rand_core::OsRng;
use seedelf_cli::address;
use seedelf_cli::assets::Assets;
use seedelf_cli::constants::{plutus_v3_cost_model, SEEDELF_POLICY_ID, SEEDELF_CONTRACT_SIZE};
use seedelf_cli::constants::{plutus_v3_cost_model, SEEDELF_CONTRACT_SIZE, SEEDELF_POLICY_ID};
use seedelf_cli::data_structures;
use seedelf_cli::display::preprod_text;
use seedelf_cli::koios::{address_utxos, evaluate_transaction, UtxoResponse};
use seedelf_cli::register::Register;
use seedelf_cli::setup;
use seedelf_cli::transaction;
use seedelf_cli::utxos;
use seedelf_cli::web_server;

/// Struct to hold command-specific arguments
#[derive(Args)]
pub struct LabelArgs {
#[arg(short = 'a', long, help = "The address paying for the seedelf.", display_order = 1)]
#[arg(
short = 'a',
long,
help = "The address paying for the seedelf.",
display_order = 1
)]
address: String,

#[arg(short = 'l', long, help = "The seedelf label / personal tag.", display_order = 2)]
#[arg(
short = 'l',
long,
help = "The seedelf label / personal tag.",
display_order = 2
)]
label: Option<String>,
}

Expand Down Expand Up @@ -55,7 +65,7 @@ pub async fn run(args: LabelArgs, network_flag: bool) -> Result<(), String> {
let mut found_collateral: bool = false;

// if the label is none then just use the empty string
let label: String = args.label.unwrap_or(String::new());
let label: String = args.label.unwrap_or_default();

// utxos
let mut all_utxos: Vec<UtxoResponse> = Vec::new();
Expand Down Expand Up @@ -126,18 +136,24 @@ pub async fn run(args: LabelArgs, network_flag: bool) -> Result<(), String> {
// lets build the seelfelf token
let token_name: Vec<u8> =
transaction::seedelf_token_name(label.clone(), draft_tx.inputs.as_ref());
println!("{} {}", "\nCreating Seedelf:".bright_blue(), hex::encode(token_name.clone()).bright_white());
println!(
"{} {}",
"\nCreating Seedelf:".bright_blue(),
hex::encode(token_name.clone()).bright_white()
);

let min_utxo: u64 = transaction::seedelf_minimum_lovelace();
println!("{} {}", "\nMinimum Required Lovelace:".bright_blue(), min_utxo.to_string().bright_white());

let mut change_output: Output = Output::new(
addr.clone(),
total_lovelace - min_utxo - tmp_fee,
println!(
"{} {}",
"\nMinimum Required Lovelace:".bright_blue(),
min_utxo.to_string().bright_white()
);

let mut change_output: Output = Output::new(addr.clone(), total_lovelace - min_utxo - tmp_fee);
for asset in tokens.items.clone() {
change_output = change_output.add_asset(asset.policy_id, asset.token_name, asset.amount)
.unwrap();
change_output = change_output
.add_asset(asset.policy_id, asset.token_name, asset.amount)
.unwrap();
}

// build out the rest of the draft tx with the tmp fee
Expand Down Expand Up @@ -189,7 +205,7 @@ pub async fn run(args: LabelArgs, network_flag: bool) -> Result<(), String> {
pallas_txbuilder::ScriptKind::PlutusV3,
plutus_v3_cost_model(),
);

// clone the tx but remove the tmp fee, collateral, change output, and fake redeemer
let mut raw_tx: StagingTransaction = draft_tx
.clone()
Expand Down Expand Up @@ -230,7 +246,7 @@ pub async fn run(args: LabelArgs, network_flag: bool) -> Result<(), String> {
};

// we can fake the signature here to get the correct tx size
let fake_signer_secret_key: SecretKey = SecretKey::new(&mut OsRng);
let fake_signer_secret_key: SecretKey = SecretKey::new(OsRng);
let fake_signer_private_key: PrivateKey = PrivateKey::from(fake_signer_secret_key);

// we need the script size here
Expand All @@ -243,14 +259,26 @@ pub async fn run(args: LabelArgs, network_flag: bool) -> Result<(), String> {
.try_into()
.unwrap();
let tx_fee: u64 = fees::compute_linear_fee_policy(tx_size, &(fees::PolicyParams::default()));
println!("{} {}", "\nTx Size Fee:".bright_blue(), tx_fee.to_string().bright_white());
println!(
"{} {}",
"\nTx Size Fee:".bright_blue(),
tx_fee.to_string().bright_white()
);

// This probably should be a function
let compute_fee: u64 = transaction::computation_fee(mem_units, cpu_units);
println!("{} {}", "Compute Fee:".bright_blue(), compute_fee.to_string().bright_white());
println!(
"{} {}",
"Compute Fee:".bright_blue(),
compute_fee.to_string().bright_white()
);

let script_reference_fee: u64 = SEEDELF_CONTRACT_SIZE * 15;
println!("{} {}", "Script Reference Fee:".bright_blue(), script_reference_fee.to_string().bright_white());
println!(
"{} {}",
"Script Reference Fee:".bright_blue(),
script_reference_fee.to_string().bright_white()
);

// total fee is the sum
let mut total_fee: u64 = tx_fee + compute_fee + script_reference_fee;
Expand All @@ -260,15 +288,18 @@ pub async fn run(args: LabelArgs, network_flag: bool) -> Result<(), String> {
} else {
total_fee
};
println!("{} {}", "Total Fee:".bright_blue(), total_fee.to_string().bright_white());

let mut change_output: Output = Output::new(
addr.clone(),
total_lovelace - min_utxo - total_fee,
println!(
"{} {}",
"Total Fee:".bright_blue(),
total_fee.to_string().bright_white()
);

let mut change_output: Output =
Output::new(addr.clone(), total_lovelace - min_utxo - total_fee);
for asset in tokens.items.clone() {
change_output = change_output.add_asset(asset.policy_id, asset.token_name, asset.amount)
.unwrap();
change_output = change_output
.add_asset(asset.policy_id, asset.token_name, asset.amount)
.unwrap();
}

// build of the rest of the raw tx with the correct fee
Expand Down
Loading

0 comments on commit 7ff9f4f

Please sign in to comment.