Titan: Building a DeFi Super App
A technical deep dive into Titan - a complete DeFi protocol featuring token swaps, concentrated liquidity, liquid staking with sTITAN, overcollateralized lending with tUSD, and snapshot-based on-chain governance.
Titan is a DeFi protocol built on Ethereum Sepolia that brings together token swapping, concentrated liquidity, liquid staking, overcollateralized lending, and on-chain governance into a single platform. The protocol uses Uniswap V4 for its trading infrastructure and implements its own token ecosystem with TITAN, sTITAN, and tUSD.
## The Token Ecosystem
### TITAN - The Base Token
TITAN is the protocol's native ERC-20 token that powers the entire ecosystem. It launches with an initial supply of 100 million tokens and has a maximum cap of 1 billion. The token implements ERC20Votes, which means holders can delegate their voting power and participate in governance. It also supports ERC20Permit for gasless approvals and ERC20Burnable for deflationary mechanics when needed.
TITAN serves multiple purposes: you can stake it to earn rewards, use it as collateral to borrow tUSD, or convert it to sTITAN for governance participation and auto-compounding yields.
### sTITAN - Liquid Staking Token
sTITAN represents staked TITAN with a unique share-based mechanism. When you deposit TITAN into the StakedTitan contract, you receive sTITAN shares based on the current exchange rate. Here's where it gets interesting: as protocol rewards flow into the contract, the total TITAN balance grows while the total sTITAN supply stays the same. This means each sTITAN becomes redeemable for more TITAN over time.
For example, if you stake 1000 TITAN when the exchange rate is 1:1, you get 1000 sTITAN. After rewards accumulate and the rate becomes 1:1.1, your 1000 sTITAN is now worth 1100 TITAN. No claiming, no compounding - the math handles everything automatically.
The contract includes security measures like a virtual offset of 1e8 to prevent first-depositor attacks (where an attacker could manipulate the initial exchange rate) and enforces a minimum deposit of 0.001 TITAN to avoid dust positions. sTITAN also inherits ERC20Votes with automatic self-delegation, making it the governance token for the protocol.
### tUSD - Protocol Stablecoin
tUSD is Titan's native stablecoin, minted against TITAN collateral through the Vault contract. Only authorized minters (primarily the Vault) can create new tUSD, ensuring controlled supply tied to actual collateral. The token follows standard ERC-20 patterns with 18 decimals.
## Staking and Rewards
### The Earn Contract
The Earn contract provides a straightforward way to stake TITAN and earn additional TITAN rewards. Unlike sTITAN's share-based model, Earn uses a per-token reward accumulator - a common pattern seen in protocols like Synthetix.
The mechanism works by tracking a global "reward per token" value that increases over time based on the configured reward rate. Each user has a snapshot of this value from their last interaction. When you stake, unstake, or claim, the contract calculates your earned rewards as: your staked balance multiplied by the difference between the current reward-per-token and your last snapshot.
This approach distributes rewards proportionally - if you hold 10% of the staked supply, you earn 10% of the rewards. There are no lockups, so you can stake, unstake, or claim at any time.
## The Lending System
### Vault - Collateralized Debt Positions
The Vault contract implements a CDP (Collateralized Debt Position) system similar to MakerDAO. Users deposit TITAN as collateral and can borrow tUSD against it. The system enforces strict collateralization rules:
**Minimum Collateral Ratio (MCR): 150%** - To borrow, your collateral value must be at least 150% of your debt. If you want to borrow 1000 tUSD, you need at least 1500 tUSD worth of TITAN.
**Liquidation Threshold: 110%** - If your collateral ratio falls below 110%, your position becomes liquidatable. This gives a 40% buffer between the minimum ratio and liquidation.
**Liquidation Bonus: 10%** - Liquidators who repay a user's debt receive the collateral plus a 10% bonus, incentivizing quick liquidations to keep the protocol solvent.
The Vault tracks each user's position with two values: collateral (TITAN deposited) and debt (tUSD borrowed). When borrowing, it checks that the new debt maintains the MCR. When liquidating, it verifies the position is underwater, burns the debt from the liquidator, and transfers the collateral plus bonus.
## Governance
### On-Chain Voting with Snapshots
The Governor contract enables sTITAN holders to propose and vote on protocol changes. The system uses configurable parameters:
- **Proposal Threshold** - Minimum sTITAN required to create a proposal
- **Voting Delay** - Blocks between proposal creation and voting start
- **Voting Period** - Duration of voting in blocks
- **Timelock Delay** - Waiting period before execution
- **Quorum Percentage** - Required participation for validity
The key innovation is snapshot-based voting. When a proposal is created, the contract records the current block number. When users vote, their voting power is calculated from that snapshot using getPastVotes(). This prevents flash loan attacks where someone could borrow tokens, vote, and return them in a single transaction.
Voters can cast For, Against, or Abstain votes. Passed proposals go through a timelock queue before execution, giving users time to react to changes.
## Uniswap V4 Integration
### SwapRouter - Token Trading
Titan's SwapRouter integrates with Uniswap V4's singleton PoolManager architecture. Unlike V3 where each pool is a separate contract, V4 consolidates all pools into a single contract, reducing gas costs significantly.
When executing a swap, the router:
1. Constructs a PoolKey identifying the trading pair (tokens are sorted by address, with the lower address as currency0)
2. Determines swap direction (zeroForOne based on which token you're selling)
3. Calls the PoolManager's swap function with the amount and slippage parameters
4. Processes the returned BalanceDelta to determine actual output
5. Verifies the output meets the minimum amount requirement
The router uses V4's unlock callback pattern - it initiates the swap by calling unlock(), which triggers a callback where the actual swap logic executes. This pattern enables atomic multi-step operations.
### LiquidityRouter - Concentrated Liquidity
The LiquidityRouter manages concentrated liquidity positions on Uniswap V4. Unlike traditional AMMs where liquidity is spread across all prices, concentrated liquidity lets providers focus their capital within specific price ranges.
When adding liquidity, users specify:
- Token pair and fee tier
- Tick range (tickLower and tickUpper define the price bounds)
- Desired amounts of each token
The router interacts with V4's PositionManager to mint a position NFT representing the LP's stake. Positions earn trading fees when the current price is within their range. Users can later remove liquidity or collect accumulated fees.
The contract tracks positions using a nested mapping: user address -> pool ID -> tick lower -> tick upper -> liquidity amount. This allows users to have multiple positions across different ranges.
## Frontend Architecture
Titan's web application is built with Next.js 16, TypeScript, and TailwindCSS 4. The Web3 stack uses wagmi 3.5 for React hooks, viem 2.46 for Ethereum interactions, and Reown AppKit (formerly WalletConnect Web3Modal) for wallet connections.
### Hook-Based Contract Interactions
Each protocol feature has a dedicated React hook that encapsulates all contract interactions. For example, the sTITAN hook provides:
- Balance and exchange rate reads via useReadContract
- Stake and unstake functions via useWriteContract
- Loading states for pending transactions
- Automatic refetching after state changes
This pattern separates blockchain logic from UI components, making the codebase more maintainable and testable. Components simply call hook functions and render based on the returned state.
### Wallet Connection
Reown AppKit handles wallet connections with support for MetaMask, WalletConnect, and other providers. The configuration specifies Sepolia as the network, with custom theming to match Titan's design. The adapter pattern allows easy switching between wallet providers while maintaining a consistent API.
## Testnet Infrastructure
### Faucet Contract
For testnet deployment, Titan includes a faucet that distributes TITAN to new users. The contract supports:
- Configurable drip amount (tokens per claim)
- Configurable cooldown period (time between claims)
- Pause functionality for maintenance
- Owner-controlled parameter updates
The faucet tracks each address's last claim timestamp and requires the cooldown to pass before allowing another claim. First-time claimers can always claim immediately.
## Security Design
Titan's contracts implement multiple security layers:
**Reentrancy Protection** - All state-changing functions use OpenZeppelin's ReentrancyGuard modifier, preventing callbacks from re-entering and manipulating state.
**Access Control** - Administrative functions like minting, pausing, and parameter updates are restricted to the owner using the Ownable pattern.
**Integer Safety** - Solidity 0.8+ automatically reverts on overflow/underflow, eliminating a historically common vulnerability class.
**Liquidation Buffer** - The 40% gap between MCR (150%) and liquidation threshold (110%) gives users significant time to add collateral during price drops.
**Snapshot Voting** - Recording voting power at proposal creation prevents flash loan governance attacks.
**Virtual Offset** - The 1e8 offset in sTITAN prevents first-depositor manipulation of the exchange rate.
## Conclusion
Titan demonstrates how to build a cohesive DeFi protocol by combining proven primitives: Uniswap V4 for trading, share-based liquid staking for yield, CDP-style lending for leverage, and snapshot voting for governance. The 9 smart contracts work together while remaining individually composable, and the frontend abstracts complexity through custom hooks. Users get a unified interface for swapping, providing liquidity, staking, borrowing, and voting - without needing to understand the underlying contract architecture.