How we built a DeFi lending protocol from scratch — architecture, security & lessons learned

Building a lending protocol means holding other people's money in code that can't be patched quietly. Here's how we approached the architecture, where we spent our security budget, and what we'd do differently next time.
Why build a protocol instead of forking one
Forking an established protocol is the fast path, but our client needed custom collateral types and an interest-rate curve that existing forks couldn't express cleanly. Inheriting a large codebase you don't fully understand is its own kind of risk — especially when real funds are involved.
So we scoped a focused protocol: supply assets to earn yield, borrow against collateral, and liquidate unhealthy positions. Everything else was deliberately left out of v1.
Architecture at a glance
The system splits into three layers. On-chain: a set of audited Solidity contracts holding all value and logic. Off-chain: a subgraph that indexes events so the UI never has to scan the chain. And the client: a Next.js app that talks to wallets and reads indexed data.
- Lending pool — custody, accounting and share accrual
- Interest-rate model — utilization-based, isolated per market
- Collateral & liquidation engine — health factors and incentives
- Price oracle adapter — pluggable, with sanity bounds
Smart-contract design
We kept contracts small and single-purpose, composing them rather than building one monolith. State-changing functions follow checks-effects-interactions, and external calls are wrapped in reentrancy guards by default — not as an afterthought.
Upgradeability was a hard decision. We chose a transparent proxy for the periphery but made the core accounting immutable, so the part that holds funds can't be rug-changed later. Governance can adjust parameters within fixed bounds, never arbitrary logic.
Where we spent the security budget
Most exploits aren't clever — they're an unchecked assumption. We wrote invariant tests first ("total borrows never exceed supply", "no position can be liquidated while healthy") and fuzzed them with Foundry until they held across millions of random inputs.
Oracle manipulation is the classic DeFi failure mode, so we bounded price movement per block and sourced from a time-weighted feed. Then we handed the whole thing to an external audit before a single mainnet dollar touched it.
Lessons learned
- Write invariants before features — they catch the bugs specs miss.
- Immutable where it holds money, upgradeable only at the edges.
- A subgraph removes 90% of frontend pain; set it up early.
- Budget for two audits: one to find issues, one to confirm the fixes.
- Blockchain
- DeFi
- Smart Contracts
- Security
Have a project like this in mind?
We'd love to help you design and build it.
