Welcome to the Matrix of blockchain
How to get alerted *before* getting hacked and prevent it
Defi hacks alone have totaled $285M just since 2019. Let's take the Balancer hack for example. The hack was exploiting the fact that a pool with a deflationary token STA (Statera) was created. The pool accumulated a significant liquidity when it was eventually drained by the hack. Read my post on Balancer for more details here on Balancer itself.
Now the special thing about the STA token is that some percentage of the supply is burnt when you transfer it. Unfortunately Balancer didn't double-check the received balances and was assuming when you transfer amountA, you also receive amountA. When taking this to the extreme and repeating, one can create the situation where when trading with the pool, no STA has to be transferred for a swap. Now use a flash loan, repeat and profit.
This resulted in the following transaction:

Now you can see this was a single transaction which resulted in roughly $500K being lost.
Many tokens were transferred in a single transaction. But was there any way to prevent this?

Well this is what we'll talk about. Yes indeed this hack could have been stopped!
It's still very dark inside the mempool
You may remember the great blogpost about mempool manipulation on Black Thursday of Blocknative. If not, bookmark this now and read it. This issue is still very relevant. In fact one of the exploits used is still an open issue on Github and largely ignored. Since then we've heard many more stories about the mempool, sometimes nicknamed dark forest and how to escape it.
Illuminating this place is not easy. You can run a node like Geth and observe your local mempool. You can also see the mempool source code of Geth here. It gives you some ideas on the behavior. Or you could even create your own node and transaction discovery service with something like ethereumjs-devp2p. But you can already see that this is not only very difficult to do, requiring a lot of computing resources and time, but it's also incredibly difficult to do well.
A mempool is only existing of transactions that the nodes you connected to have seen and told you about. To get a full picture of the whole network's mempool therefore requires being connected to as many nodes as possible. The more nodes we are connected to, the earlier we will be notified of new mempool transactions. Now this is where Mempool Explorer from Blocknative comes to help.

The service of Blocknative goes beyond this:
- You could actually use the backend API behind this directly.
- Use the notify frontend lib to greatly improve your DAPP's user experience.
- Or simulate pending transactions. This is what we need for our hack preventation.
Entering the Matrix

Now how does the simulation feature work?
The simulations build upon the mempool service. In general dealing with internal transactions is difficult. Recall our Balancer hack transaction. In the advanced internal transactions tab, you can see the full monstrosity of transactions here. Now imagine you want to keep track of any calls to your smart contract off-chain. This is extremely difficult as you'd also have to find all internal transactions which you can only get by simulating the whole transaction.
Simulations by Blocknative basically take any pending transaction and run it in its their local EVM. They are run using the last known state of the blockchain (state trie). Since the state can change before the transaction is actually added to a block, the simulation is not always 100% accurate, so keep that in mind.
Also note that simulations currently only work for Ethereum mainnet.
Uniswap Example
A good way to visualize this is by looking at the Uniswap simulation examples. Create a Blocknative account and then go to this example query.
You can see an example result on the right. You can click the hash and it will direct you to Etherscan. Since this is a pending transaction, you might have to wait a few minutes for the transaction to be confirmed.
Once finished, you can see the actual token transferred by this Uniswap trade:

It likely won't match the Blocknative balanceChanges perfectly due to the constantly changing states in a Uniswap pool. You can see here instead of 10174 TRU tokens paid to the trader, it actually sent 10346 TRU. Close enough!

Simulations are challenging
The simulations are particularly useful for traders and protocols. They reveal all internal calls and its effects on the state. However, with the current node client implementations, this process can take substantially longer than the actual EVM execution. This time can often be the difference between doing a trade in time or preventing a hack.
To take it from Blocknative directly, the challenges for simulations include:
- Ensuring your node remains properly synced at the time of simulation.
- Capturing all pending transactions propagating through the mempool. Individual nodes frequently miss pending transactions, particularly during periods of network congestion.
- Detecting new pending transactions as rapidly as possible.
- Knowing which transactions are likely to be included in the next block – and thus are candidates to be simulated against the current block state.
- Performing the simulation quickly to maximize the time the simulation results are actionable.
- Interpreting the simulation to see how address balances are shifting.
Getting notified about the hack
Now how can we use this to prevent hacks?
Let's create a subscription for the Balancer STA pool.

- Now we can create a query. Also what about if the transaction is split over multiples? -
When you're finished, you have the option to add this to a webhook. Now you'll be alerted whenever such a transaction was found!

Of course creating these subscriptions can all be automated using the API. The 'Export Configuration' function can help you with the setup for this.
Let's prevent the hack...
Okay so now we are getting alerted about any hacks. What do we do now?
Well you have to respond quickly. And your contracts need to be designed to have some kind of emergency pause. One common pattern is to use the Openzeppelin Pausable contract. Make any function pausable except for some emergency withdrawal function. The emergency pause can only be called by a single private key. If you were to use Governance for this, you wouldn't be able to respond quickly enough. Now when the contracts are paused, users may only withdraw their funds in a safe way.
Awesome, we just prevented the hack. Get alerted about a big balance change, automatically call emergency pause and then let users safely withdraw funds.
Any downsides?
Well. There ain't no such thing as a free lunch. Of course we are giving up decentralization to some degree. Having the option to pause a contract by a single address goes against the spirit of decentralization. But there are ways to improve on this:
- Use this pausing ability only for the most critical parts of the protocol.
- Add some kind of auto-resume function when it makes sense. This way the owner can't pause indefinitely. For example the pause could be only for 14 days, giving users time to withdraw and then it automatically resumes.
And last but not least, add the option to remove the pausing feature later on when you feel the contracts are sufficiently battle-tested.
Solidity Developer
More great blog posts from Markus Waas
How to use ChatGPT with Solidity
Using the Solidity Scholar and other GPT tips
How to integrate Uniswap 4 and create custom hooks
Let's dive into Uniswap v4's new features and integration
How to integrate Wormhole in your smart contracts
Entering a New Era of Blockchain Interoperability
Solidity Deep Dive: New Opcode 'Prevrandao'
All you need to know about the latest opcode addition
How Ethereum scales with Arbitrum Nitro and how to use it
A blockchain on a blockchain deep dive
The Ultimate Merkle Tree Guide in Solidity
Everything you need to know about Merkle trees and their future
The New Decentralized The Graph Network
What are the new features and how to use it
zkSync Guide - The future of Ethereum scaling
How the zero-knowledge tech works and how to use it
Exploring the Openzeppelin CrossChain Functionality
What is the new CrossChain support and how can you use it.
Deploying Solidity Contracts in Hedera
What is Hedera and how can you use it.
Writing ERC-20 Tests in Solidity with Foundry
Blazing fast tests, no more BigNumber.js, only Solidity
ERC-4626: Extending ERC-20 for Interest Management
How the newly finalized standard works and can help you with Defi
Advancing the NFT standard: ERC721-Permit
And how to avoid the two step approve + transferFrom with ERC721-Permit (EIP-4494)
Moonbeam: The EVM of Polkadot
Deploying and onboarding users to Moonbeam or Moonriver
Advanced MultiSwap: How to better arbitrage with Solidity
Making multiple swaps across different decentralized exchanges in a single transaction
Deploying Solidity Smart Contracts to Solana
What is Solana and how can you deploy Solidity smart contracts to it?
Smock 2: The powerful mocking tool for Hardhat
Features of smock v2 and how to use them with examples
How to deploy on Evmos: The first EVM chain on Cosmos
Deploying and onboarding users to Evmos
EIP-2535: A standard for organizing and upgrading a modular smart contract system.
Multi-Facet Proxies for full control over your upgrades
MultiSwap: How to arbitrage with Solidity
Making multiple swaps across different decentralized exchanges in a single transaction
The latest tech for scaling your contracts: Optimism
How the blockchain on a blockchain works and how to use it
Ultimate Performance: The Aurora Layer2 Network
Deploying and onboarding users to the Aurora Network powered by NEAR Protocol
What is ecrecover in Solidity?
A dive into the waters of signatures for smart contracts
How to use Binance Smart Chain in your Dapp
Deploying and onboarding users to the Binance Smart Chain (BSC)
Using the new Uniswap v3 in your contracts
What's new in Uniswap v3 and how to integrate Uniswap v3
What's coming in the London Hardfork?
Looking at all the details of the upcoming fork
The Ultimate Ethereum Mainnet Deployment Guide
All you need to know to deploy to the Ethereum mainnet
SushiSwap Explained!
Looking at the implementation details of SushiSwap
Solidity Fast Track 2: Continue Learning Solidity Fast
Continuing to learn Solidity fast with the advanced basics
What's coming in the Berlin Hardfork?
Looking at all the details of the upcoming fork
Using 1inch ChiGas tokens to reduce transaction costs
What are gas tokens and example usage for Uniswap v2
Openzeppelin Contracts v4 in Review
Taking a look at the new Openzeppelin v4 Release
EIP-3156: Creating a standard for Flash Loans
A new standard for flash loans unifying the interface + wrappers for existing ecosystems
Tornado.cash: A story of anonymity and zk-SNARKs
What is Tornado.cash, how to use it and the future
High Stakes Roulette on Ethereum
Learn by Example: Building a secure High Stakes Roulette
How to implement generalized meta transactions
We'll explore a powerful design for meta transactions based on 0x
Utilizing Bitmaps to dramatically save on Gas
A simple pattern which can save you a lot of money
Using the new Uniswap v2 as oracle in your contracts
How does the Uniswap v2 oracle function and how to integrate with it
Smock: The powerful mocking tool for Hardhat
Features of smock and how to use them with examples
How to build and use ERC-721 tokens in 2021
An intro for devs to the uniquely identifying token standard and its future
Trustless token management with Set Protocol
How to integrate token sets in your contracts
Exploring the new Solidity 0.8 Release
And how to upgrade your contracts to Solidity 0.8
How to build and use ERC-1155 tokens
An intro to the new standard for having many tokens in one
Leveraging the power of Bitcoins with RSK
Learn how RSK works and how to deploy your smart contracts to it
Solidity Fast Track: Learn Solidity Fast
'Learn X in Y minutes' this time with X = Solidity 0.7 and Y = 20
Sourcify: The future of a Decentralized Etherscan
Learn how to use the new Sourcify infrastructure today
Integrating the 0x API into your contracts
How to automatically get the best prices via 0x
How to build and use ERC-777 tokens
An intro to the new upgraded standard for ERC-20 tokens
COMP Governance Explained
How Compound's Decentralized Governance is working under the hood
How to prevent stuck tokens in contracts
And other use cases for the popular EIP-165
Understanding the World of Automated Smart Contract Analyzers
What are the best tools today and how can you use them?
A Long Way To Go: On Gasless Tokens and ERC20-Permit
And how to avoid the two step approve + transferFrom with ERC20-Permit (EIP-2612)!
Smart Contract Testing with Waffle 3
What are the features of Waffle and how to use them.
How to use xDai in your Dapp
Deploying and onboarding users to xDai to avoid the high gas costs
Stack Too Deep
Three words of horror
Integrating the new Chainlink contracts
How to use the new price feeder oracles
TheGraph: Fixing the Web3 data querying
Why we need TheGraph and how to use it
Adding Typescript to Truffle and Buidler
How to use TypeChain to utilize the powers of Typescript in your project
Integrating Balancer in your contracts
What is Balancer and how to use it
Navigating the pitfalls of securely interacting with ERC20 tokens
Figuring out how to securely interact might be harder than you think
Why you should automatically generate interests from user funds
How to integrate Aave and similar systems in your contracts
How to use Polygon (Matic) in your Dapp
Deploying and onboarding users to Polygon to avoid the high gas costs
Migrating from Truffle to Buidler
And why you should probably keep both.
Contract factories and clones
How to deploy contracts within contracts as easily and gas-efficient as possible
How to use IPFS in your Dapp?
Using the interplanetary file system in your frontend and contracts
Downsizing contracts to fight the contract size limit
What can you do to prevent your contracts from getting too large?
Using EXTCODEHASH to secure your systems
How to safely integrate anyone's smart contract
Using the new Uniswap v2 in your contracts
What's new in Uniswap v2 and how to integrate Uniswap v2
Solidity and Truffle Continuous Integration Setup
How to setup Travis or Circle CI for Truffle testing along with useful plugins.
Upcoming Devcon 2021 and other events
The Ethereum Foundation just announced the next Devcon in 2021 in Colombia
The Year of the 20: Creating an ERC20 in 2020
How to use the latest and best tools to create an ERC-20 token contract
How to get a Solidity developer job?
There are many ways to get a Solidity job and it might be easier than you think!
Design Pattern Solidity: Mock contracts for testing
Why you should make fun of your contracts
Kickstart your Dapp frontend development with create-eth-app
An overview on how to use the app and its features
The big picture of Solidity and Blockchain development in 2020
Overview of the most important technologies, services and tools that you need to know
Design Pattern Solidity: Free up unused storage
Why you should clean up after yourself
How to setup Solidity Developer Environment on Windows
What you need to know about developing on Windows
Avoiding out of gas for Truffle tests
How you do not have to worry about gas in tests anymore
Design Pattern Solidity: Stages
How you can design stages in your contract
Web3 1.2.5: Revert reason strings
How to use the new feature
Gaining back control of the internet
How Ocelot is decentralizing cloud computing
Devcon 5 - Review
Impressions from the conference
Devcon 5 - Information, Events, Links, Telegram
What you need to know
Design Pattern Solidity: Off-chain beats on-chain
Why you should do as much as possible off-chain
Design Pattern Solidity: Initialize Contract after Deployment
How to use the Initializable pattern
Consensys Blockchain Jobs Report
What the current blockchain job market looks like
Provable — Randomness Oracle
How the Oraclize random number generator works
Solidity Design Patterns: Multiply before Dividing
Why the correct order matters!
Devcon 5 Applications closing in one week
Devcon 5 Applications closing
Randomness and the Blockchain
How to achieve secure randomness for Solidity smart contracts?