DEV Community

Cover image for Watch Each Block Get Created and Defeat Sweepers 🔥

Watch Each Block Get Created and Defeat Sweepers 🔥

Touch of Magic in the Dark Forest of the Blockchain

A Touch of Magic in the Dark Forest of the Blockchain

Blockchain can often feel like traversing a dark forest fraught with challenges, especially when dealing with MEV. It's a realm where every transaction carries risks and rewards. In this article, we delve into strategies to safeguard your ETH from potential threats lurking within this mysterious landscape.

Recently, I encountered a critical security issue that resulted in significant losses from my prized rewards earned during a hackathon. This setback underscored the importance of vigilance and security measures in every project, emphasizing personal responsibility.

Sure, here's a revised version:

Would you like to read more about it? You can do so here.

Turning adversity into opportunity, I embarked on a journey to fortify my defenses against such vulnerabilities. This led me to coding a nice script designed to try to protect the remaining ETH in compromised wallets.

In this guide, we'll explore how this script operates and its pivotal role in safeguarding your ETH effectively.

How This Module Saves Your Remaining ETH

To address the challenge of securing compromised wallets, I developed a script that monitors and transfers ETH to safety when conditions warrant.

Importing and Configuring Dependencies

import { utils, Wallet, providers } from 'ethers'
import { gasPriceToGwei } from '../lib/converter.lib'
require('dotenv').config()

const { formatEther } = utils

const SAFE_WALLET = process.env.SAFE_WALLET as string
const RPC_URL = process.env.RPC_URL as string
const provider = new providers.JsonRpcProvider(RPC_URL)
const thresholdToTransfer = '0.01'

if (!SAFE_WALLET || !RPC_URL) {
  throw new Error(
    'SAFE_WALLET and RPC_URL must be set in the environment variables.'
  )
}

console.log('Safe address: ', SAFE_WALLET)
Enter fullscreen mode Exit fullscreen mode
  • Dependencies: Imports necessary functions and classes from the ethers library to interact with the Ethereum blockchain.
  • Environment Variables: Loads environment variables like SAFE_WALLET and RPC_URL for configuration.

Monitoring and Safe Transfer Function

export const monitoringAndSafe = async (burnWallet: Wallet) => {
  try {
    const threshold = utils.parseEther(thresholdToTransfer)
    const balance = await burnWallet.getBalance()
    if (balance.isZero()) {
      console.log('Balance is zero')
      return
    }

    const gasPrice = await provider.getGasPrice()
    const gasLimit = 21000

    console.log(`Gas price: ${gasPriceToGwei(gasPrice)} gwei`)

    const gasCost = gasPrice.mul(gasLimit).mul(12).div(10)

    if (balance.lt(gasCost)) {
      console.log(
        `Insufficient funds for gas (balance=${formatEther(
          balance
        )} ETH, gasCost=${formatEther(gasCost)} ETH)`
      )
      return
    }

    if (balance.gt(threshold)) {
      const safeValue = balance.sub(gasCost)
      console.log(`safeValue: ${formatEther(safeValue)} ETH`)

      try {
        console.log(`Transferring ${formatEther(safeValue)} ETH to safe wallet`)
        const nonce = await provider.getTransactionCount(
          burnWallet.address,
          'latest'
        )
        const tx = await burnWallet.sendTransaction({
          to: SAFE_WALLET,
          gasLimit,
          gasPrice,
          nonce,
          value: safeValue,
        })
        console.log(
          `Transaction sent with nonce ${tx.nonce}, transferring ${formatEther(
            safeValue
          )} ETH at gas price ${gasPriceToGwei(gasPrice)}`
        )
        console.log(
          `Safe wallet balance: ${
            SAFE_WALLET && formatEther(await provider.getBalance(SAFE_WALLET))
          } ETH`
        )
      } catch (err: any) {
        console.log(`Error sending transaction: ${err.message ?? err}`)
      }
    } else {
      console.log(
        `Balance is below threshold: ${utils.formatEther(balance)} ETH`
      )
    }
  } catch (error) {
    console.error('Error in monitoringAndSafe function:', error)
  }
}
Enter fullscreen mode Exit fullscreen mode

Detailed Explanation

  • Threshold Check: Verifies if the wallet's balance meets a predefined threshold before initiating any transfer.
  • Gas Price Calculation: Fetches the current gas price and calculates the gas cost required for transactions.
  • Transaction Execution: Sends ETH from the compromised wallet to a designated safe wallet, ensuring sufficient balance for gas fees.

This script offers a proactive approach to protecting your ETH by automatically transferring funds to safety when conditions are met. It serves as a vital defense mechanism against potential threats in the blockchain ecosystem.

In conclusion, safeguarding your assets in the blockchain realm requires vigilance and proactive measures. By leveraging tools like this script, you can mitigate risks and ensure the security of your crypto assets.


We must remember that this is not an infallible script "even though Mighty Wolfcito has used it in his wallet before", but it could give you a good advantage against sweepers, and by using it, you are assuming the inherent risks associated with it.

By implementing this script, you can monitor and safeguard your ETH, mitigating risks associated with compromised wallets. Embrace the power of blockchain security and protect your assets with every transaction.

Top comments (0)