Skip to content

Commit

Permalink
chore: add Makefile and codespell (foundry-rs#8948)
Browse files Browse the repository at this point in the history
* add makefile + codespell

* update makefile

* fix typos found by codespell

* add codespell CI task

* fix outdated spec

* ignore testdata

* switch default profile to dev, add strat to ignored words list
  • Loading branch information
zerosnacks authored Sep 24, 2024
1 parent ccb3c37 commit b09a88b
Show file tree
Hide file tree
Showing 44 changed files with 139 additions and 54 deletions.
3 changes: 3 additions & 0 deletions .codespellrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[codespell]
skip = .git,target,testdata,Cargo.toml,Cargo.lock
ignore-words-list = crate,ser,ratatui,Caf,froms,strat
10 changes: 10 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,15 @@ jobs:
cache-on-failure: true
- run: cargo test --workspace --doc

codespell:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: codespell-project/actions-codespell@v2
with:
skip: "*.json"

clippy:
runs-on: ubuntu-latest
timeout-minutes: 30
Expand Down Expand Up @@ -107,6 +116,7 @@ jobs:
- nextest
- docs
- doctest
- codespell
- clippy
- rustfmt
- forge-fmt
Expand Down
72 changes: 72 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Heavily inspired by:
# - Lighthouse: https://github.com/sigp/lighthouse/blob/693886b94176faa4cb450f024696cb69cda2fe58/Makefile
# - Reth: https://github.com/paradigmxyz/reth/blob/1f642353ca083b374851ab355b5d80207b36445c/Makefile
.DEFAULT_GOAL := help

# Cargo profile for builds.
PROFILE ?= dev

# List of features to use when building. Can be overridden via the environment.
# No jemalloc on Windows
ifeq ($(OS),Windows_NT)
FEATURES ?= rustls aws-kms cli asm-keccak
else
FEATURES ?= jemalloc rustls aws-kms cli asm-keccak
endif

##@ Help

.PHONY: help
help: ## Display this help.
@awk 'BEGIN {FS = ":.*##"; printf "Usage:\n make \033[36m<target>\033[0m\n"} /^[a-zA-Z_0-9-]+:.*?##/ { printf " \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST)

##@ Build

.PHONY: build
build: ## Build the project.
cargo build --features "$(FEATURES)" --profile "$(PROFILE)"

##@ Other

.PHONY: clean
clean: ## Clean the project.
cargo clean

## Linting

fmt: ## Run all formatters.
cargo +nightly fmt
./.github/scripts/format.sh --check

lint-foundry:
RUSTFLAGS="-Dwarnings" cargo clippy --workspace --all-targets --all-features

lint-codespell: ensure-codespell
codespell --skip "*.json"

ensure-codespell:
@if ! command -v codespell &> /dev/null; then \
echo "codespell not found. Please install it by running the command `pip install codespell` or refer to the following link for more information: https://github.com/codespell-project/codespell" \
exit 1; \
fi

lint: ## Run all linters.
make fmt && \
make lint-foundry && \
make lint-codespell

## Testing

test-foundry:
cargo nextest run -E 'kind(test) & !test(/issue|forge_std|ext_integration/)'

test-doc:
cargo test --doc --workspace

test: ## Run all tests.
make test-foundry && \
make test-doc

pr: ## Run all tests and linters in preparation for a PR.
make lint && \
make test
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ By default `forge config` shows the currently selected foundry profile and its v

### DappTools Compatibility

You can re-use your `.dapprc` environment variables by running `source .dapprc` before using a Foundry tool.
You can reuse your `.dapprc` environment variables by running `source .dapprc` before using a Foundry tool.

### Additional Configuration

Expand Down
2 changes: 1 addition & 1 deletion crates/anvil/core/src/eth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -522,7 +522,7 @@ pub enum EthRequest {
EvmSetTime(U256),

/// Serializes the current state (including contracts code, contract's storage, accounts
/// properties, etc.) into a savable data blob
/// properties, etc.) into a saveable data blob
#[cfg_attr(feature = "serde", serde(rename = "anvil_dumpState", alias = "hardhat_dumpState"))]
DumpState(#[cfg_attr(feature = "serde", serde(default))] Option<Params<Option<bool>>>),

Expand Down
2 changes: 1 addition & 1 deletion crates/anvil/core/src/eth/transaction/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -672,7 +672,7 @@ pub enum TypedTransaction {
/// This is a function that demotes TypedTransaction to TransactionRequest for greater flexibility
/// over the type.
///
/// This function is purely for convience and specific use cases, e.g. RLP encoded transactions
/// This function is purely for convenience and specific use cases, e.g. RLP encoded transactions
/// decode to TypedTransactions where the API over TypedTransctions is quite strict.
impl TryFrom<TypedTransaction> for TransactionRequest {
type Error = ConversionError;
Expand Down
2 changes: 1 addition & 1 deletion crates/anvil/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1401,7 +1401,7 @@ impl PruneStateHistoryConfig {
!self.enabled || self.max_memory_history.is_some()
}

/// Returns tru if this setting was enabled.
/// Returns true if this setting was enabled.
pub fn is_config_enabled(&self) -> bool {
self.enabled
}
Expand Down
4 changes: 2 additions & 2 deletions crates/anvil/src/eth/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1936,7 +1936,7 @@ impl EthApi {
Ok(())
}

/// Reorg the chain to a specific depth and mine new blocks back to the cannonical height.
/// Reorg the chain to a specific depth and mine new blocks back to the canonical height.
///
/// e.g depth = 3
/// A -> B -> C -> D -> E
Expand Down Expand Up @@ -2566,7 +2566,7 @@ impl EthApi {
// current midpoint, as spending any less gas would make no
// sense (as the TX would still revert due to lack of gas).
//
// We don't care about the reason here, as we known that trasaction is correct
// We don't care about the reason here, as we known that transaction is correct
// as it succeeded earlier
lowest_gas_limit = mid_gas_limit;
}
Expand Down
2 changes: 1 addition & 1 deletion crates/anvil/src/eth/backend/cheats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ impl CheatsManager {
let mut state = self.state.write();
// When somebody **explicitly** impersonates an account we need to store it so we are able
// to return it from `eth_accounts`. That's why we do not simply call `is_impersonated()`
// which does not check that list when auto impersonation is enabeld.
// which does not check that list when auto impersonation is enabled.
if state.impersonated_accounts.contains(&addr) {
// need to check if already impersonated, so we don't overwrite the code
return true
Expand Down
2 changes: 1 addition & 1 deletion crates/anvil/src/eth/backend/mem/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ pub struct Backend {
/// which the write-lock is active depends on whether the `ForkDb` can provide all requested
/// data from memory or whether it has to retrieve it via RPC calls first. This means that it
/// potentially blocks for some time, even taking into account the rate limits of RPC
/// endpoints. Therefor the `Db` is guarded by a `tokio::sync::RwLock` here so calls that
/// endpoints. Therefore the `Db` is guarded by a `tokio::sync::RwLock` here so calls that
/// need to read from it, while it's currently written to, don't block. E.g. a new block is
/// currently mined and a new [`Self::set_storage_at()`] request is being executed.
db: Arc<AsyncRwLock<Box<dyn Db>>>,
Expand Down
2 changes: 1 addition & 1 deletion crates/anvil/src/eth/backend/mem/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -569,7 +569,7 @@ impl MinedTransaction {
pub struct MinedTransactionReceipt {
/// The actual json rpc receipt object
pub inner: ReceiptResponse,
/// Output data fo the transaction
/// Output data for the transaction
pub out: Option<Bytes>,
}

Expand Down
2 changes: 1 addition & 1 deletion crates/anvil/src/eth/pool/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
//! used to determine whether it can be included in a block (transaction is ready) or whether it
//! still _requires_ other transactions to be mined first (transaction is pending).
//! A transaction is associated with the nonce of the account it's sent from. A unique identifying
//! marker for a transaction is therefor the pair `(nonce + account)`. An incoming transaction with
//! marker for a transaction is therefore the pair `(nonce + account)`. An incoming transaction with
//! a `nonce > nonce on chain` will _require_ `(nonce -1, account)` first, before it is ready to be
//! included in a block.
//!
Expand Down
2 changes: 1 addition & 1 deletion crates/cheatcodes/assets/cheatcodes.json

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

2 changes: 1 addition & 1 deletion crates/cheatcodes/spec/src/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1544,7 +1544,7 @@ interface Vm {
/// Deploys a contract from an artifact file. Takes in the relative path to the json file or the path to the
/// artifact in the form of <path>:<contract>:<version> where <contract> and <version> parts are optional.
///
/// Additionaly accepts abi-encoded constructor arguments.
/// Additionally accepts abi-encoded constructor arguments.
#[cheatcode(group = Filesystem)]
function deployCode(string calldata artifactPath, bytes calldata constructorArgs) external returns (address deployedAddress);

Expand Down
4 changes: 2 additions & 2 deletions crates/cheatcodes/src/inspector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ pub struct BroadcastableTransaction {
pub struct GasMetering {
/// True if gas metering is paused.
pub paused: bool,
/// True if gas metering was resumed or reseted during the test.
/// True if gas metering was resumed or reset during the test.
/// Used to reconcile gas when frame ends (if spent less than refunded).
pub touched: bool,
/// True if gas metering should be reset to frame limit.
Expand Down Expand Up @@ -1196,7 +1196,7 @@ impl<DB: DatabaseExt> Inspector<DB> for Cheatcodes {
call.target_address == HARDHAT_CONSOLE_ADDRESS;

// Clean up pranks/broadcasts if it's not a cheatcode call end. We shouldn't do
// it for cheatcode calls because they are not appplied for cheatcodes in the `call` hook.
// it for cheatcode calls because they are not applied for cheatcodes in the `call` hook.
// This should be placed before the revert handling, because we might exit early there
if !cheatcode_call {
// Clean up pranks
Expand Down
2 changes: 1 addition & 1 deletion crates/cheatcodes/src/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -594,7 +594,7 @@ fn serialize_value_as_json(value: DynSolValue) -> Result<Value> {
match value {
DynSolValue::Bool(b) => Ok(Value::Bool(b)),
DynSolValue::String(s) => {
// Strings are allowed to contain strigified JSON objects, so we try to parse it like
// Strings are allowed to contain stringified JSON objects, so we try to parse it like
// one first.
if let Ok(map) = serde_json::from_str(&s) {
Ok(Value::Object(map))
Expand Down
2 changes: 1 addition & 1 deletion crates/chisel/src/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1161,7 +1161,7 @@ impl Type {
Self::ethabi(&return_parameter.ty, Some(intermediate)).map(|p| (contract_expr.unwrap(), p))
}

/// Inverts Int to Uint and viceversa.
/// Inverts Int to Uint and vice-versa.
fn invert_int(self) -> Self {
match self {
Self::Builtin(DynSolType::Uint(n)) => Self::Builtin(DynSolType::Int(n)),
Expand Down
2 changes: 1 addition & 1 deletion crates/cli/src/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ pub fn block_on<F: Future>(future: F) -> F::Output {

/// Conditionally print a message
///
/// This macro accepts a predicate and the message to print if the predicate is tru
/// This macro accepts a predicate and the message to print if the predicate is true
///
/// ```ignore
/// let quiet = true;
Expand Down
2 changes: 1 addition & 1 deletion crates/config/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ model_checker = { contracts = { 'a.sol' = [
], timeout = 10000 }
verbosity = 0
eth_rpc_url = "https://example.com/"
# Setting this option enables decoding of error traces from mainnet deployed / verfied contracts via etherscan
# Setting this option enables decoding of error traces from mainnet deployed / verified contracts via etherscan
etherscan_api_key = "YOURETHERSCANAPIKEY"
# ignore solc warnings for missing license and exceeded contract size
# known error codes are: ["unreachable", "unused-return", "unused-param", "unused-var", "code-size", "shadowing", "func-mutability", "license", "pragma-solidity", "virtual-interfaces", "same-varname", "too-many-warnings", "constructor-visibility", "init-code-size", "missing-receive-ether", "unnamed-return", "transient-storage"]
Expand Down
2 changes: 1 addition & 1 deletion crates/config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2717,7 +2717,7 @@ impl<P: Provider> Provider for OptionalStrictProfileProvider<P> {
figment.data().map_err(|err| {
// figment does tag metadata and tries to map metadata to an error, since we use a new
// figment in this provider this new figment does not know about the metadata of the
// provider and can't map the metadata to the error. Therefor we return the root error
// provider and can't map the metadata to the error. Therefore we return the root error
// if this error originated in the provider's data.
if let Err(root_err) = self.provider.data() {
return root_err;
Expand Down
2 changes: 1 addition & 1 deletion crates/evm/core/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ fn get_create2_factory_call_inputs(salt: U256, inputs: CreateInputs) -> CallInpu
/// Used for routing certain CREATE2 invocations through [DEFAULT_CREATE2_DEPLOYER].
///
/// Overrides create hook with CALL frame if [InspectorExt::should_use_create2_factory] returns
/// true. Keeps track of overriden frames and handles outcome in the overriden insert_call_outcome
/// true. Keeps track of overridden frames and handles outcome in the overridden insert_call_outcome
/// hook by inserting decoded address directly into interpreter.
///
/// Should be installed after [revm::inspector_handle_register] and before any other registers.
Expand Down
2 changes: 1 addition & 1 deletion crates/evm/coverage/src/anchors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ pub fn find_anchor_simple(

Ok(ItemAnchor {
instruction: ic_pc_map.get(instruction).ok_or_else(|| {
eyre::eyre!("We found an anchor, but we cant translate it to a program counter")
eyre::eyre!("We found an anchor, but we can't translate it to a program counter")
})?,
item_id,
})
Expand Down
4 changes: 2 additions & 2 deletions crates/evm/evm/src/executors/fuzz/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,15 +88,15 @@ impl FuzzedExecutor {
let execution_data = RefCell::new(FuzzTestData::default());
let state = self.build_fuzz_state();
let dictionary_weight = self.config.dictionary.dictionary_weight.min(100);
let strat = proptest::prop_oneof![
let strategy = proptest::prop_oneof![
100 - dictionary_weight => fuzz_calldata(func.clone(), fuzz_fixtures),
dictionary_weight => fuzz_calldata_from_state(func.clone(), &state),
];
// We want to collect at least one trace which will be displayed to user.
let max_traces_to_collect = std::cmp::max(1, self.config.gas_report_samples) as usize;
let show_logs = self.config.show_logs;

let run_result = self.runner.clone().run(&strat, |calldata| {
let run_result = self.runner.clone().run(&strategy, |calldata| {
let fuzz_res = self.single_fuzz(address, should_fail, calldata)?;

// If running with progress then increment current run.
Expand Down
6 changes: 3 additions & 3 deletions crates/evm/evm/src/executors/invariant/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ impl InvariantTestRun {
}
}

/// Wrapper around any [`Executor`] implementor which provides fuzzing support using [`proptest`].
/// Wrapper around any [`Executor`] implementer which provides fuzzing support using [`proptest`].
///
/// After instantiation, calling `invariant_fuzz` will proceed to hammer the deployed smart
/// contracts with inputs, until it finds a counterexample sequence. The provided [`TestRunner`]
Expand Down Expand Up @@ -463,7 +463,7 @@ impl<'a> InvariantExecutor<'a> {
EvmFuzzState::new(self.executor.backend().mem_db(), self.config.dictionary);

// Creates the invariant strategy.
let strat = invariant_strat(
let strategy = invariant_strat(
fuzz_state.clone(),
targeted_senders,
targeted_contracts.clone(),
Expand Down Expand Up @@ -519,7 +519,7 @@ impl<'a> InvariantExecutor<'a> {
last_call_results,
self.runner.clone(),
),
strat,
strategy,
))
}

Expand Down
10 changes: 5 additions & 5 deletions crates/evm/evm/src/executors/invariant/shrink.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@ struct Shrink {
/// If the failure is not reproducible then restore removed call and moves to next one.
#[derive(Debug)]
struct CallSequenceShrinker {
/// Length of call sequence to be shrinked.
/// Length of call sequence to be shrunk.
call_sequence_len: usize,
/// Call ids contained in current shrinked sequence.
/// Call ids contained in current shrunk sequence.
included_calls: VarBitSet,
/// Current shrinked call id.
/// Current shrunk call id.
shrink: Shrink,
/// Previous shrinked call id.
/// Previous shrunk call id.
prev_shrink: Option<Shrink>,
}

Expand Down Expand Up @@ -82,7 +82,7 @@ impl CallSequenceShrinker {
/// Maximal shrinkage is guaranteed if the shrink_run_limit is not set to a value lower than the
/// length of failed call sequence.
///
/// The shrinked call sequence always respect the order failure is reproduced as it is tested
/// The shrunk call sequence always respect the order failure is reproduced as it is tested
/// top-down.
pub(crate) fn shrink_sequence(
failed_case: &FailedInvariantCaseData,
Expand Down
2 changes: 1 addition & 1 deletion crates/evm/evm/src/executors/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -576,7 +576,7 @@ impl Executor {
/// Creates the environment to use when executing a transaction in a test context
///
/// If using a backend with cheatcodes, `tx.gas_price` and `block.number` will be overwritten by
/// the cheatcode state inbetween calls.
/// the cheatcode state in between calls.
fn build_test_env(
&self,
caller: Address,
Expand Down
4 changes: 2 additions & 2 deletions crates/evm/fuzz/src/strategies/param.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,12 +218,12 @@ mod tests {
let func = get_func(f).unwrap();
let db = CacheDB::new(EmptyDB::default());
let state = EvmFuzzState::new(&db, FuzzDictionaryConfig::default());
let strat = proptest::prop_oneof![
let strategy = proptest::prop_oneof![
60 => fuzz_calldata(func.clone(), &FuzzFixtures::default()),
40 => fuzz_calldata_from_state(func, &state),
];
let cfg = proptest::test_runner::Config { failure_persistence: None, ..Default::default() };
let mut runner = proptest::test_runner::TestRunner::new(cfg);
let _ = runner.run(&strat, |_| Ok(()));
let _ = runner.run(&strategy, |_| Ok(()));
}
}
Loading

0 comments on commit b09a88b

Please sign in to comment.