The 12-week playbook
DeFi protocols look complicated from the outside, but the shipping schedule is surprisingly stable. Most protocols we ship · DEX, lending market, staking system, or perpetuals · fit in a 12-week window if you start with a tight spec.
Weeks 1:2 · Spec and tokenomics
We pin down the protocol: what asset moves, what the fee surface looks like, who earns it, what the governance scope is, and what the oracle dependency is. Tokenomics modeling · supply curve, fee distribution, emissions · happens here so the contracts don't get rewritten halfway through.
Weeks 3:6 · Contracts
Foundry-based development with full unit test coverage and invariant tests. By the end of week 6 we have a feature-complete contract suite that passes its own tests.
Weeks 7:8 · Internal review and pre-audit
Slither static analysis, Echidna fuzzing for state invariants, and a fresh-eyes internal review by a contract reviewer who didn't write the code.
Weeks 9:10 · External audit
Two-week external audit window. Audit firm picked from Trail of Bits, OpenZeppelin, Spearbit, Pashov, yAudit, or a Cyfrin Codehawks contest depending on budget and risk profile.
Weeks 11:12 · UI and launch
The UI (Next.js + wagmi + viem + RainbowKit / ConnectKit) is built in parallel during weeks 6:10, ready to integrate the moment audit-fixed contracts deploy. Week 11: testnet, public beta. Week 12: mainnet, liquidity seeding, multisig handover.
The four shapes we ship most
Almost every DeFi protocol is a variation on one of four primitives. They differ in what moves on-chain, where the risk concentrates, and what an exploit actually steals. Knowing which shape you are building is the first design decision, because it sets the oracle dependency, the liquidity model, and the entire audit surface.
AMM DEXes · automated market makers
An AMM replaces an orderbook with a pricing formula and a pool of two or more assets. The classic constant-product curve (x · y = k, the Uniswap v2 shape) lets anyone swap against the pool while arbitrageurs keep the price honest. Liquidity providers deposit both sides and earn a swap fee, but they carry impermanent loss · the gap between holding the assets and providing them when the price diverges. Newer designs add concentrated liquidity (Uniswap v3, where LPs pick a price band for higher capital efficiency), stableswap curves (Curve, flat near the peg for low-slippage stablecoin trades), and hooks (Uniswap v4, custom logic on every swap). The hard parts are MEV-resistant routing, fee-tier design, and making sure the pool math cannot be gamed by a flash-loaned imbalance.
Lending markets
A lending protocol lets suppliers deposit assets to earn yield and borrowers take over-collateralized loans against them. Interest rates float with utilization · the higher the share of a pool that is borrowed, the higher the rate, which pulls in more supply and discourages new borrows. The core risk surface is the collateral factor (how much you can borrow against an asset), the liquidation threshold, and the liquidation incentive that pays keepers to close unhealthy positions. Compound and Aave are the reference shapes; isolated-market designs (Morpho, Euler style) limit contagion by giving each asset pair its own risk parameters instead of one shared pool. Oracles are existential here · a single bad price feed can mint bad debt across the whole market.
Staking and yield
Staking systems pay token holders for locking value or providing a service. The patterns range from simple reward-per-token staking pools to ve-token systems (vote-escrowed, à la Curve) where users lock tokens for a duration to get boosted rewards and governance weight, to liquid staking where the staked position itself becomes a tradable receipt token. The accounting trap is reward distribution math · a naive implementation that loops over stakers will run out of gas, so rewards are tracked per-share with a global accumulator. Get the rounding wrong and the last withdrawer either drains the pool or gets stuck.
Perpetuals
Perpetual futures let traders take leveraged long or short positions with no expiry, held in line with spot by a funding rate that longs and shorts pay each other. Two architectures dominate: vAMM or oracle-priced models (GMX, dYdX v3 style) where a pool or virtual curve sets the mark price, and orderbook perps (dYdX v4, Hyperliquid style) that match real bids and asks. Perps carry the densest risk surface in DeFi · funding-rate logic, mark-vs-index price, liquidation engines, insurance funds to socialize bad debt, and oracle latency that an attacker can exploit during volatility. This is the shape that most rewards heavy invariant testing.
What kills DeFi protocols
Most DeFi losses fall into a short list of named exploit classes. None of them are exotic · they recur because they are easy to introduce and easy to miss. Designing against each one from day one is cheaper than discovering them in an audit, and far cheaper than discovering them on mainnet.
| Exploit class | How it works | How we defend |
|---|---|---|
| Reentrancy | An external call hands control back to the attacker before state updates finish, letting them re-enter and drain funds (the DAO hack class). | Checks-effects-interactions ordering, ReentrancyGuard, and Echidna invariants that assert balances never go negative. |
| Oracle manipulation | An attacker moves a thin spot price (often with a flash loan) so the protocol misprices collateral or mints bad debt. | Chainlink or other robust feeds with TWAP fallbacks and sanity bounds; never a raw single-block spot price. |
| Flash-loan attacks | Uncollateralized single-transaction loans amplify any pricing or accounting flaw to massive size. | Assume every input can be flash-funded; price off manipulation-resistant sources and test under adversarial liquidity. |
| MEV · front-running and sandwich | Searchers reorder or wrap user transactions to extract value, worsening swap execution and liquidations. | Slippage limits, commit-reveal or batch designs where it fits, and MEV-aware routing. |
| Liquidation races | Keeper bots compete or stall on closing unhealthy positions, leaving bad debt during volatility. | Dynamic liquidation incentives and partial liquidations so closing positions stays profitable in any market. |
| Governance and access | A captured vote or an unguarded admin function changes parameters or upgrades a contract maliciously. | Timelocks, delegation snapshots, multisig control, and tight role-based access on every privileged call. |
Underneath all of these sit two simpler killers · arithmetic bugs (overflow, rounding, decimals mismatch between tokens) and upgrade mistakes (a botched proxy or storage-layout collision). Foundry unit tests catch the arithmetic; a disciplined upgrade process with storage gaps catches the rest. Whichever shape you ship, the external audit is non-negotiable; if you want the numbers behind that line item, see smart contract audit cost.
Tooling and testing we standardize on
The testing stack is what separates a demo from a protocol that can hold value. We build in Foundry and lean on four layers of coverage: unit tests for every function path, fork tests against real mainnet state so integrations are tested against the actual contracts they will touch, invariant and fuzz tests (Foundry's built-in fuzzer plus Echidna) that hammer the protocol with random sequences and assert properties like "total supply equals the sum of balances" or "the pool is never insolvent," and static analysis with Slither to catch known anti-patterns before a human ever reviews. Gas profiling and a deployment-and-upgrade rehearsal on a fork round it out. The front end · Next.js with wagmi, viem, and RainbowKit or ConnectKit · is built in parallel so it is ready the moment audited contracts land.
What it costs
A full DeFi protocol · contracts + audit coordination + UI + launch · is scoped per project. Pricing depends on which of the four shapes you are building, the chain, the number of external integrations, and which audit firm fits the risk profile. A single-asset staking system is a very different number from a cross-margin perps exchange. Send a one-paragraph description of the protocol and we will send back a real scope. If a token sale rides on top of the protocol, the token launch guide covers that side, and you can see the full Web3 build menu at our Web3 specialty. Building an exchange specifically? See crypto exchange development cost.
FAQ
How long does it take to build a DeFi protocol?
About 12 weeks for most · DEX, lending market, staking, or perpetuals · when you start with a tight spec.
What's involved in DeFi protocol development?
Spec + tokenomics (weeks 1:2), Foundry contracts with invariant tests (3:6), internal review with Slither/Echidna (7:8), external audit (9:10), then UI and launch (11:12).
Do you audit DeFi protocols before mainnet?
Yes · internal review + Slither + Echidna, then an external audit (Trail of Bits, OpenZeppelin, Spearbit, Pashov, yAudit, or Cyfrin), with a re-audit of any meaningful change.
What types of DeFi protocols do you build?
AMM DEXes, lending markets, staking systems, and perpetuals.