Coder Social home page Coder Social logo

mouseless-eth / rusty-sando Goto Github PK

View Code? Open in Web Editor NEW
717.0 33.0 249.0 19.07 MB

Implementation of a competitive v2/v3 multi-meat MEV sandwich bot written using Rust and Huff.

License: MIT License

Rust 75.96% Solidity 24.04%
huff mev rust evm sandwich

rusty-sando's Introduction

Rusty-Sando (re-write) license twitter

A practical example on how to perform V2/V3 and multi-meat sandwich attacks written using Rust and Huff.

The goal of this repo is to act as reference material for aspiring searchers.

This codebase has been cleaned up and rewritten using the Artemis framework. (Further details in pull request #31)

Demo

final_demo.mp4

Brief Explanation

Anytime that a transaction interacts with a Uniswap V2/V3 pool and its forks, there is some slippage introduced (routers, aggregators, other MEV bots). Sandwich bots, like this one, are a toxic form of MEV as they profit off this slippage by frontrunning the transaction pushing the price of an asset up to the slippage limit, and then immediately selling the asset through a backrun transaction.

Bot Logic Breakdown can be found under bot/README.md

Contract Logic Breakdown can be found under contract/README.md

Features

  • Fully Generalized: Sandwich any tx that introduces slippage.
  • V2 and V3 Logic: Logic to handle Uniswap V2/V3 pools.
  • Multi-Meat: Build and send multi-meat sandwiches.
  • Gas Optimized: Contract written in Huff using unconventional gas optimizations.
  • Local Simulations: Fast concurrent EVM simulations to find sandwich opportunities.
  • Token Dust: Stores dust at the end of every bundle for lower gas usage the next time the token is traded.
  • Salmonella Checks: Detect if erc20's transfer function uses any unusual opcodes that may produce different mainnet results.

Notice

If any bugs or optimizations are found, feel free to create a pull request. All pull requests are welcome!

Warning

This software is highly experimental and should be used at your own risk. Although tested, this bot is experimental software and is provided on an "as is" and "as available" basis under the MIT license. We cannot guarantee the stability or reliability of this codebase and are not responsible for any damage or loss caused by its use. We do not give out warranties.

Acknowledgments

rusty-sando's People

Contributors

mevsando avatar mouseless-eth avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rusty-sando's Issues

Sandwish Contract and Inception Block

Hello,

I'm exploring the documentation at this location, specifically focusing on the environment variables under the "Usage" section. There are two values that I need clarification on:

SANDWICH_CONTRACT=0xaAaAaAaaAaAaAaaAaAAAAAAAAaaaAaAaAaaAaaAa
SANDWICH_INCEPTION_BLOCK=...

I need to create and fund a smart contract? Whats an Inception Block? I have some hints here, thanks @Cionn3

  1. I'm looking for guidance on how to generate the FLASHBOTS_AUTH_KEY. Could you provide some information or direct me to resources that explains how to obtain this key?
  2. Finally, I have a question about the Erigon archive node. I began the sync process around two days ago. Is it necessary for me to wait for it to completely synchronize and index before continuing?

Screenshot 2023-08-04 at 6 52 15 PM

Thank you for your experience, and I look forward to your reply. Cheers.

Thread 'tokio-runtime-worker' panicked at 'arithmetic operation overflow'

Im having this error:
thread 'tokio-runtime-worker' panicked at 'arithmetic operation overflow'

Running:
cargo run --bin rusty-sando --release

We think is in create_optimal_sandwich func located in /src/simulate/make_sandwich.rs

pub async fn create_optimal_sandwich(
    ingredients: &RawIngredients,
    sandwich_balance: U256,
    next_block: &BlockInfo,
    fork_factory: &mut ForkFactory,
    sandwich_maker: &SandwichMaker,
) -> Result<OptimalRecipe, SimulationError> {
    let optimal = juiced_quadratic_search(
        ingredients,
        U256::zero(),
        sandwich_balance,
        next_block,
        fork_factory,
    )
    .await?;

    #[cfg(test)]
    {
        println!("Optimal amount in: {}", optimal);
    }

    sanity_check(
        sandwich_balance,
        optimal,
        ingredients,
        next_block,
        sandwich_maker,
        fork_factory.new_sandbox_fork(),
    )
}

By running /src/runner/mod.rs

let mut optimal_sandwich = match make_sandwich::create_optimal_sandwich(
                        &raw_ingredients,
                        sandwich_balance,
                        &block_oracle.next_block,
                        &mut fork_factory,
                        &sandwich_maker,
                    )
                    .await
                    {
                        Ok(optimal) => optimal,
                        Err(e) => {
                            log::info!(
                                "{}",
                                format!("{:?} sim failed due to {:?}", &victim_hash, e).yellow()
                            );
                            return;
                        }
                    };

Any idea what may be causing this error?
Thanks!

Bug in juiced_quadratic_search

upper_bound = intervals[intervals.len() / 3] - 1;
In make_sandwich.rs line 185 panics on every run of juiced_quadratic_search function

Pulsechain

Can this be made to run on Pulsechain ? It's an Ethereum fork

metamorphic contracts

Hi,

Sorry for this but can someone explain how can i get this done? im asking because there is a lack of documentation in this

"Fill in the searcher address in Huff contract and deploy either straight onchain or via create2 using a metamorphic like factory."

Contract's recover Weth function not working properly.

I deployed the sandwich contract and I've been able to interact with it using foundry's "cast send" commands. I was able to successfully Seppuku one of the contracts I deployed so I'm at least sure that I'm using the command correctly in some capacity.

However, I've deposited some Weth to the contract and I've attempted to use the "cast send" with JUMPDEST 0x42 so that I can Recover the Weth I sent to the contract. The command works to some degree but for some reason the wad it passes stays at 0 which makes it impossible for me to recover my Weth.

Here is the transaction on etherscan: https://etherscan.io/tx/0xd9a9caf2bef63eea110c1596d655aa5926c95f4dec6af35706748e84ba47e2ce

Here is the log:
https://etherscan.io/tx/0xd9a9caf2bef63eea110c1596d655aa5926c95f4dec6af35706748e84ba47e2ce#eventlog

In the log you can see that the command is correctly using the addresses but the wad is 0.

Am I missing something? How can I recover the Weth on the contract <3

Regarding the optimization issue of invoking contracts,

we can see that in the code, the amount is passed by setting msg.value. It is well known that transferring funds incurs thousands of gas costs. Why not pack the amount using shr(uint32) + offset(uint8) into calldata? This would require less than one thousand gas costs.

JUMPDEST locations are incorrect.

The read me in contract folder incorrectly lables the jump destinations, if you need the jumpdest use the following table pulled from the contract

├─ [2352] SandoCommon::getJumpDestFromSig(v2_backrun0) [delegatecall]
│   └─ ← 5
├─ [0] console::f5b1bba9(0000000000000000000000000000000000000000000000000000000000000005) [staticcall]
│   └─ ← ()
├─ [3148] SandoCommon::getJumpDestFromSig(v2_frontrun0) [delegatecall]
│   └─ ← 10
├─ [0] console::f5b1bba9(000000000000000000000000000000000000000000000000000000000000000a) [staticcall]
│   └─ ← ()
├─ [3943] SandoCommon::getJumpDestFromSig(v2_backrun1) [delegatecall]
│   └─ ← 15
├─ [0] console::f5b1bba9(000000000000000000000000000000000000000000000000000000000000000f) [staticcall]
│   └─ ← ()
├─ [4736] SandoCommon::getJumpDestFromSig(v2_frontrun1) [delegatecall]
│   └─ ← 20
├─ [0] console::f5b1bba9(0000000000000000000000000000000000000000000000000000000000000014) [staticcall]
│   └─ ← ()
├─ [5531] SandoCommon::getJumpDestFromSig(v3_backrun0) [delegatecall]
│   └─ ← 25
├─ [0] console::f5b1bba9(0000000000000000000000000000000000000000000000000000000000000019) [staticcall]
│   └─ ← ()
├─ [6327] SandoCommon::getJumpDestFromSig(v3_frontrun0) [delegatecall]
│   └─ ← 30
├─ [0] console::f5b1bba9(000000000000000000000000000000000000000000000000000000000000001e) [staticcall]
│   └─ ← ()
├─ [7119] SandoCommon::getJumpDestFromSig(v3_backrun1) [delegatecall]
│   └─ ← 35
├─ [0] console::f5b1bba9(0000000000000000000000000000000000000000000000000000000000000023) [staticcall]
│   └─ ← ()
├─ [7915] SandoCommon::getJumpDestFromSig(v3_frontrun1) [delegatecall]
│   └─ ← 40
├─ [0] console::f5b1bba9(0000000000000000000000000000000000000000000000000000000000000028) [staticcall]
│   └─ ← ()
├─ [8708] SandoCommon::getJumpDestFromSig(seppuku) [delegatecall]
│   └─ ← 45
├─ [0] console::f5b1bba9(000000000000000000000000000000000000000000000000000000000000002d) [staticcall]
│   └─ ← ()
├─ [9503] SandoCommon::getJumpDestFromSig(recoverEth) [delegatecall]
│   └─ ← 50
├─ [0] console::f5b1bba9(0000000000000000000000000000000000000000000000000000000000000032) [staticcall]
│   └─ ← ()
├─ [10299] SandoCommon::getJumpDestFromSig(recoverWeth) [delegatecall]
│   └─ ← 55
├─ [0] console::f5b1bba9(0000000000000000000000000000000000000000000000000000000000000037) [staticcall]
│   └─ ← ()
├─ [9503] SandoCommon::getJumpDestFromSig(recoverEth) [delegatecall]
│   └─ ← 50
├─ [172] 0xf92CE891Ab58B70486487043DD3f2e6eD713e019::fallback() 
│   ├─ [0] 0xFA66075755e579b37B654d3baAF7da0F70cd09bE::fallback() 
│   │   └─ ← ()
│   └─ ← ()
├─ [9503] SandoCommon::getJumpDestFromSig(recoverEth) [delegatecall]
│   └─ ← 50
├─ [0] console::f5b1bba9(0000000000000000000000000000000000000000000000000000000000000032) [staticcall]
│   └─ ← ()
└─ ← ()

Contracts -> Tests failing

forge test --rpc-url <your-rpc-url-here>

The above test as detailed in the contract/README is failing.

But when I change the test/sandwich.t.sol to not rely on HuffDeployer to deploy sandwich.huff and instead provide the address of sandwich.huff contract already deployed on chain then the tests pass without problems.

//sandwich = HuffDeployer.deploy("sandwich");
sandwich = <deployed sandwich.huff address>;

Not sure whats happening. Could be an issue in upsream Foundry project.

Opening this issue to document this problem and the interim solution.

[huffsando: REVERT] frontrun

Ive try to run this code using:
cargo run --release --features debug

And always get:
[huffsando: REVERT] frontrun

Sometimes with this error also:
[ERROR] error receiving event: channel lagged by X

The issue is duplicated because mouseless-eth closed it, I don't understand why.

Any idea?

Thanks,

Cannot deploy contract

Trying to deploy the huff contract it and it says:

    │   ├─ [0] VM::prank(HuffConfig: [0xC7f2Cf4845C6db0e1a1e91ED41Bcd0FcC1b0E141]) 
    │   │   └─ ← ()
    │   ├─ [0] VM::ffi([rm, src/__TEMP__exzchhtyiyilqpjvvhjrbtzfffmlwbyvsando.huff]) 
    │   │   └─ ← 0x
    │   ├─ [0] VM::broadcast() 
    │   │   └─ ← "You have an active prank. Broadcasting and pranks are not compatible. Disable one or the other"
    │   └─ ← "You have an active prank. Broadcasting and pranks are not compatible. Disable one or the other"
    └─ ← "You have an active prank. Broadcasting and pranks are not compatible. Disable one or the other"


Error: 
You have an active prank. Broadcasting and pranks are not compatible. Disable one or the other

Command used:
forge script ./script/DeploySandwich.s.sol --rpc-url <alchemy_endpoint> --broadcast --private-key <privkey>

Any idea why ?

Tests Failure

Hi,

We are having this error in all tests:

---- simulate::make_sandwich::test::sandv2_multi_with_three_expect_one_reverts stdout ---- thread 'simulate::make_sandwich::test::sandv2_multi_with_three_expect_one_reverts' panicked at 'called Option::unwrap()on aNone value', src/simulate/make_sandwich.rs:696:10

We think is because this:

From: bot/src/utils/state_diff.rs

pub async fn get_from_txs(
    client: &Arc<Provider<Ws>>,
    meats: &Vec<Transaction>,
    block_num: BlockNumber,
) -> Option<BTreeMap<Address, AccountDiff>> {
    // add statediff trace to each transaction
    let req = meats
        .iter()
        .map(|tx| (tx, vec![TraceType::StateDiff]))
        .collect();

    let block_traces = match client.trace_call_many(req, Some(block_num)).await {
        Ok(x) => x,
        Err(_) => {
            // should throw error here but guess None also works :<
            return None;
        }
    };

    let mut merged_state_diffs = BTreeMap::new();

    block_traces
        .into_iter()
        .flat_map(|bt| bt.state_diff.map(|sd| sd.0.into_iter()))
        .flatten()
        .for_each(|(address, account_diff)| {
            match merged_state_diffs.entry(address) {
                Entry::Vacant(entry) => {
                    entry.insert(account_diff);
                }
                Entry::Occupied(_) => {
                    // Do nothing if the key already exists
                    // we only care abt the starting state
                }
            }
        });

    Some(merged_state_diffs)
}

And this:
In: bot/src/simulate/make_sandwich.rs

        let state = utils::state_diff::get_from_txs(
            &ws_provider,
            &victim_txs,
            BlockNumber::Number(U64::from(fork_block_num)),
        )
        .await
        .unwrap();

We think that

let block_traces = match client.trace_call_many(req, Some(block_num)).await {
        Ok(x) => x,
        Err(_) => {
            // should throw error here but guess None also works :<
            return None;
        }
    };

Is returning ERR None, and this is the failure cause, but we don't know exactly was happening.
Any help is appreciated

Recover funds

Hello, was wondering how can I recover funds I sent to the contract ?

Always getting [huffsando: REVERT] frontrun

Ive try to run this code using:
cargo run --release --features debug

And always get:
[huffsando: REVERT] frontrun

Sometimes with this error also:
[ERROR] error receiving event: channel lagged by X

Any idea?

Thanks,

access list omitted for several op codes

access list not included for below op codes

opcode::EXTCODECOPY
            opcode::EXTCODEHASH
            opcode::EXTCODESIZE
            opcode::BALANCE
            opcode::SELFDESTRUCT 
            opcode::DELEGATECALL 
            opcode::CALL 
            opcode::STATICCALL 
            opcode::CALLCODE

looks like only get entry but not inserted?

or am i mis understadning?

btw, can you explain the function is_sando_safu? why those op codes are not considered safe? and why op code GAS should not be called more than call

Cargo Tests result in "Optimal amount in: 0 not sandwichable"

cargo test --release -- --nocapture
Compiling rusty-sando v0.1.0 (/home/bunkerdiss/Mainnet/rusty-sando/bot)
Finished release [optimized + debuginfo] target(s) in 32.22s
Running unittests src/lib.rs (target/release/deps/rusty_sando-aadba4f6843ddd34)

running 8 tests
Optimal amount in: 0
not sandwichable
total_duration took: 98.083001ms
test simulate::make_sandwich::test::sandv3_uniswap_universal_router_two ... ok
Optimal amount in: 0
not sandwichable
total_duration took: 104.813099ms
test simulate::make_sandwich::test::sandv2_sushi_router ... ok
Optimal amount in: 0
not sandwichable
total_duration took: 115.216918ms
test simulate::make_sandwich::test::sandv2_non_sandwichable ... ok
Optimal amount in: 0
not sandwichable
total_duration took: 124.925376ms
Optimal amount in: 0
test simulate::make_sandwich::test::sandv2_multi_two ... ok
not sandwichable
total_duration took: 127.250113ms
Optimal amount in: 0
not sandwichable
total_duration took: 128.15483ms
test simulate::make_sandwich::test::sandv2_multi_with_three_expect_one_reverts ... ok
test simulate::make_sandwich::test::sandv2_metamask_swap_router ... ok
Optimal amount in: 0
not sandwichable
total_duration took: 142.075276ms
test simulate::make_sandwich::test::sandv3_uniswap_universal_router_one ... ok
Optimal amount in: 0
not sandwichable
total_duration took: 164.145253ms
test simulate::make_sandwich::test::sandv2_kyber_swap ... ok

test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.17s

 Running unittests src/main.rs (target/release/deps/rusty_sando-e283202ca237ea10)

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Doc-tests rusty-sando

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

as you can see running the cargo tests result in all not sandwichable optimal in being 0. anyone else have this issue?

panic at unwrap error, Please help!!!

when Running
$ cargo test --release -- --nocapture
i get the error.

simulate::make_sandwich::test::sandv2_kyber_swap' panicked at 'called `Result::unwrap()` on an `Err` value: InternalError(Http(Response { status: 200, version: HTTP/1.1, headers: {"date": "Tue, 18 Jul 2023 15:04:03 GMT", "content-length": "0"}, body: Some([]) }))', src/utils/testhelper.rs:39:55
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'simulate::make_sandwich::test::sandv2_multi_with_three_expect_one_reverts' panicked at 'called `Result::unwrap()` on an `Err` value: InternalError(Http(Response { status: 200, version: HTTP/1.1, headers: {"date": "Tue, 18 Jul 2023 15:04:03 GMT", "content-length": "0"}, body: Some([]) }))', src/utils/testhelper.rs:39:55

my setups are like this

.env

RPC_URL_WSS=wss://eth-mainnet.g.alchemy.com/v2/wE6H0DZdOWaVWL2RIRsq8eEjC6KWVD74
SEARCHER_PRIVATE_KEY=mykey
FLASHBOTS_AUTH_KEY=mykey
SANDWICH_CONTRACT=0x8dCE61A5701165D05af240Ee0cbDEc9042964A01
INTERVAL_BLOCK_NEW_POOL=50
V2_ALERT_DISCORD_WEBHOOK=https://discord.com/api/webhooks/1130844464777269289/nwy6w_7PzKj5CIWVxf6UQ-Q6PSBVFHl6_1GPbKKq2LoPxHRHWKH_p5bvd5dg71G2ltOR
V3_ALERT_DISCORD_WEBHOOK=https://discord.com/api/webhooks/1130844476177399918/2XvSYs_w0tZHcpyCC0lzFMJ7HJQytT7j8ntHt0OSP00hBxddPkWJoJLqsUbimQRnYQeP
POISON_ALERT_DISCORD_WEBHOOK=https://discord.com/api/webhooks/1130845040336457778/rRxV_OzqKi3b2Gp7_QVlKbytcOc6eJJE7GUmmZKiupbeOCcMm47ZHy--tvcPrrdouOVF
SANDWICH_INCEPTION_BLOCK=17720362

utils/testhelper.rs

use std::{sync::Arc, time::Duration};

use ethers::{
    prelude::*,
    utils::{Anvil, AnvilInstance},
};

use crate::{
    prelude::{Erc20, Pool, PoolVariant, UniswapV3Pool},
    types::BlockInfo,
};

use super::{constants::get_weth_address, dotenv::get_sandwich_contract_address};

pub async fn get_next_block_info(prev_block_number: u64, client: &Arc<Provider<Ws>>) -> BlockInfo {
    let prev_block = client.get_block(prev_block_number).await.unwrap().unwrap();
    BlockInfo::find_next_block_info(prev_block)
}

// need to return anvil instance to keep it alive (so that we can make calls)
pub async fn create_fork_ws(fork_block_num: u64) -> (Arc<Provider<Ws>>, AnvilInstance) {
    let port_num: u16 = rand::Rng::gen_range(&mut rand::thread_rng(), 3000..4000);

    let _anvil = Anvil::new()
        .fork(format!(
            "https://eth-mainnet.g.alchemy.com/v2/wE6H0DZdOWaVWL2RIRsq8eEjC6KWVD74@{}",
            fork_block_num
        ))
        .port(port_num)
        .spawn();
    let ws_fork = Ws::connect(format!("ws://127.0.0.1:{}", port_num))
        .await
        .unwrap();
    let ws_provider_fork = Provider::new(ws_fork).interval(Duration::from_millis(100));
    (Arc::new(ws_provider_fork), _anvil)
}

pub async fn create_ws() -> Arc<Provider<Ws>> {
    let ws = Ws::connect("ws://localhost:8545").await.unwrap();
    let ws_provider = Provider::new(ws).interval(Duration::from_millis(100));
    Arc::new(ws_provider)
}

pub async fn create_v2_pool(pool_address: Address, client: &Arc<Provider<Ws>>) -> Pool {
    let pool_contract = super::contracts::get_pair_v2_contract(&pool_address, client);
    let token_0 = pool_contract.token_0().call().await.unwrap();
    let token_1 = pool_contract.token_1().call().await.unwrap();

    Pool::new(
        pool_address,
        token_0,
        token_1,
        U256::from(3000),
        PoolVariant::UniswapV2,
    )
}

pub async fn create_v3_pool(pool_address: Address, client: &Arc<Provider<Ws>>) -> Pool {
    let pool = UniswapV3Pool::new(pool_address, client.into());

    let token_0 = pool.token_0().call().await.unwrap();
    let token_1 = pool.token_1().call().await.unwrap();
    let fee = pool.fee().call().await.unwrap();

    Pool::new(
        pool_address,
        token_0,
        token_1,
        U256::from(fee),
        PoolVariant::UniswapV3,
    )
}

/// Override an address's weth balance
pub fn mutate_weth_balance(
    state: &mut call_raw::spoof::State,
    address_to_mutate: Address,
    mutate_amount: U256,
) {
    let key = super::u256_to_h256_be(
        U256::from_str_radix(
            "ffa74f65cef4257058238f071cd4f631a58040052dd622d00aa7a451153252f4",
            16,
        )
        .unwrap(),
    );
    // Spoofing WETH balance
    // cast index address [address] 3 : WETH (give our sandwich contract 100weth)
    let val = super::u256_to_h256_be(U256::from("100000000000000000000"));
    // Give our acc a fuckton of WETH
    state
        .account(super::constants::get_weth_address())
        .store(key, val);
    state.account(address_to_mutate).balance(mutate_amount);
}

pub async fn get_weth_balance_at_block(block: u64) -> U256 {
    let (fork, _instance) = create_fork_ws(block).await;
    let weth_contract = Erc20::new(get_weth_address(), fork);
    let owner = get_sandwich_contract_address();
    weth_contract.balance_of(owner).call().await.unwrap()
}

#[macro_export]
macro_rules! time_function {
    ($x:expr) => {{
        let start = std::time::Instant::now();
        let result = $x;
        let elapsed = start.elapsed();
        println!("Elapsed time: {:?}", elapsed);
        result
    }};
}

Can anyone help me?

I'm getting these errors when I cargo test and cargo run

[16:51:18][INFO] all_pools_len: 0
[16:51:18][INFO] Found 0 tokens worth of dust
thread 'main' panicked at 'called Result::unwrap() on an Err value: Invalid name: please ensure the contract and method you're calling exist! failed to decode empty bytes. if you're using jsonrpc this is likely due to jsonrpc returning 0x in case contract or method don't exist

Anyone know why? Maybe my erigon node isn't setup properly, I run it with --ws
The node is running.

Error 2
Error

Unable to Fund the HUFF contract

I have updated the sandwich.huff with my address as below.

#define constant SEARCHER = 0xe1C17AA226Eb2F6d2a29C025532caBa4fbE45a83
#define constant HELPER = 0xe1C17AA226Eb2F6d2a29C025532caBa4fbE45a83

Compiled the contract using huffc, and deployed the same to this address 0x6C00C500009405000D005817a35f002a002F0068

Now when I am trying to fund the contract, I am getting this error

Warning! Error encountered during contract execution [invalid jump destination]

ETH Txn: https://etherscan.io/tx/0x64392fabbfac3795c5ccf2fe32e9799e86e7159875191378fccc5cebcbe15298

Please help!

Huff constant documentation

Can you explain the purpose of the following constants:

#define constant PAIR_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54
#define constant HELPER = 0x2B5AD5c4795c026514f8317c7a215E218DcCD6cF

I see no documentation on these constants, and it seems at very least, HELPER needs to be changed prior to deployment.

Thanks

Cannot deploy the contract

Hi,

Same problem deploying the contract as here #20 and here #33 and fix 3fb7081 did not resolve the issue.

"You have an active prank. Broadcasting and pranks are not compatible. Disable one or the other"

[2166321] → new Deployer@0x5b73C5498c1E3b4dbA84de0F1833c4a029d90519 └─ ← 10599 bytes of code [98] Deployer::setUp() └─ ← () [2113497] Deployer::run() ├─ [1981204] → new HuffConfig@0xC7f2Cf4845C6db0e1a1e91ED41Bcd0FcC1b0E141 │ └─ ← 9785 bytes of code ├─ [679] HuffConfig::set_broadcast(true) │ └─ ← HuffConfig: [0xC7f2Cf4845C6db0e1a1e91ED41Bcd0FcC1b0E141] ├─ [74581] HuffConfig::deploy(sando) │ ├─ [0] VM::ffi([./lib/foundry-huff/scripts/binary_check.sh]) │ │ └─ ← 0x01 │ ├─ [0] VM::ffi([./lib/foundry-huff/scripts/rand_bytes.sh]) │ │ └─ ← 0x0e733023c11bfe6a8965c755c2d8500a │ ├─ [0] VM::ffi([./lib/foundry-huff/scripts/file_writer.sh, src/__TEMP__bpwamwyejjqqmzlxebcshznkhdjwbethsando.huff, ]) │ ├─ [0] VM::prank(HuffConfig: [0xC7f2Cf4845C6db0e1a1e91ED41Bcd0FcC1b0E141]) │ │ └─ ← () │ ├─ [0] VM::ffi([rm, src/__TEMP__bpwamwyejjqqmzlxebcshznkhdjwbethsando.huff]) │ │ └─ ← 0x │ ├─ [0] VM::broadcast() │ │ └─ ← "You have an active prank. Broadcasting and pranks are not compatible. Disable one or the other" │ └─ ← "You have an active prank. Broadcasting and pranks are not compatible. Disable one or the other" └─ ← "You have an active prank. Broadcasting and pranks are not compatible. Disable one or the other" Error: You have an active prank. Broadcasting and pranks are not compatible. Disable one or the other

Using:

`// SPDX-License-Identifier: MIT
pragma solidity ^0.8.15;

import "forge-std/Script.sol";
import "forge-std/console.sol";
import "foundry-huff/HuffDeployer.sol";
import "../src/LilRouter.sol";

contract Deployer is Script {

// serachers
function setUp() public {

}
function run() public{
    address sandwich = HuffDeployer.broadcast("sando");
    console.log(address(sandwich));
}

}`

//forge script ./script/DeploySandwich.s.sol --rpc-url {} --broadcast --private-key {}

Any ideas?

All instructions followed, yet bot still doesn't seem to work.

I was able to deploy and interact with sandwich contract successfully and after running the bot I'm getting both of the appropriate sim failed errors as seen in the demo video:

sim failed due to FrontrunReverted(b"\x08\0\0"
sim failed due to FrontrunReverted(b"\x9f\0\0"

The behaviors are expected and everything looks good so far. However, the bot still doesn't seem to be working correctly. One unexpected behavior is this,

thread 'tokio-runtime-worker' panicked at 'called Result::unwrap()on anErr value: FrontrunEvmError(Transaction(NonceTooLow { tx: 1, state: 6 }))', src/simulate/make_sandwich.rs:439:10

I feel like this is currently the barrier preventing the bot from working correctly.

The error NonceTooLow suggests that the nonce used in the transaction (tx: 1) is lower than the current nonce in the state (state: 6), hence the transaction is considered invalid. But I don't really know where to begin with fixing this.

Any help or insights would by very much appreciated.

please note the line 439:10 doesn't match the exact place in the repo's code as I've added print statement in my code.

Contract Deployment

Sorry I am coming again with this question but I can't figure out why I can't deploy the contract on chain.

Doing this command:
forge script ./script/DeploySandwich.s.sol --rpc-url <HTTP_RPC> --broadcast --private-key <PRIV_KEY>

And I this result:
Error: You have an active prank. Broadcasting and pranks are not compatible. Disable one or the other

Any help would be appreciated.

Warnings when running cargo run --release --features debug

Summary

When executing the command cargo run --release --features debug, I encounter several warnings.

The first warning pertains to an assigned value that is never read:

warning: value assigned to `weth_inventory` is never read
  --> crates/strategy/src/bot/mod.rs:70:17
   |
70 |         let mut weth_inventory = self.sando_state_manager.get_weth_inventory();
   |                 ^^^^^^^^^^^^^^
   |
   = help: maybe it is overwritten before being read?
   = note: `#[warn(unused_assignments)]` on by default

The second warning highlights that a variable does not need to be mutable:

warning: variable does not need to be mutable
   --> crates/strategy/src/bot/mod.rs:174:13
    |
174 |         let mut sando_bundles = vec![];
    |             ----^^^^^^^^^^^^^
    |             |
    |             help: remove this `mut`
    |
   = note: `#[warn(unused_mut)]` on by default

Test Plan

Follow these steps to reproduce the warnings:

  1. Clone the repository: git clone https://github.com/mouseless-eth/rusty-sando.git
  2. Navigate to the contract directory: cd contract
  3. Install dependencies: forge install
  4. Change to the bot directory: cd ../bot
  5. Copy the example environment file: cp .env.example .env
  6. Run the integration tests using the command: cargo test -p strategy --release --features debug

Compiler run failed: Error (7858)

Error (7858): Expected pragma, import directive or contract/interface/library/struct/enum/constant/function/error definition.
--> lib/foundry-huff/lib/solidity-stringutils/strings.sol:2:1:
|
2 | ./src/strings.sol
| ^

Can anyone help me? Or just tell me what is wrong

Optimize FrontRun [ENHANCEMENT]

The FrontRun Tx using Sando.huff in this repo consumes around 103k gas.

And the state of the art bots use around 86k gas. 17% less.

Ex. https://etherscan.io/tx/0xeeb288abdd22e1f2c26f3f46eef0ca769afb78910a248d3ae9de965f02cdb103

Link to the deployed contract and disassembled byte code used by them - https://library.dedaub.com/ethereum/address/0x6b75d8af000000e20b7a7ddf000ba900b4009a80/disassembled

How do we compare and port the optimizations used in this contrat into sando.huff?

This issue is meant to host the discussion around the optimizations used by sando.huff and other searcher contracts.

All tests fail.

Not issue related.

Please, mouseless-eth, don't close the issue without giving explanations or block us from adding more issues, we are not all born knowing, thanks for sharing your code but if you don't want us to ask, make it private, but don't block us every time we ask or have doubts. Several doubts are repeated among the community and all of them have been closed without leaving any comments about the solution.

The steps we follow are:

1) We deploy the contract using create2 factory
-- Before that, we correctly define the SEARCHER constant in the contract and we get the contract bytecode.

2) We funded the contract with WETH

3) We define all variables in .env correctly
Including SEARCHER_PRIVATE_KEY, FLASHBOTS_AUTH_KEY, SANDWICH_CONTRACT AND INCEPTION BLOCK.

WSS_RPC=ws://localhost:8545
SEARCHER_PRIVATE_KEY=0000000000000000000000000000000000000000000000000000000000000001
FLASHBOTS_AUTH_KEY=0000000000000000000000000000000000000000000000000000000000000002
SANDWICH_CONTRACT=0xaAaAaAaaAaAaAaaAaAAAAAAAAaaaAaAaAaaAaaAa
SANDWICH_INCEPTION_BLOCK=...

4) When running
cargo test -p strategy --release --features debug

We get:

running 4 tests
test can_sandwich_uni_v2 ... FAILED
test can_sandwich_sushi_swap ... FAILED
test can_sandwich_multi_v2_swaps ... FAILED
test can_sandwich_uni_v3 ... FAILED

failures:

---- can_sandwich_uni_v2 stdout ----
thread 'can_sandwich_uni_v2' panicked at 'called `Result::unwrap()` on an `Err` value: [huffsando: REVERT] frontrun: b"\0\0\0"', crates/strategy/tests/main.rs:102:10
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

---- can_sandwich_sushi_swap stdout ----
thread 'can_sandwich_sushi_swap' panicked at 'called `Result::unwrap()` on an `Err` value: [huffsando: REVERT] frontrun: b"\0\0\0"', crates/strategy/tests/main.rs:130:10

---- can_sandwich_multi_v2_swaps stdout ----
thread 'can_sandwich_multi_v2_swaps' panicked at 'called `Result::unwrap()` on an `Err` value: [huffsando: REVERT] frontrun: b"\0\0\0"', crates/strategy/tests/main.rs:163:10

---- can_sandwich_uni_v3 stdout ----
thread 'can_sandwich_uni_v3' panicked at 'called `Result::unwrap()` on an `Err` value: [huffsando: REVERT] frontrun: b"\0\0\0"', crates/strategy/tests/main.rs:191:10


failures:
    can_sandwich_multi_v2_swaps
    can_sandwich_sushi_swap
    can_sandwich_uni_v2
    can_sandwich_uni_v3

We appreciate any ideas or help on how to better identify the error, prior to uploading an issue, we tried to solve it on our own without success.

Thank you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.