ByAUJay
Flash Loan Prevention: Best Practices for DeFi Protocols
In the world of DeFi, flash loans can be a double-edged sword. On one hand, they offer incredible flexibility and opportunities for traders, but on the other, they can lead to some serious vulnerabilities if not managed properly. Here are some effective strategies to help protect your protocol from flash loan exploits.
1. Use Time-Locked Transactions
Time-locked transactions can act as a safety net. By requiring a certain amount of time to pass before a transaction can be executed, you can help mitigate flash loan attacks:
- Delayed Execution: This gives your smart contracts a crucial window to check the legitimacy of the transaction.
- Vulnerability Checks: Before executing, you can also check for any abnormal activity or patterns.
2. Implement Circuit Breakers
Circuit breakers are your go-to for temporarily halting activities in your protocol when you detect something fishy. Here’s how to implement them:
- Automatic Detection: Set triggers for unusual trading volumes or price movements.
- Manual Overrides: Allow governance participants to pause operations if they spot a potential exploit.
3. Incorporate Liquidation Mechanisms
Establishing solid liquidation mechanisms can discourage attackers from trying flash loan exploits. A well-designed liquidation process:
- Provides Incentives: Ensure that there's a strong incentive for users to maintain healthy collateral ratios.
- Encourages Participation: Let users know that they can step in and help liquidate positions when necessary, which adds a layer of community involvement.
4. Limit Maximum Borrowing Amounts
Setting limits on how much can be borrowed in a single flash loan can greatly reduce risk. You might consider:
- Tiered Limits: Different amounts based on user reputation or history with the protocol.
- Dynamic Adjustments: Setting limits that can change in real time based on market conditions.
5. Monitor On-Chain Activity
Keeping an eye on on-chain activities provides valuable insights into the health of your protocol. You can use:
- Analytics Tools: Leverage platforms like Dune Analytics or Nansen to identify trends.
- Custom Alerts: Set up alerts for unusual transaction patterns or spikes in activity that could indicate an attack in progress.
6. Conduct Regular Audits
Regular audits are a must! Even the best protocols can have unexpected vulnerabilities. Make sure to:
- Engage with Experts: Bring in third-party auditors who specialize in smart contracts.
- Community Involvement: Encourage community bug bounties to ensure thorough testing.
Conclusion
Flash loans can indeed be risky, but with the right preventive measures, DeFi protocols can protect themselves and their users. By implementing practices like time-locked transactions, circuit breakers, and monitoring on-chain activity, you can create a more secure environment for everyone involved.
Stay vigilant and keep innovating!
the concrete headache you’re living with
- You’re probably relying on AMM spot reads or those short TWAPs that can easily be adjusted for a few blocks. With Proof of Stake, validators have control over multiple consecutive blocks, which makes it easier than you might think to mess with multi-block TWAPs. Uniswap actually breaks down how the cost of manipulating TWAPs drops as the number of controlled blocks increases. Check it out here.
- If your L2 deployments aren’t keeping an eye on the sequencer’s uptime, that’s a risky move. When Optimism, Base, or Arbitrum sequencers hit a stall, stale oracle reads can lead to some serious trouble, like triggering invalid liquidations or doling out under/over-collateralized loans. You can read more about this here.
- We still have those single-transaction economic actions hanging around (you know, deposit→borrow, stake→mint, vote→execute). If they share an oracle or path with the target action, a flash loan can allow attackers to pivot the state and settle everything in the same transaction.
- Governance is snapshotting "now," rather than "at the start of the proposal." This is exactly how Beanstalk got drained: a flash loan was taken out, voting power was acquired, an emergency proposal was passed, funds were drained, and then the loan was repaid--all in one neat package. You can dive deeper into this here.
- Lastly, those caps and circuit breakers? They’re either non-existent or pretty soft. Lending markets without specific supply or borrow caps per asset and price deviation guards have faced some massive losses (like 8-figure ones) through oracle or parameter manipulation, all thanks to that flash liquidity. More on this can be found here.
The Real Risk if You Keep Shipping Like This
- Loss severity: In 2024, we saw around $2.2 billion stolen across 303 incidents. Then in 2025, things took a turn for the worse, with losses skyrocketing month over month. February alone hit about $1.53 billion, and flash-loan-driven oracle manipulation (like the incident with UwU Lend, which lost $20 million) remains one of the main culprits. (chainalysis.com)
- Missed GTM windows: Just one incident can set you back weeks on things like forensic triage, liquidity recovery, community votes, and patch cycles. Everything slows down--listings get put on hold, market maker spreads widen, and partners may hit pause on integrations.
- Premiums & cost of capital: When it comes to risk providers and insurers, you’re priced based on how well your protocol controls are set up. If you’ve got weak oracle paths or if there's no auto-pause feature, expect your premiums to double. And market makers? They’ll widen spreads if they see potential price exploits.
- L2-specific hazards: Downtime from sequencers plus stale feeds can create a ticking time bomb for liquidations. If you’re overlooking Chainlink’s Sequencer Uptime Feeds, you might just turn an outage into a bad-debt situation. (docs.chain.link)
- Opportunity cost: Things like “EOA-only” checks or simplistic per-block limits aren’t stopping flash loans and actually mess with composability. Even worse, they can give you a false sense of security while attackers quietly route through relays and smart wallets. Best-practice documentation has been cautioning against tx.origin-style gates for years. (docs.solidity.org)
7Block Labs’ Flash-Loan Hardening Methodology (Technical But Pragmatic)
We’ve got a robust layered defense that turns single-transaction profits into a math problem that just doesn’t add up. Plus, we make sure your gas budgets stay predictable and the user experience remains smooth.
1) Oracle and Price-Path Hardening
- Replace spot reads with solid TWAPs and medianization:
- Go for Uniswap v3’s
observe()for geometric TWAP instead of using those configurable windows; just skip directly reading reserves. Make sure you keep enough observations to stretch out the horizon. Check out the details here. - Tune your TWAP window based on how deep the pool liquidity is. You can figure out the cost of attacks using liquidity/tick math and market-impact models, like Apostro's approach. We adjust the windows so that the cost of manipulation is greater than the potential gains when you factor in fees and arbitrage. More info on that can be found here.
- Go for Uniswap v3’s
- Add L2 Sequencer checks to every price read on rollups:
- Utilize Chainlink Sequencer Uptime Feeds to ensure everything stays in sync. Be sure to implement a grace period after any downtime to dodge those pesky stale data liquidations. You can read up on this here.
- Opt for medianized, delayed, or optimistic oracles when it makes sense:
- Maker’s OSM brings in a controlled delay and stoppable updates. This is super handy for any governance changes and liquidation paths. Check it out here.
- UMA’s Optimistic Oracle offers liveness windows and dispute bonds for event-based prices. We roll this out when you need human or economic dispute resolution. More details are available here.
- Low-latency market data without sacrificing trust:
- Chainlink Data Streams deliver reports in under a second with on-chain verification. You can integrate these with commit-reveal paths to minimize MEV/OEV while still keeping things verifiable. Dive into it here.
- ZK-verified historical pricing:
- Want to do some manipulation-resistant checks without on-chain caching? We can verify Uniswap v2/v3 TWAPs for any historical windows using Axiom, which proves storage reads on-chain. This means you can have “checkpoint-free” historical guards and selective proofs for when it’s worth it economically. Learn more about it here.
2) Transaction-Level "Flash-Unfriendly" State Transitions
- Cross-Block Commits for Sensitive Flows:
We’ve got a neat trick to help out with sensitive flows by splitting actions like “affect‑price” and “consume‑price” across different blocks. So, picture this: you take a deposit snapshot in block N and then borrow after block N+1, using a Time-Weighted Average Price (TWAP) that’s calculated over the period from [N−K, N]. This approach really helps break those pesky atomic attack loops and makes sure there’s some market exposure going on.
- EIP-1153 Transient Storage Sentinels:
When it comes to actions that shouldn’t happen at the same time in a single transaction (like depositing and borrowing in the same call graph), we’ve got transient locks on the scene. These locks reset right after the transaction ends and cost us just 100 gas per TSTORE/TLOAD--way cheaper than the SSTORE-based ones. If you’re using Solidity 0.8.24 or later, you can tap into TSTORE/TLOAD through inline assembly. Plus, with the Dencun update on March 13, 2024, EIP-1153 has now been activated on mainnet! Check out more on this over at soliditylang.org.
Example (sketch):
- When diving into the deposit logic, let’s set a temporary “phase” flag. If that flag is on in the same transaction, we’ll block any borrowing paths. Don’t worry, this flag clears itself at the end of the transaction, which helps us avoid those pesky SSTORE refunds and gas spikes. By the way, the compiler gives us a heads-up on TSTORE usage--our audits include invariant tests to keep everything in check. (soliditylang.org)
- Governance flash-resistance:
- Let’s leverage ERC20Votes/IVotes snapshotting to grab voting power right when a proposal kicks off. Plus, we’ll add some timelocks before execution. This way, we’re cutting out those “buy votes now” opportunities. (docs.openzeppelin.com)
3) Protocol-Level Kill-Switches and Boundaries
- Circuit Breakers and Deviation Checks:
- We can hit pause on exchanges and mints if prices swing too much beyond set thresholds or if the difference between TWAP and spot prices goes over defined limits. This method has been tried and tested in the Synthetix SIP-55/65 designs. (Check it out here)
- Lending Market Caps:
- It’s crucial to set supply and borrow caps for each asset, along with isolation and debt ceilings (think Aave v3 style), and develop governance playbooks to tweak these caps safely. This approach helps minimize risks if an oracle goes off course. (Learn more here)
4) Real-time Detection, Automated Response, and Runbooks
- Forta + Defender (or OpenZeppelin Monitor) for MTTD under minutes:
- Stay ahead of the game by subscribing to flash-loan detection, an attack-detector combo, alerts for odd borrowing or minting bots, and custom price-deviation notifications. Make sure to connect it to auto-pause through Sentinel/Relayer/Autotask. You can find more details here.
- Response Automation:
- When things go south--like if the Sequencer goes down, the price deviates by more than X%, or if there's a cross-pool skew greater than Y bps--immediately trigger a partial pause and tighten those caps. Just remember, a governance review is needed before you unpause. Get all the specifics here.
5) Gas Optimization Without Sacrificing Safety
- Keep oracles secure while managing gas costs:
- Whenever you can, opt for
observe()instead ofobservations; cache those immutable addresses; make use ofcalldata; batch those oracle reads; and useMCOPYalong with transient storage when it fits. Thanks to the post-Berlin gas model and EIP-1153, keeping per-transaction guards affordable is a breeze--just 100 gas forTLOAD/TSTOREcompared to thousands for regular storage writes. (fvictorio.github.io)
- Whenever you can, opt for
- Plan those cost envelopes for TWAP windows: Going for longer windows increases the manipulation cost linearly based on liquidity and time, but it also bumps up the gas cost just a bit--so it's smart to calibrate each pool using simulation traces. (docs.uniswap.org)
- L2 oracle guard (Sequencer + TWAP sanity)
- Only read the Chainlink price if the Sequencer is up and the grace period has passed; if not, just revert or use a long-window TWAP as a backup.
- Set the GRACE_PERIOD_TIME based on each asset's volatility (like 30-60 minutes) and make sure to enforce certain minimum liquidity and TVL requirements for any DEX pool used in the fallback. (docs.chain.link)
- “Same-tx” flash-guard with EIP-1153
- Add a transient phase flag for deposit() and mint(), so if borrow()/redeem() tries to execute in the same transaction graph, it just reverts. This pattern is great for gas efficiency and resets itself automatically; it works alongside, rather than replacing, cross-block commits. (soliditylang.org)
- Example C -- Governance snapshots + timelock
- Shift governance voting to ERC20Votes snapshots and enforce a timelock (like 24-48 hours) before anything gets executed. Also, don’t allow proposals to go through if the oracle circuit breaker is active. This would’ve stopped those Beanstalk-style emergency executions that used flash-borrowed voting power. (docs.openzeppelin.com)
- Example D -- ZK-verified historical TWAP
- Before any big liquidation happens, require a ZK-verified TWAP proof for [t1, t2] from Axiom to control the behavior. If the proof fails or strays too far from the medianized feeds beyond a certain threshold, then just pause the liquidation process. (blog.axiom.xyz)
- Example E -- Lending caps and isolation
- Set up supply and borrow caps, along with isolation for new collaterals. Make those cap changes dependent on oracle health metrics and liquidity depth. This approach syncs nicely with Aave-style methods to help minimize guesswork in governance. (governance.aave.com)
Emerging Best Practices We're Standardizing in 2026 Builds
- “Flash‑unfriendly” accrual mechanics: We’re looking at delaying those reward and price-per-share effects across blocks. Instead of settling interest or distributions right away, we’ll do it after the oracle windows have been confirmed. This should make things a bit more stable.
- OEV/SVR integration: With Chainlink's Smart Value Recapture, you can sync your oracle updates with your protocol. This helps claw back some MEV and cuts down on those pesky incentives for manipulation during liquidation ticks. Check out the details here.
- TWAP windows informed by validator set dynamics: Research from Uniswap has shown how cost curves relate to block control. On chains where validator schedules are known, it might make sense to either extend those windows or require non-adjacent sampling. This can really help raise costs effectively. Dive into their findings here.
What We Measure (GTM Metrics That Matter)
- Price-Path Robustness
To keep things stable, we want the minimum economically viable manipulation cost (EMC) to be at least three times the maximum profit from a single transaction for every asset pair we support. We figure out EMC based on pool liquidity, fee tiers, and how long our TWAP window is, all backed up with simulations. You can dive deeper into this here. - Oracle Reliability on L2
We’ve managed to avoid any unintended liquidations during sequencer outages, and we're doing our part by ensuring grace periods are enforced 100%. Plus, we only allow price-consuming paths that have passed uptime checks. Check out the details here. - Incident Response
Our mean time to detect (MTTD) issues is under 2 minutes, thanks to Forta/Monitor. When it comes to responding, we can partially pause within 5 minutes using automated Relayer playbooks, and if we need a human to step in for unpausing, we’ve got a service level agreement (SLA) in place for under 6 hours. More about that can be found here. - Loss-Containment
We’ve set up supply and borrow caps to make sure that the maximum loss per new market is no more than N% of the protocol’s total value locked (TVL). For riskier assets, we implement isolation mode until certain oracle depth criteria are met--these are based on TVL and volume thresholds. You can read more about it here. - Gas Optimization
We’ve designed our oracles to stay within a ±3-5% gas variance compared to the baseline. By using transient storage sentinels instead of storage-based flags, we've managed to cut down the costs for each transaction to around 100 gas reads and writes. Learn more about this here.
How 7Block Labs Gets Things Done (End-to-End)
- Architecture & Threat Modeling: We carefully chart out every price path and state transition. Then, we calculate the EMC and run simulations for multi-block attacks (including those pesky validator-controlled sequences).
- Oracle Policy and Implementation: We’ve got our hands on the Uniswap v3 TWAP libraries, set up Chainlink Data Streams, and integrated Maker-style OSM delays. We also incorporate UMA liveness when necessary, plus Axiom-backed ZK proofs for those important historical checks. You can dive into the details here.
- Protocol Controls: We're all about keeping things safe, so we implement circuit breakers, isolation measures, caps, and EIP-1153 sentinels. Everything is backed by Foundry tests and fuzzing harnesses that are linked to specific invariants. Check out more on this blog.
- Monitoring & Response: We set up Forta/Monitor to automatically pause playbooks, create escalation channels, and have post-mortem templates ready to go--all while making sure we meet partner and listing requirements. Want to know more? Visit here.
Where to Start with Us
- Security-first oracle and price-path review: We’ve got your back! We replace those fragile reads and add L2 sequencer gates without putting the brakes on your roadmap. Check out what we've cooked up in our smart contract and risk-focused builds through our smart contract and DeFi practices:
- Smart contract development and audits: Explore our smart contract development and security audit services to ensure everything runs smoothly.
- DeFi protocol engineering: Dive into our DeFi development services and DEX development services to take your projects to the next level.
- Cross-chain and oracle integrations: Check out our cross-chain solutions development and blockchain integration services to link it all up seamlessly.
- End-to-end delivery: We offer comprehensive web3 development services and a wider range of blockchain development services to see your projects through from start to finish.
Brief in-depth details (what you’ll see in the PRs)
- Oracle adapters:
- We’re rolling out Uniswap v3 TWAP readers that use an observe-based approach, complete with limits on how much the max tick can change during each window and checks for pool TVL/volume. You can learn more about it here.
- Chainlink is stepping up with sequencer-gated price readers that include GRACE_PERIOD_TIME and guards against stale rounds. Check out the details here.
- Governance:
- We’re introducing an ERC20Votes-based token that brings in snapshots and a timelock for execution. Plus, if the price circuit breaker gets tripped, the execution will just refuse to go through. Read more about it here.
- Protocol controls:
- There’s a Synthetix-style price deviation circuit breaker coming in. It’s all parameterized based on asset volatility, oracle latency, and liquidation thresholds. You can dive deeper into it here.
- We’re also adding Aave-style caps and isolation features. The cap adjustments will be gated by oracle health and liquidity metrics, and you can learn more about it here.
- Gas posture:
- We’re implementing transient storage sentinels (EIP-1153) to block same-transaction action bundles that use up minimal gas, along with MCOPY for memory operations wherever it makes sense. For more info, check this link.
- ZK integrations:
- The Axiom proof requests are now verifying historical storage reads for TWAP sanity, which means we’re enabling permissionless and resistance to manipulation during liquidation. Get the full scoop here.
Why This Works
- This approach directly tackles the three main factors that influence flash-loan profitability: controlling price paths, keeping state coupling within a single transaction, and managing response latency. By doing this, your protocol becomes tough to manipulate, hard to finalize atomically, and super quick to pause if any signals get tripped.
- It mirrors what’s actually going down from 2024 to 2026: the reality of validator control windows, the dynamics of L2 sequencers, the recapture of OEV, Dencun's transient storage, and ZK-verified data access--moving beyond those outdated PoW-era assumptions. Check it out here: (blog.uniswap.org)
CTA for DeFi ICP
Let's chat! Book a quick 15-minute scoping call with us.
Like what you're reading? Let's build together.
Get a free 30-minute consultation with our engineering team.
Related Posts
ByAUJay
Creating a Yield Aggregator for RWA Tokens: A Step-by-Step Guide
### Summary So, you’re looking to create a serious RWA yield aggregator in 2026? Well, things have definitely stepped up a notch technically! You'll need to manage a few crucial elements like ERC‑4626/7540 vault flows, permissioned token standards (ERC‑3643/1404), NAV and reserve oracles, and cross‑chain DvP. It’s going to be a challenging but exciting ride!
ByAUJay
Building 'Policy-Based' DeFi Wallets for Corporate Treasuries When it comes to managing corporate funds, efficiency and security are top priorities. That's where 'policy-based' DeFi wallets come in. These wallets not only allow businesses to tap into decentralized finance but also ensure there's a robust framework in place to manage their assets according to specific guidelines. What exactly do we mean by 'policy-based'? Well, it's all about tailoring the wallet's functionality to fit the unique needs of a company's treasury operations. With these kinds of wallets, companies can set rules and policies that dictate how funds are accessed, spent, and invested. So, if you're worried about security or compliance, these wallets can be a big help. These wallets can be designed to handle everything from regular transactions to more complex financial maneuvers, like yield farming or liquidity provision. Plus, the ability to automate certain processes means that businesses can save time and reduce the risk of human error. In a nutshell, 'policy-based' DeFi wallets are game-changers for corporate treasuries. They provide a smart, efficient way to manage crypto assets while keeping everything in check with rules that align with the company's financial strategy. It's a win-win!
**Summary:** Hey there! Corporate treasuries now have a great opportunity to explore the world of DeFi with some robust controls. Thanks to EIP-7702 smart accounts, along with policy modules like ERC-7579 and ERC-6900, they can ensure everything runs smoothly. Plus, with features like MPC signing, on-chain sanctions checks, and Travel Rule workflows, security is top-notch. This guide is here to take you through how 7Bl can help make it all happen!
ByAUJay
The 'Dual-Market' DeFi Setup: Merging Speed with Flexibility
**Summary:** A lot of DeFi stacks make you choose between super-fast execution and a whole bunch of features. But with a Dual‑Market architecture, you don’t have to pick one over the other anymore! It combines a low-latency “Fast Market” for quick trades with an intent-driven “Flexible Market” that offers versatility, bringing them together in a seamless way.

