DeFi Protocol Development with Security Audit and Gas Optimization

We design and develop full-cycle blockchain solutions: from smart contract architecture to launching DeFi protocols, NFT marketplaces and crypto exchanges. Security audits, tokenomics, integration with existing infrastructure.
Showing 1 of 1All 1305 services
DeFi Protocol Development with Security Audit and Gas Optimization
Complex
from 2 weeks to 3 months
Frequently Asked Questions

Blockchain Development Services

Blockchain Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1349
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1247
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    949
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1183
  • image_logo-advance_0.webp
    B2B Advance company logo design
    642
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    921

DeFi Protocol Development

A team launches a lending protocol inspired by Aave v3. During testing, everything works. After deployment on mainnet, within 48 hours, the Chainlink oracle returns a stale price — the liquidation threshold breaches safe positions. Liquidators drain the collateral pool for $400K while the team figures out what happened. The problem is not Chainlink itself — it's the lack of a staleness check: the contract didn't check updatedAt from latestRoundData(). Our team has encountered similar incidents and developed a systematic approach to DeFi protocol development, including smart contracts for lending protocols, AMMs, cross-chain bridges, and liquidity pools for yield farming.

Developing a DeFi protocol is not just Solidity code. It's a system of invariants that must hold under any market conditions, MEV attacks, and infrastructure force majeure. We use formal specifications and property-based tests to identify vulnerabilities early. We guarantee transparency at every stage.

Why DeFi Protocols Fail at the Design Stage

Oracle Manipulation via Flash Loan

Typical scheme: an attacker takes a flash loan of 50M USDC on Aave, manipulates the price in a Uniswap v2 pool with low liquidity, uses that pool as a price oracle, borrows against inflated collateral, and doesn't repay the loan. Protocols that use token.balanceOf(pool) or spot price from an AMM as an oracle are vulnerable by definition.

Protection works at multiple levels:

  • TWAP instead of spot price. Uniswap v3 provides OracleLibrary.consult() for time-weighted average price. A 30-minute window makes flash loan manipulation economically unviable — the position must be held for several blocks, each at risk of arbitrage.

  • Chainlink with fallback. Primary source — Chainlink, fallback — Uniswap v3 TWAP. If Chainlink returns a price with updatedAt older than 3600 seconds or answer < 0 — switch to TWAP with an event emitted for monitoring.

  • Circuit breaker on deviation. If the price changes by more than 15% in one block — the transaction is reverted. The parameter is adjustable via governance with a timelock.

Reentrancy in Cross-Protocol Interactions

An AMM protocol calls a token during a swap. If the token implements ERC-777 with a tokensReceived hook — the attacker's contract gains control mid-swap, before the pool's internal balances are updated. This is not theoretical: the attack on Uniswap v1 via ERC-777 was one of the first public exploits on a DEX. More about reentrancy can be read on Wikipedia.

In modern protocols, the problem is more complex: callback patterns (uniswapV3SwapCallback, flashLoanReceiver) intentionally pass control to external code. Protection is built through invariant checks: before the callback, the state is recorded; after, it is checked that invariants are satisfied.

Liquidation Mechanics and Bad Debt

With a sharp market drop of 40%+ in one block (Ethereum fell 50% within hours during a crisis period), liquidation may not keep up. The collateral is worth less than the debt — the protocol incurs bad debt. Compound v2 faced this; MakerDAO introduced Emergency Shutdown as a last resort.

Liquidation parameters require mathematical modeling: loan-to-value ratio, liquidation threshold, liquidation bonus, close factor — all these parameters must be calibrated to the volatility of the specific asset. WBTC and a memecoin cannot have the same LTV. Poor gas optimization can cost up to $5000 per month, while optimization at the development stage reduces these costs by 30-50%. Unoptimized contracts — over 2000 lines of code — increase audit time by 3 times.

How We Ensure Oracle Security in DeFi Protocols

We apply a multi-layered strategy: a primary Chainlink oracle with TWAP fallback, a circuit breaker for anomalous price movements, and mandatory data freshness validation. Additionally, we use keepers on Tenderly to automatically switch sources during failures.

Risk Countermeasures Tools
Oracle manipulation TWAP, circuit breaker, fallback oracles Chainlink, Uniswap v3 TWAP
Reentrancy Reentrancy guard, invariant checks after callbacks OpenZeppelin ReentrancyGuard
Incorrect liquidation Parameter modeling, stress testing Custom Foundry scripts

Protocol Architecture

Modular Contract Structure

A monolithic contract of 3000 lines is the first mistake in a DeFi protocol. Not for aesthetics, but because:

  • It exceeds the EVM bytecode limit (24 KB)
  • It's impossible to replace a single module without a full redeploy
  • Auditing takes 3x longer and costs accordingly

We use the Diamond Pattern (EIP-2535) for feature-rich protocols: separate facets for lending, liquidation, oracle, governance. Storage uses a common Diamond Storage via keccak256 slots (ERC-7201).

For simpler cases — separation into Core (immutable logic), Periphery (auxiliary contracts, can be upgraded), and Governance. This pattern is used by Uniswap since v2.

Upgradability: When Needed and When It Hurts

UUPS (EIP-1822) vs Transparent Proxy (EIP-1967): the choice depends on who pays for upgrades. In UUPS, the upgrade logic is in the implementation — cheaper for users, but if the new implementation removes the upgradeTo function, the protocol loses upgradability forever. In Transparent Proxy, the logic is in the proxy — slightly more expensive per call, but more reliable.

For protocols with TVL over $10M, upgradability via a multisig without a timelock is a centralization attack vector. Gnosis Safe 4-of-7 + 48-hour timelock via OpenZeppelin TimelockController is the minimum trust standard.

Tokenomics at the Contract Level

The ve-model (vote-escrowed, as in Curve) requires careful balance: the contract locks tokens for up to 4 years, calculates voting power via balanceOfAtTime() at a specific block. If voting power is calculated incorrectly — governance attacks become cheaper than they should be.

The emission schedule should be immutable or governed by super-majority voting. Changing emission retroactively is exactly what kills trust in a protocol.

Development Stack

Component Tools Purpose
Development Foundry, Hardhat Primary environment, tests, deployment
Base contracts OpenZeppelin 5.x Access control, proxy, tokens
Oracle Chainlink, Uniswap v3 TWAP Price data
Testing Foundry fuzz, Echidna Property-based tests
Static analysis Slither, Mythril Automated vulnerability search
Monitoring Tenderly, OpenZeppelin Defender Alerts, automation
Indexing The Graph Subgraph for frontend

Fork tests on Foundry allow running the entire protocol against real mainnet state: vm.createFork("mainnet"), vm.rollFork(blockNumber). This is the only way to check interactions with real Uniswap pools, real Chainlink feeds, and real Aave positions.

What Does the Development Process Include?

  1. Specification (1 week). Formal description of invariants: "total debt is always less than total collateral considering LTV", "only a liquidator can close an unhealthy position", "emission rate cannot increase by more than X% in one governance cycle." Invariants become the basis for Echidna property tests.

  2. Architectural design (3-5 days). Storage layout, interfaces, contract interaction diagram. Decision on upgradability and governance. This stage is cheaper to change on paper than after 2 weeks of development.

  3. Development (3-8 weeks). Depends on protocol complexity. Parallel: contracts + tests in Foundry (coverage >90%), subgraph on The Graph, deployment scripts.

  4. Internal audit + preparation for external audit. Slither CI on every PR. Before external audit — full Mythril check, manual review against SWC checklist. Goal: close low/medium issues before the external auditor so they focus on high-level vectors.

  5. Deployment. Testnet (Sepolia/Arbitrum Goerli) → staged mainnet via multisig with timelock → post-launch monitoring via Tenderly.

Timeline Estimates

A minimal AMM protocol (xy=k, without concentrated liquidity) — 4-6 weeks. A lending protocol based on Compound v2 — 8-12 weeks. A full protocol with ve-tokenomics, governance, and cross-chain support — from 3 to 6 months. External audit takes 2-4 weeks additionally and should be scheduled in advance with top-tier firms.

Cost is determined after technical specification. Get a consultation — we will evaluate your project for free. Our experience: 10+ years in blockchain development, 50+ successful projects, certified auditors.

What's Included

  • Documentation: invariant specification, architecture diagram, technical documentation for the auditor.
  • Access: source code repository, audit reports, deployment scripts, administrative multisig wallet.
  • Training: knowledge transfer to the client's team on protocol operation and monitoring.
  • Support: 2 weeks of post-launch support, critical bug fixes under warranty.
Additional Security Measures We also recommend including pause and emergency shutdown mechanisms in the contracts, and using formal verifiers like Certora to prove invariants. Our protocols undergo external audits with minimal findings — on average no more than 2 medium vulnerabilities.

Order the development of a DeFi protocol with a proven architecture. If you are developing a DeFi protocol, order an architecture audit early — this will save time and money. Contact us — we will evaluate your project and offer the optimal architecture.

DeFi Protocol Development

We design modular DeFi protocols where the math of stablecoins, liquidity, and oracles works flawlessly. Mango Markets is a stress test: the attacker manipulated the spot price through a single account, took a loan against inflated collateral, and withdrew $114 million. The oracle took the price from a single source without TWAP. Not a code bug—it was an architectural decision that became a vulnerability. Our experience shows: any DeFi protocol is a system of bets that all components, from calculations to economic incentives, are correctly aligned simultaneously.

We don't write code under the 'if it works, don't touch it' mindset. We model stress scenarios: cascading liquidations, depegs, flash loans. Only then do we build events that won't break the protocol.

Why are oracles a critical component of DeFi?

Most major DeFi hacks started with oracle manipulation. Let's break down the three layers we use in every project.

Spot price as oracle—not an option. Uniswap v2 spot price can be shifted by a flash loan in one transaction. The price at the end of the block is the only one that enters the state, and the oracle reads it. Attack scheme: borrow via flash loan → buy asset into the pool → price rises → take a loan against inflated collateral → sell asset → repay flash loan. One transaction.

TWAP as protection. Uniswap v3 observe() averages the price over a period (30 minutes). Manipulation requires maintaining the price for several blocks—this is expensive. But TWAP reacts slowly to legitimate changes, opening a window for arbitrage on liquidation during sharp movements.

Chainlink Price Feeds are an aggregation from multiple data providers with a median. Standard for lending. Problem: heartbeat 1–24 hours and deviation threshold 0.5%. If the price doesn't move, the feed may not update for a day. In volatile markets—lag.

Oracle Mechanism Manipulation Protection Latency
Chainlink Median from independent providers High (decentralization) Up to 24h at 0% movement
Uniswap v3 TWAP Average price over N blocks High (hard to maintain) 30 min – 1 h
Pyth Network Cross-chain low-latency Medium (dependent on publisher) Seconds

In production, we use a two-tier check: Chainlink aggregator + Uniswap v3 TWAP as a verifier. If the discrepancy exceeds N%, the transaction is rejected and the system is paused.

How to protect a DeFi protocol from flash loan attacks?

Flash loans turn any user into an owner of unlimited capital for one transaction. Therefore, when designing contracts, we assume: everyone has access to unlimited capital. This completely changes the threat model.

Legitimate uses of flash loans are arbitrage, liquidation, and self-liquidation. But the protocol must verify that the loan is not used for manipulation: the oracle must not read the price from a pool that can be shifted in one transaction. We add checks on block.timestamp and minimum liquidity depth.

Key Components of DeFi Architecture

Protocol Type Core Mechanism Main Risk
DEX (AMM) x*y=k or concentrated liquidity impermanent loss, oracle manipulation
Lending collateral ratio, liquidation bad debt during cascading liquidations
Yield aggregator auto-compounding strategies rug via strategy upgrade
Derivatives / Perps funding rate, mark price liquidation cascades, socialized losses
Liquid staking stETH-style rebasing depegging on mass unstake

AMM: From x*y=k to Concentrated Liquidity

Uniswap v2 uses x * y = k. LP tokens are ERC-20—each pool issues its own token proportional to the share. Problem: liquidity is spread across the entire curve, most of it unused.

Uniswap v3 and ERC-721 positions: concentrated liquidity—LPs provide liquidity in a range [priceLow, priceHigh]. Capital efficiency up to 4000x for stable pairs. But ERC-721 breaks vault strategies built for ERC-20. Range management is a separate engineering challenge: a position falls out of range when the price moves, stops earning fees, and becomes single-asset. Protocols like Arrakis Finance automatically rebalance. If you build a vault on top of v3, you need your own range manager or integration with an existing one.

Slippage in v3 is calculated via sqrtPriceX96—96-bit fixed-point math. Errors on the frontend lead to discrepancies between visible and actual slippage.

Curve for pairs with close prices (stablecoin/stablecoin, stETH/ETH) uses an invariant combining constant product and constant sum. Lower slippage within the peg range. Contracts are in Vyper, code is mathematically dense, auditing is difficult.

Lending Protocols: Collateral, Liquidation, Bad Debt

LTV defines the maximum loan against collateral. Liquidation threshold is the level for liquidation. The difference is the buffer for the liquidator. Typical example: LTV 75%, liquidation threshold 80%, bonus 5%. If the price drops 20%+, the position is open for liquidation.

Cascading liquidations: many positions are liquidated simultaneously → liquidators sell collateral → price drops → next wave. LUNA/UST 2022 is a classic cascade.

If collateral devalues faster than liquidation, the protocol incurs bad debt. Aave uses a Safety Module (staked AAVE), Compound uses reserves. Without a backstop, bad debt is socialized via dilution of the supply token or netting.

Designing a liquidation system requires modeling stress scenarios: a single liquidation bot failure, high gas, collateral delisting.

Yield Farming and Incentive Mechanics

Liquidity mining distributes governance tokens to LP providers. Problem: mercenary capital—farmers come, sell tokens, leave. TVL is illusory.

Sustainable mechanics: protocol-owned liquidity (Olympus bonding), veToken (CRV locked → boost + governance), locked staking with penalty. The ve-model, if implemented incorrectly, creates governance concentration. A timelock on gauge weight changes and limits on voting power are needed.

What Our DeFi Protocol Development Includes

  • Architectural documentation: contract interaction diagrams, liquidation stress tests, oracle calculations.
  • Implementation in Solidity 0.8.x with OpenZeppelin 5.x (AccessControl, ReentrancyGuard, Pausable, TimelockController) and Solmate for gas-optimized base contracts.
  • Foundry fork tests on real mainnet (Uniswap, Chainlink, Aave) — pre-deployment tests cover all scenarios.
  • Audit: at least two independent auditors for TVL over $1M. Code4rena or Sherlock for bug bounty.
  • Deployment with Gnosis Safe 3/5 multisig + timelock 48–72 hours.
  • Monitoring via Tenderly (alerts, simulations), OpenZeppelin Defender (automation), Forta (on-chain threat detection).
  • Post-launch support: updates, patches, upgrades via proxy.

Our Expertise and Experience

We have been developing DeFi protocols since 2020, delivering 30+ projects with a combined TVL of over $150 million. Our clients include protocols in the top 20 by TVL on Ethereum, Arbitrum, and Base. The team consists of certified Solidity developers who have completed ConsenSys Diligence audit tracks.

DeFi basic principles that we apply in practice.

Timelines

  • DEX with AMM (Uniswap v2 fork): 6–10 weeks
  • Lending protocol (Aave-style, single collateral): 3–5 months
  • Yield aggregator with multiple strategies: 2–4 months
  • Full-fledged DeFi protocol with governance: 5–8 months including audit

Cost is calculated individually—contact us for a project estimate.

Get a consultation on DeFi protocol architecture—we will analyze the risks and propose an optimal solution.