Skip to content

Commit

Permalink
Clean up and refactor the code (#9)
Browse files Browse the repository at this point in the history
* Clean up and refactor the code

* Further cleaning

* Fix deprecated cron tests

* Switch to classic math
  • Loading branch information
Aursen authored Jan 16, 2024
1 parent 0debfbb commit 045ec97
Show file tree
Hide file tree
Showing 132 changed files with 997 additions and 2,605 deletions.
533 changes: 92 additions & 441 deletions Cargo.lock

Large diffs are not rendered by default.

7 changes: 7 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,10 @@ members = ["cli", "cron", "plugin", "programs/*", "relayer", "sdk", "utils"]

[profile.release]
overflow-checks = true
lto = "fat"
codegen-units = 1

[profile.release.build-override]
opt-level = 3
incremental = false
codegen-units = 1
4 changes: 0 additions & 4 deletions cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,10 @@ indicatif = "0.16"
reqwest = "0.11.14"
serde = { version = "1.0.136", features = ["derive"] }
serde_json = "1.0.79"
serde_yaml = "0.9.4"
solana-account-decoder = "=1.17.14"
solana-client = "=1.17.14"
solana-clap-utils = "=1.17.14"
solana-cli-config = "=1.17.14"
solana-sdk = "=1.17.14"
spl-associated-token-account = "1.1.1"
spl-memo = "3.0.1"
spl-token = "~3.5.0"
tar = "0.4"
thiserror = "1.0.30"
Expand Down
2 changes: 1 addition & 1 deletion cli/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::process::Command;

fn main() {
let output = Command::new("git")
.args(&["rev-parse", "HEAD"])
.args(["rev-parse", "HEAD"])
.output()
.expect("unable to get git commit hash");
let commit_hash = String::from_utf8(output.stdout).unwrap();
Expand Down
6 changes: 1 addition & 5 deletions cli/src/client.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use anchor_lang::{prelude::Clock, AccountDeserialize};
use clockwork_utils::ProgramLogsDeserializable;
use solana_client::{
client_error, rpc_client::RpcClient,
rpc_response::RpcSimulateTransactionResult,
client_error, rpc_client::RpcClient, rpc_response::RpcSimulateTransactionResult,
};
use solana_sdk::{
commitment_config::CommitmentConfig,
Expand All @@ -21,7 +20,6 @@ use std::{
};
use thiserror::Error;


#[derive(Debug, Error)]
pub enum ClientError {
#[error(transparent)]
Expand Down Expand Up @@ -135,7 +133,6 @@ impl Client {
}
}


impl Debug for Client {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "RPC client payer {}", self.payer_pubkey())
Expand All @@ -155,4 +152,3 @@ impl DerefMut for Client {
&mut self.client
}
}

19 changes: 6 additions & 13 deletions cli/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,7 @@ use {
crate::deps::ToTagVersion,
clap::crate_version,
solana_sdk::commitment_config::CommitmentConfig,
std::{
env,
fs,
path::PathBuf,
time::Duration,
},
std::{env, fs, path::PathBuf, time::Duration},
};

pub const DEFAULT_RPC_TIMEOUT_SECONDS: Duration = Duration::from_secs(30);
Expand Down Expand Up @@ -82,7 +77,7 @@ impl CliConfig {
}

pub fn active_runtime(&self, filename: &str) -> String {
if self.dev == true {
if self.dev {
if filename.contains("solana") {
self.active_runtime_dir().join(filename).to_string()
} else if filename.contains("program") {
Expand All @@ -103,9 +98,7 @@ impl CliConfig {
path.extend(["test-ledger", "validator-keypair.json"]);
path
})
.expect(&format!(
"Unable to find location of validator-keypair.json"
))
.unwrap_or_else(|_| panic!("Unable to find location of validator-keypair.json"))
.to_string()
}

Expand All @@ -114,7 +107,7 @@ impl CliConfig {
}

pub fn geyser_lib(&self) -> String {
if self.dev == true && env::consts::OS.to_lowercase().contains("mac") {
if self.dev && env::consts::OS.to_lowercase().contains("mac") {
self.active_runtime("libclockwork_plugin.dylib")
} else {
// in the release process, we always rename dylib to so anyway
Expand Down Expand Up @@ -146,8 +139,8 @@ impl CliConfig {
String::from_utf8(output.stdout)
.expect("Unable to get output from cargo -vV")
.split('\n')
.find(|line| line.trim_start().to_lowercase().starts_with(&host_prefix))
.map(|line| line.trim_start_matches(&host_prefix).trim())
.find(|line| line.trim_start().to_lowercase().starts_with(host_prefix))
.map(|line| line.trim_start_matches(host_prefix).trim())
.expect("Unable to detect target 'host' from cargo -vV")
.to_owned()
}
Expand Down
42 changes: 13 additions & 29 deletions cli/src/deps.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,15 @@
use {
super::*,
anyhow::{
Context,
Result,
},
anyhow::{Context, Result},
bzip2::read::BzDecoder,
clap::crate_version,
indicatif::{
ProgressBar,
ProgressStyle,
},
reqwest::{
blocking::get,
Url,
},
indicatif::{ProgressBar, ProgressStyle},
reqwest::{blocking::get, Url},
std::{
ffi::OsStr,
fs::{
self,
copy,
File,
},
io::{self,},
path::{
Path,
PathBuf,
},
fs::{self, copy, File},
io::{self},
path::{Path, PathBuf},
},
tar::Archive,
};
Expand All @@ -44,15 +28,15 @@ pub fn download_deps(
let active_runtime = &runtime_dir.join(&clockwork_tag);

download_and_extract(
&active_runtime,
active_runtime,
&solana_archive.unwrap_or(CliConfig::solana_release_url(&solana_tag)),
&active_runtime.join(CliConfig::solana_release_archive()),
config::SOLANA_DEPS,
force_init,
)?;
if !dev {
download_and_extract(
&active_runtime,
active_runtime,
&clockwork_archive.unwrap_or(CliConfig::clockwork_release_url(&clockwork_tag)),
&active_runtime.join(CliConfig::clockwork_release_archive()),
config::CLOCKWORK_DEPS,
Expand Down Expand Up @@ -83,8 +67,8 @@ pub fn download_and_extract(
// create runtime dir if necessary
fs::create_dir_all(runtime_dir)
.context(format!("Unable to create dirs for {:#?}", runtime_dir))?;
download_file(src_url, &dest_path)?;
extract_archive(&dest_path, runtime_dir, files_to_extract)?;
download_file(src_url, dest_path)?;
extract_archive(dest_path, runtime_dir, files_to_extract)?;
println!();
Ok(())
}
Expand All @@ -108,7 +92,7 @@ fn download_file(url: &str, dest: &Path) -> Result<()> {
let mut source = pb.wrap_read(response);

let mut dest =
File::create(&dest).context(format!("Failed to create file {:#?}", dest))?;
File::create(dest).context(format!("Failed to create file {dest:#?}"))?;
io::copy(&mut source, &mut dest)?;
pb.finish_with_message("Download complete.");
}
Expand All @@ -130,7 +114,7 @@ fn extract_archive(
files_to_extract: &[&str],
) -> Result<()> {
let file =
File::open(&archive_path).context(format!("Failed to open file {:#?}", archive_path))?;
File::open(archive_path).context(format!("Failed to open file {:#?}", archive_path))?;
let target_file_names: Vec<&OsStr> = files_to_extract.iter().map(OsStr::new).collect();
let mut archive = Archive::new(BzDecoder::new(file));

Expand Down Expand Up @@ -174,7 +158,7 @@ pub trait ToTagVersion {

impl ToTagVersion for String {
fn to_tag_version(&self) -> String {
if !self.starts_with("v") {
if !self.starts_with('v') {
format!("v{}", self)
} else {
self.to_owned()
Expand Down
6 changes: 4 additions & 2 deletions cli/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ pub enum CliError {
InvalidAddress,
#[error("Program file does not exist")]
InvalidProgramFile,
#[error("No default signer found in {0}, \
run `solana-keygen new`, or `solana config set —keypair <FILEPATH>`")]
#[error(
"No default signer found in {0}, \
run `solana-keygen new`, or `solana config set —keypair <FILEPATH>`"
)]
KeypairNotFound(String),
}
5 changes: 1 addition & 4 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@ mod print;
mod processor;

use {
crate::{
config::CliConfig,
print::print_style,
},
crate::{config::CliConfig, print::print_style},
cli::app,
errors::CliError,
processor::process,
Expand Down
21 changes: 9 additions & 12 deletions cli/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -308,18 +308,18 @@ fn parse_instruction_file(
}

fn parse_keypair_file(arg: &str, matches: &ArgMatches) -> Result<Keypair, CliError> {
Ok(read_keypair_file(parse_string(arg, matches)?)
.map_err(|_err| CliError::BadParameter(arg.into()))?)
read_keypair_file(parse_string(arg, matches)?)
.map_err(|_err| CliError::BadParameter(arg.into()))
}

fn parse_http_method(arg: &str, matches: &ArgMatches) -> Result<HttpMethod, CliError> {
Ok(HttpMethod::from_str(parse_string(arg, matches)?.as_str())
.map_err(|_err| CliError::BadParameter(arg.into()))?)
HttpMethod::from_str(parse_string(arg, matches)?.as_str())
.map_err(|_err| CliError::BadParameter(arg.into()))
}

fn parse_pubkey(arg: &str, matches: &ArgMatches) -> Result<Pubkey, CliError> {
Ok(Pubkey::from_str(parse_string(arg, matches)?.as_str())
.map_err(|_err| CliError::BadParameter(arg.into()))?)
Pubkey::from_str(parse_string(arg, matches)?.as_str())
.map_err(|_err| CliError::BadParameter(arg.into()))
}

fn parse_string(arg: &str, matches: &ArgMatches) -> Result<String, CliError> {
Expand All @@ -330,24 +330,21 @@ fn parse_string(arg: &str, matches: &ArgMatches) -> Result<String, CliError> {
}

pub fn _parse_i64(arg: &str, matches: &ArgMatches) -> Result<i64, CliError> {
Ok(parse_string(arg, matches)?
parse_string(arg, matches)?
.parse::<i64>()
.map_err(|_err| CliError::BadParameter(arg.into()))
.unwrap())
}

pub fn parse_u64(arg: &str, matches: &ArgMatches) -> Result<u64, CliError> {
Ok(parse_string(arg, matches)?
parse_string(arg, matches)?
.parse::<u64>()
.map_err(|_err| CliError::BadParameter(arg.into()))
.unwrap())
}

pub fn parse_usize(arg: &str, matches: &ArgMatches) -> Result<usize, CliError> {
Ok(parse_string(arg, matches)?
parse_string(arg, matches)?
.parse::<usize>()
.map_err(|_err| CliError::BadParameter(arg.into()))
.unwrap())
}

// Json parsers
Expand Down
13 changes: 2 additions & 11 deletions cli/src/print.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,8 @@
#![allow(dead_code)]

use {
std::{
fmt::Display,
io::Write,
},
termcolor::{
Color,
ColorChoice,
ColorSpec,
StandardStream,
WriteColor,
},
std::{fmt::Display, io::Write},
termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor},
};

#[macro_export]
Expand Down
9 changes: 4 additions & 5 deletions cli/src/processor/config.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use anchor_lang::{
solana_program::{
instruction::Instruction, pubkey::Pubkey,
},
InstructionData, ToAccountMetas
solana_program::{instruction::Instruction, pubkey::Pubkey},
InstructionData, ToAccountMetas,
};
use clockwork_network_program::state::{Config, ConfigSettings};

Expand Down Expand Up @@ -41,7 +39,8 @@ pub fn set(
accounts: clockwork_network_program::accounts::ConfigUpdate {
admin: client.payer_pubkey(),
config: Config::pubkey(),
}.to_account_metas(Some(false)),
}
.to_account_metas(Some(false)),
data: clockwork_network_program::instruction::ConfigUpdate { settings }.data(),
};
client.send_and_confirm(&[ix], &[client.payer()]).unwrap();
Expand Down
2 changes: 1 addition & 1 deletion cli/src/processor/crontab.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pub fn get(client: &Client, schedule: String) -> Result<(), CliError> {
let schedule = Schedule::from_str(schedule.as_str()).unwrap();

let mut i = 0;
for t in schedule.after(&DateTime::<Utc>::from_utc(
for t in schedule.after(&DateTime::<Utc>::from_naive_utc_and_offset(
NaiveDateTime::from_timestamp_opt(clock.unix_timestamp, 0).unwrap(),
Utc,
)) {
Expand Down
20 changes: 10 additions & 10 deletions cli/src/processor/delegation.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use anchor_lang::{
solana_program::{
instruction::Instruction, system_program, sysvar
},
InstructionData, AccountDeserialize, ToAccountMetas
solana_program::{instruction::Instruction, system_program},
AccountDeserialize, InstructionData, ToAccountMetas,
};
use clockwork_network_program::state::{Config, Delegation, Worker};
use spl_associated_token_account::get_associated_token_address;
Expand Down Expand Up @@ -37,11 +35,11 @@ pub fn create(client: &Client, worker_id: u64) -> Result<(), CliError> {
delegation: delegation_pubkey,
delegation_tokens: get_associated_token_address(&delegation_pubkey, &config.mint),
mint: config.mint,
rent: sysvar::rent::ID,
system_program: system_program::ID,
token_program: anchor_spl::token::ID,
worker: worker_pubkey,
}.to_account_metas(Some(false)),
}
.to_account_metas(Some(false)),
data: clockwork_network_program::instruction::DelegationCreate {}.data(),
};
client.send_and_confirm(&[ix], &[client.payer()]).unwrap();
Expand Down Expand Up @@ -76,8 +74,9 @@ pub fn deposit(
config: Config::pubkey(),
delegation: delegation_pubkey,
delegation_tokens: get_associated_token_address(&delegation_pubkey, &config.mint),
token_program: anchor_spl::token::ID,
}.to_account_metas(Some(false)),
token_program: anchor_spl::token::ID,
}
.to_account_metas(Some(false)),
data: clockwork_network_program::instruction::DelegationDeposit { amount }.data(),
};
client.send_and_confirm(&[ix], &[client.payer()]).unwrap();
Expand Down Expand Up @@ -112,8 +111,9 @@ pub fn withdraw(
config: Config::pubkey(),
delegation: delegation_pubkey,
delegation_tokens: get_associated_token_address(&delegation_pubkey, &config.mint),
token_program: anchor_spl::token::ID,
}.to_account_metas(Some(false)),
token_program: anchor_spl::token::ID,
}
.to_account_metas(Some(false)),
data: clockwork_network_program::instruction::DelegationWithdraw { amount }.data(),
};
client.send_and_confirm(&[ix], &[client.payer()]).unwrap();
Expand Down
Loading

0 comments on commit 045ec97

Please sign in to comment.