A client comes to us with a requirement: a fractional-reserve stablecoin to tie up less capital than DAI. The first bank run simulation shows that during mass redemptions, reserves are exhausted within 3 blocks. The algorithmic part fails to react in time, and the peg breaks. Fractional-reserve is a trade-off between capital efficiency and stability. Our experience shows that most teams undertaking the implementation underestimate the bank run mechanism in an on-chain context: smart contracts allow withdrawing everything in a single transaction. For example, if the governance token price drops 30% within one block, the system must remain solvent — we design protection against such scenarios. We can reduce liquidity costs significantly, making the project viable for startups.
How to Ensure Fractional-Reserve Stablecoin Stability Against Bank Run?
The Algorithmic Part Kills the Peg Faster Than It Seems — Developing Fractional Reserve
FRAX v1 launched with CR 100%, then the algorithm lowered CR as demand grew. Theory: if the market trusts the protocol, part of the collateral can be replaced with governance token FXS. In practice, after the SVB crash during the crisis period, CR fell below 90%, and recovery took several weeks of volatility. Not a failure, but a vivid example that the algorithmic part is not linear under pressure.
The key invariant to protect: redemption must always be possible at face value. If a user cannot burn 1 stablecoin and get $1 in collateral (or equivalent), the arbitrage mechanism is broken, and the peg relies solely on psychology.
Contract Architecture: Three Layers
Layer 1 — Minting/Redemption. The user deposits collateral (USDC, ETH via Chainlink price feed) and receives stablecoins. On mint at CR=80% — 80 cents in USDC + governance tokens worth 20 cents. On redeem — the reverse. This layer must be atomic and independent of on-chain governance token liquidity.
Layer 2 — PID Controller CR. An algorithm that raises CR on depeg downward and lowers it on stable peg. Critical: do not make changes instantaneously. A CR change of 1% per day is typical. A sharp change creates MEV opportunities for arbitrageurs who will attack the transition moment.
Layer 3 — AMO (Algorithmic Market Operations). Free reserves are deployed in Curve/Aave/Convex generating yield. AMO contracts must have a hard limit on maximum deployment: if AMO can allocate more than (1 - CR) of total supply, the system becomes vulnerable to simultaneous withdrawals.
Example PID Controller Parameters
P = 0.05, I = 0.001, D = 0.01. CR change limit: no more than 0.5% per block, no more than 1% per day. Triggers: if depeg > 0.5% down — increase CR by 0.2% each block until stabilization.
Why Oracles Matter for Peg Maintenance?
Typical flash loan attack: attacker borrows a large amount of USDC, suppresses governance token price by 40% through a thin Uniswap v2 pool, the contract instantly recalculates CR via a TWAP oracle with a short window (5 minutes) — CR drops, the protocol becomes technically undercollateralized. The attacker then opens redemption and receives USDC from reserves at an unfavorable rate.
Protection: TWAP minimum 30 minutes for the governance token as a collateral component. For USDC and ETH, Chainlink with deviation threshold 0.5% suffices. Separate oracles for different components, not an aggregated price feed. Chainlink documentation recommends using TWAP oracles for low-liquidity assets and decentralized price feeds for major collaterals.
How We Build Such Systems
Development starts with the economic model, not code. We need to determine:
- Target CR range (e.g., 80-90%)
- PID parameters: CR change speed, trigger thresholds
- List of acceptable collateral assets and their weight coefficients
- Incentive mechanism for peg maintenance (stability fees, bond mechanism)
Hybrid collateral — a combination of collateral assets and an algorithmic part — allows achieving capital efficiency without losing stability.
Stack: Solidity 0.8.x, OpenZeppelin for access control and pausability, Chainlink for price feeds, Curve Finance SDK for AMO integration. Tests in Foundry with mainnet fork — mandatory because AMO logic depends on real Curve pool states.
For the governance token — standard ERC-20 with burn mechanism on stablecoin mint. Important: the governance token must not have infinite mint — this killed projects like Iron Finance (IRON/TITAN, where value dropped from $2B to $0 within 24 hours).
Testing Bank Run Scenario
In Foundry, we can simulate simultaneous redemption of 80% supply in one block. The contract must either handle this correctly (dispense USDC from reserves, freeze governance token portion) or activate a circuit breaker. Circuit breaker — a pausable module with timelock that introduces a cooldown on redemption when a threshold volume per block is exceeded.
Property-based test via Echidna: invariant "total_collateral_value / total_supply >= min_CR" must hold for any minting and redemption scenario.
PID Controller Parameters
| Parameter |
Value |
| P |
0.05 |
| I |
0.001 |
| D |
0.01 |
| Max CR change per block |
0.5% |
| Max CR change per day |
1% |
| Trigger for upward CR adjustment |
Depeg > 0.5% down |
Process
- Economic design (1-2 weeks). Parameterization of the model, simulation in Python/Jupyter, stress-test bank run scenarios. Determine thresholds where the system becomes unstable.
- Contract design (1 week). Storage layout, interfaces, interaction diagram. Special attention to operation order in mint/redeem (Checks-Effects-Interactions).
- Development (3-6 weeks). Core contracts + AMO + oracle integration. Fork tests against mainnet Curve/Aave.
- Audit. For financial protocols of this level — mandatory external audit. We prepare the codebase: Slither clean, 95%+ test coverage, NatSpec on all public functions.
- Deployment. First testnet (Sepolia) with simulated market stress via Foundry scripts. Mainnet deployment via Gnosis Safe multisig with timelock of at least 48 hours on parameter changes.
| Component |
Timeline |
| Minimal system (without AMO) |
6-8 weeks |
| With AMO modules and full testing |
2-3 months |
| Preparation for external audit |
1-2 weeks |
Timelines and cost depend heavily on the number of collateral types and governance complexity. We will assess your project in 1-2 days — contact us to discuss details. Get a consultation today and start developing your fractional-reserve stablecoin.
What's Included
- Economic model with simulations
- Full set of smart contracts (mint/redeem, PID, AMO, governance token)
- Chainlink oracle and Curve AMO integration
- Tests with >95% coverage, including property-based and fork tests
- Documentation (NatSpec, technical specification)
- Audit preparation (Slither, Mythril, Echidna)
- Testnet and mainnet deployment via multisig
- Post-release support (1 month monitoring)
Our team has over 5 years of experience in DeFi protocol development and 10+ implemented stablecoin projects. We guarantee passing external audit and resilience to bank run scenarios. Order fractional-reserve stablecoin development — write to us for a consultation.
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.