Crypto Lending Platform Development with Security Audit

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
Crypto Lending Platform Development with Security Audit
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
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1250
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_logo-advance_0.webp
    B2B Advance company logo design
    646
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929

We specialize in building secure crypto lending platforms. In our practice, we have delivered 12 DeFi projects, including protocols with a combined TVL of over $500M. Losses from lending protocol hacks can reach hundreds of millions of dollars—one mistake in a contract can cost the entire project. Our experience helps avoid the typical errors that lead to exploits.

One major hack was the Euler Finance protocol, which lost $197M. Euler Finance exploit report The vulnerability lay in the donateToReserves function, which allowed accumulating a deficit without checking collateral. The attacker used a flash loan to create a position with a broken health factor and self-liquidated through the donate mechanism. The code had passed several audits, but the error remained undetected. Our solutions have helped clients prevent losses exceeding $50M.

Lending protocols are one of the most complex categories in DeFi. Each function (deposit, borrow, repay, liquidate) interacts with others, and system invariants are non-trivial. Therefore, we pay special attention to formal verification and extensive testing.

Our team offers end-to-end crypto lending platform development—from specification to audit and deployment. Contact us to discuss your project details.

Why are lending protocols particularly vulnerable?

Oracle manipulation and cascading liquidations

A lending protocol relies on a price oracle to calculate the collateral ratio. Compromising the oracle means you can take out a loan against overvalued collateral or avoid liquidation.

Cream Finance lost $130M through oracle manipulation: a thinly liquid token was used as collateral, its price was manipulated via a flash loan in an AMM pool, and the attacker borrowed an amount many times over the actual value.

Protection—multi-layered oracle:

  1. Chainlink as primary feed with latestRoundData staleness check (>1 hour — pause)
  2. Uniswap v3 TWAP as secondary with a 30-minute window
  3. Circuit breaker: if the two oracles diverge by more than 5% — new borrows suspended

Cascading liquidations are a separate problem. During a sharp market decline, simultaneous liquidation of thousands of positions pushes the asset price down, triggering further liquidations. Compound v3 solves this through liquidation caps at the protocol level.

Health factor calculation and integer precision

Most errors occur here. Health factor = (collateralValue * collateralFactor) / borrowedValue. When calculated with uint256 without proper scaling, rounding cuts precision.

Concrete example: collateral 1.001 ETH with collateralFactor 0.8 gives 0.8008 ETH coverage. Borrow 0.8 ETH. Health factor should be 1.001. If the calculation is done as (collateral * factor / 1e18) / borrow instead of using mulDiv, precision loss can mark a healthy position as liquidatable.

We use FullMath.mulDiv from Uniswap v3 core for all calculations where precision matters. No division before all multiplications.

Reentrancy in liquidate + transfer chains

The liquidate function typically performs several actions: takes collateral from the borrower, repays debt, pays a bonus to the liquidator. If the collateral token implements ERC-777 or has a custom transfer hook, there is a window for reentrancy between steps.

AAVE v3 uses ReentrancyGuard at the Pool contract level and additionally checks a _status flag in critical paths. For any lending protocol, nonReentrant on deposit, borrow, repay, and liquidate is mandatory.

Learn more about reentrancy: reentrancy attack.

Common mistakes when developing a lending protocol
  • Using a single oracle without a fallback
  • Incorrect health factor calculation due to rounding
  • Lack of partial liquidation for large positions
  • Ignoring reentrancy in custom tokens
  • Too high collateral factor for volatile assets

How to protect a protocol from cascading liquidations?

Modular structure modeled on Compound v3

Comptroller / RiskManager
  ├── CToken / CometMarket (per asset)
  │     ├── InterestRateModel
  │     └── PriceOracle
  ├── LiquidationEngine
  └── GovernanceModule

A separate contract for each supported asset (CToken pattern) vs a single Comet contract with mappings—this is a fundamental architectural decision. The CToken pattern is simpler to audit and isolate risk: a problem in one market does not affect others. A single contract is cheaper to deploy and simpler for users.

Characteristic CToken pattern (Compound v2) Single contract (Comet)
Audit complexity Lower: isolated contracts Higher: complex logic
Gas efficiency Higher deploy, lower transactions Lower deploy, higher transactions
Systemic error risk Low Medium
Flexibility High: can add markets independently Medium: changes affect all markets

Interest rate model

Kinked interest rate is the standard: low rate at utilization < 80%, sharp rise above. Formula:

  • If U < kink: borrowRate = baseRate + slope1 * U
  • If U >= kink: borrowRate = baseRate + slope1 * kink + slope2 * (U - kink)

At 95% utilization, rates can reach 100%+ APR—this mechanism pressures borrowers to return liquidity to the pool.

Parameters (baseRate, slope1, slope2, kink) should be changeable through governance with a timelock. The market changes, and optimal parameters change with it.

Liquidation mechanics

Liquidation bonus (5-10% of collateral) is the reward for liquidators. Too small a bonus—liquidators are not incentivized, the protocol accumulates bad debt. Too large—borrowers lose more than reasonable.

Partial liquidation (repaying only part of the debt) is mandatory. Full liquidation of a large position in one go requires enormous capital from the liquidator. Compound v3 allows liquidation down to a health factor of 1.05.

Flash loan liquidations are the standard pattern. The liquidator takes a flash loan, repays the debt, receives collateral (with a bonus), sells it on a DEX, returns the flash loan plus fee. The protocol must support this—i.e., not block collateral withdrawal in the same transaction.

Supported assets and collateral factors

Asset Collateral Factor Liquidation Threshold Example (Aave v3)
ETH/WETH 80% 82.5% 80% / 82.5%
WBTC 70% 75% 70% / 75%
USDC 85% 88% 86% / 88%
LINK 65% 70% 65% / 70%
Volatile ERC-20 40-60% 50-65% varies

Isolation mode (Aave v3)—assets with a debt ceiling, used only as collateral for stablecoins. For new or less liquid assets, this is the right strategy: it reduces systemic risk.

What is included in lending platform development

  • Documentation: specification, mathematical model, risk parameters
  • Smart contracts in Solidity (Foundry) with modular architecture
  • Test suite: unit, fuzz, integration, fork tests
  • Oracle integration (Chainlink, Uniswap TWAP)
  • User interface (optional)
  • External audit by independent experts (typical cost for a complex protocol: $30,000 to $100,000)
  • Deployment and monitoring
  • Post-release support and updates

Development process

  1. Specification (3-5 days). Define assets, interest rate models, need for governance and upgradeability.
  2. Mathematical specifications (2-3 days). Formulas are verified on a Python reference before writing Solidity. This saves a week of debugging in contracts.
  3. Development (4-6 weeks). Foundry + fuzz tests on all invariants: health factor cannot become negative, total debt does not exceed reserves, liquidation bonus is calculated correctly.
  4. Fork testing. Simulate flash loan attacks on a mainnet fork. Test cascading liquidations through price manipulation.
  5. External audit. Mandatory for any protocol with TVL. Preferably two independent auditors.

Timeframe estimates

Minimum viable lending protocol (one asset, basic liquidation)—4-6 weeks. Full platform with multiple markets, governance, upgrades—2-3 months. Audit—an additional 4-8 weeks depending on code size.

Contact us to discuss your project. Get a free consultation and preliminary assessment.

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.