Skip to content

Commit

Permalink
Merge pull request #50 from Rjected/add-fmt-clippy-workflows
Browse files Browse the repository at this point in the history
feat(ci): add clippy, fmt, udeps workflows
  • Loading branch information
zeroXbrock authored Nov 20, 2024
2 parents a946937 + 59ef061 commit ddf1645
Show file tree
Hide file tree
Showing 18 changed files with 119 additions and 100 deletions.
52 changes: 52 additions & 0 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
name: Lint

on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]

env:
CARGO_TERM_COLOR: always

jobs:
clippy:
name: clippy
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@nightly
with:
components: clippy
- uses: Swatinem/rust-cache@v2
with:
cache-on-failure: true
- run: cargo clippy --workspace --lib --examples --tests --benches --all-features --locked
env:
RUSTFLAGS: -D warnings

fmt:
name: fmt
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@nightly
with:
components: rustfmt
- name: Run fmt
run: cargo fmt --all --check

udeps:
name: udeps
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@nightly
- uses: Swatinem/rust-cache@v2
with:
cache-on-failure: true
- uses: taiki-e/install-action@cargo-udeps
- run: cargo udeps --workspace --lib --examples --tests --benches --all-features --locked
2 changes: 1 addition & 1 deletion .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ jobs:

test:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4
with:
Expand Down
17 changes: 0 additions & 17 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ contender_sqlite = { path = "crates/sqlite_db/" }
contender_testfile = { path = "crates/testfile/" }
contender_bundle_provider = { path = "crates/bundle_provider/" }

eyre = "0.6.12"
# eyre = "0.6.12"
tokio = { version = "1.40.0" }
alloy = { version = "0.3.6" }
serde = "1.0.209"
Expand Down
14 changes: 8 additions & 6 deletions crates/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.as_ref()
.unwrap_or(&vec![])
.iter()
.map(|key| PrivateKeySigner::from_str(&key).expect("invalid private key"))
.map(|key| PrivateKeySigner::from_str(key).expect("invalid private key"))
.collect::<Vec<PrivateKeySigner>>();
let signers = get_signers_with_defaults(private_keys);
check_private_keys(
&testconfig.setup.to_owned().unwrap_or(vec![]),
&testconfig.setup.to_owned().unwrap_or_default(),
signers.as_slice(),
);
let broke_accounts = find_insufficient_balance_addrs(
Expand Down Expand Up @@ -103,7 +103,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
min_balance,
} => {
let testconfig = TestConfig::from_file(&testfile)?;
let rand_seed = seed.map(|s| RandSeed::from_str(&s)).unwrap_or_default();
let rand_seed = seed
.map(|s| RandSeed::seed_from_str(&s))
.unwrap_or_default();
let url = Url::parse(rpc_url.as_ref()).expect("Invalid RPC URL");
let rpc_client = ProviderBuilder::new()
.network::<AnyNetwork>()
Expand Down Expand Up @@ -155,7 +157,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
continue;
}

let agent = SignerStore::new_random(signers_per_period, &rand_seed, &from_pool);
let agent = SignerStore::new_random(signers_per_period, &rand_seed, from_pool);
all_signers.extend_from_slice(&agent.signers);
agents.add_agent(from_pool, agent);
}
Expand Down Expand Up @@ -196,7 +198,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let fund_amount = min_balance;
pending_fund_txs.push(
fund_account(
&admin_signer,
admin_signer,
*address,
fund_amount,
&eth_client,
Expand Down Expand Up @@ -417,7 +419,7 @@ async fn spam_callback_default(
return SpamCallbackType::Log(LogCallback::new(rpc_client.clone()));
}
}
SpamCallbackType::Nil(NilCallback::new())
SpamCallbackType::Nil(NilCallback)
}

async fn is_balance_sufficient(
Expand Down
2 changes: 1 addition & 1 deletion crates/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ path = "src/lib.rs"

[dependencies]
alloy = { workspace = true, features = ["full", "node-bindings", "rpc-types-mev"] }
eyre = { workspace = true }
# eyre = { workspace = true }
rand = { workspace = true }
serde = { workspace = true, features = ["derive"] }
futures = { workspace = true }
Expand Down
10 changes: 2 additions & 8 deletions crates/core/src/agent_controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub trait AgentRegistry<Index: Ord> {
fn get_agent(&self, idx: Index) -> Option<&Address>;
}

#[derive(Debug)]
#[derive(Debug, Default)]
pub struct SignerStore {
pub signers: Vec<PrivateKeySigner>,
}
Expand Down Expand Up @@ -87,16 +87,10 @@ where
}

impl SignerStore {
pub fn new() -> Self {
SignerStore {
signers: Vec::new(),
}
}

pub fn new_random(num_signers: usize, rand_seeder: &RandSeed, acct_seed: &str) -> Self {
// add numerical value of acct_seed to given seed
let new_seed = rand_seeder.as_u256() + U256::from_be_slice(acct_seed.as_bytes());
let rand_seeder = RandSeed::from_u256(new_seed);
let rand_seeder = RandSeed::seed_from_u256(new_seed);

// generate random private keys with new seed
let prv_keys = rand_seeder
Expand Down
4 changes: 2 additions & 2 deletions crates/core/src/generator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ where

// finds fuzzed values for a function call definition and populates `canonical_fuzz_map` with fuzzy values.
let mut find_fuzz = |req: &FunctionCallDefinition| {
let fuzz_args = req.fuzz.to_owned().unwrap_or(vec![]);
let fuzz_args = req.fuzz.to_owned().unwrap_or_default();
let fuzz_map = self.create_fuzz_map(num_txs, &fuzz_args)?; // this may create more values than needed, but it's fine
canonical_fuzz_map.extend(fuzz_map);
Ok(())
Expand Down Expand Up @@ -299,7 +299,7 @@ where
None,
req.kind.to_owned(),
);
return Ok((on_spam_setup(tx.to_owned())?, tx));
Ok((on_spam_setup(tx.to_owned())?, tx))
};

match step {
Expand Down
16 changes: 8 additions & 8 deletions crates/core/src/generator/seeder/rand_seed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,25 +30,25 @@ impl RandSeed {
/// - If `seed` is less than 32 bytes, it is right-padded with 0x01.
/// - If `seed` is more than 32 bytes, only the first 32 bytes are used.
/// - Number types created from these bytes are interpreted as big-endian.
pub fn from_bytes(seed_bytes: &[u8]) -> Self {
pub fn seed_from_bytes(seed_bytes: &[u8]) -> Self {
let mut seed_arr = [0u8; 32];
fill_bytes(seed_bytes, &mut seed_arr);
Self { seed: seed_arr }
}

/// Interprets seed as a number in base 10 or 16.
pub fn from_str(seed: &str) -> Self {
pub fn seed_from_str(seed: &str) -> Self {
let (radix, seed) = if seed.starts_with("0x") {
(16u64, seed.split_at(2).1)
} else {
(10u64, seed)
};
let n =
U256::from_str_radix(seed, radix).expect("invalid seed number; must fit in 32 bytes");
Self::from_u256(n)
Self::seed_from_u256(n)
}

pub fn from_u256(seed: U256) -> Self {
pub fn seed_from_u256(seed: U256) -> Self {
Self {
seed: seed.to_be_bytes(),
}
Expand Down Expand Up @@ -92,7 +92,7 @@ impl Seeder for RandSeed {
let val = keccak256(seed_num.as_le_slice());
let val = U256::from_be_bytes(val.0);
let val = val % (max - min) + min;
RandSeed::from_u256(val)
RandSeed::seed_from_u256(val)
});
Box::new(vals)
}
Expand All @@ -116,7 +116,7 @@ mod tests {
let mut seed_bytes = [0u8; 32];
seed_bytes[seed_bytes.len() - 1] = 0x01;
println!("{}", seed_bytes.encode_hex());
let seed = super::RandSeed::from_bytes(&seed_bytes);
let seed = super::RandSeed::seed_from_bytes(&seed_bytes);
println!("{}", seed.as_bytes().encode_hex());
assert_eq!(seed.as_bytes().len(), 32);
assert_eq!(seed.as_u64(), 1);
Expand All @@ -126,7 +126,7 @@ mod tests {

#[test]
fn encodes_seed_string() {
let seed = super::RandSeed::from_str("0x01");
let seed = super::RandSeed::seed_from_str("0x01");
assert_eq!(seed.as_u64(), 1);
assert_eq!(seed.as_u128(), 1);
assert_eq!(seed.as_u256(), U256::from(1));
Expand All @@ -135,7 +135,7 @@ mod tests {
#[test]
fn encodes_seed_u256() {
let n = U256::MAX;
let seed = super::RandSeed::from_u256(n);
let seed = super::RandSeed::seed_from_u256(n);
assert_eq!(seed.as_u256(), n);
}
}
7 changes: 3 additions & 4 deletions crates/core/src/generator/templater.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ where
let mut last_end = 0;

for _ in 0..num_template_vals {
let template_value = self.copy_end(&arg, last_end);
let template_value = self.copy_end(arg, last_end);
let (template_key, template_end) =
self.find_key(&template_value)
.ok_or(ContenderError::SpamError(
Expand Down Expand Up @@ -109,8 +109,7 @@ where
.value
.as_ref()
.map(|s| self.replace_placeholders(s, placeholder_map))
.map(|s| s.parse::<U256>().ok())
.flatten();
.and_then(|s| s.parse::<U256>().ok());

let from = funcdef
.from
Expand All @@ -137,7 +136,7 @@ where
.parse::<Address>()
.map_err(|e| ContenderError::with_err(e, "failed to parse from address"))?;

let full_bytecode = self.replace_placeholders(&createdef.bytecode, &placeholder_map);
let full_bytecode = self.replace_placeholders(&createdef.bytecode, placeholder_map);
let tx = alloy::rpc::types::TransactionRequest {
from: Some(from),
to: Some(alloy::primitives::TxKind::Create),
Expand Down
2 changes: 1 addition & 1 deletion crates/core/src/generator/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use alloy::{
/// assert_eq!(calldata.encode_hex(), "60fe47b10000000000000000000000000000000000000000000000000000000012345678");
/// ```
pub fn encode_calldata(args: &[impl AsRef<str>], sig: &str) -> Result<Vec<u8>> {
let func = json_abi::Function::parse(&sig).map_err(|e| {
let func = json_abi::Function::parse(sig).map_err(|e| {
ContenderError::SpamError("failed to parse function name", Some(e.to_string()))
})?;
let values: Vec<DynSolValue> = args
Expand Down
36 changes: 17 additions & 19 deletions crates/core/src/spammer/blockwise.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use crate::{

use super::{OnTxSent, SpamTrigger, Spammer};

#[derive(Default)]
pub struct BlockwiseSpammer;

impl BlockwiseSpammer {
Expand All @@ -27,26 +28,23 @@ where
S: Seeder + Send + Sync,
P: PlanConfig<String> + Templater<String> + Send + Sync,
{
fn on_spam(
async fn on_spam(
&self,
scenario: &mut TestScenario<D, S, P>,
) -> impl std::future::Future<Output = crate::Result<Pin<Box<dyn Stream<Item = SpamTrigger> + Send>>>>
{
async move {
let poller = scenario
.rpc_client
.watch_blocks()
.await
.map_err(|e| ContenderError::with_err(e, "failed to get block stream"))?;
Ok(poller
.into_stream()
.flat_map(futures::stream::iter)
.map(|b| {
println!("new block detected: {:?}", b);
SpamTrigger::BlockHash(b)
})
.boxed())
}
) -> crate::Result<Pin<Box<dyn Stream<Item = SpamTrigger> + Send>>> {
let poller = scenario
.rpc_client
.watch_blocks()
.await
.map_err(|e| ContenderError::with_err(e, "failed to get block stream"))?;
Ok(poller
.into_stream()
.flat_map(futures::stream::iter)
.map(|b| {
println!("new block detected: {:?}", b);
SpamTrigger::BlockHash(b)
})
.boxed())
}
}

Expand All @@ -67,7 +65,7 @@ mod tests {
async fn watches_blocks_and_spams_them() {
let anvil = spawn_anvil();
println!("anvil url: {}", anvil.endpoint_url());
let seed = crate::generator::RandSeed::from_str("444444444444");
let seed = crate::generator::RandSeed::seed_from_str("444444444444");
let mut scenario = TestScenario::new(
MockConfig,
MockDb.into(),
Expand Down
2 changes: 1 addition & 1 deletion crates/core/src/spammer/timed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ where
};
Ok(
futures::stream::unfold(0, move |t| async move { Some((do_poll(t).await, t + 1)) })
.map(|t| SpamTrigger::Tick(t))
.map(SpamTrigger::Tick)
.boxed(),
)
}
Expand Down
Loading

0 comments on commit ddf1645

Please sign in to comment.