🏗️Architecture

DreamLend is built as a comprehensive decentralized P2P lending protocol on Somnia L1, featuring a multi-layered architecture designed for scalability, security, and exceptional user experience.

🌟 Architecture Overview

DreamLend Architecture

DreamLend follows a modern, layered architecture that separates concerns while maintaining seamless integration between components:

  1. 👥 User Layer - Lenders, Borrowers, and Liquidators

  2. 🖥️ Frontend Layer - Next.js application with React hooks

  3. ⛓️ Blockchain Layer - Smart contracts on Somnia L1

  4. 🔮 Oracle Layer - DIA Oracle V2 for price feeds

  5. 📊 Data Layer - The Graph subgraph for indexing

👥 User Layer

Participants

🏦 Lenders

  • Role: Provide capital for loans

  • Actions: Create loan offers, set terms, earn interest

  • Incentives: Interest income + $DREAM rewards

💰 Borrowers

  • Role: Access capital by providing collateral

  • Actions: Accept loans, manage collateral, repay loans

  • Incentives: Access to capital + $DREAM rewards

⚡ Liquidators

  • Role: Maintain protocol health

  • Actions: Monitor loans, execute liquidations

  • Incentives: Liquidation bonuses + $DREAM rewards

🖥️ Frontend Layer

Technology Stack

  • Framework: Next.js 14 with App Router

  • Styling: Tailwind CSS with custom components

  • State Management: React hooks and context

  • Web3 Integration: Reown AppKit + ethers.js

  • Data Fetching: Apollo Client for subgraph queries

Key Components

📱 Pages

  • Home: Protocol overview and statistics

  • Create: Loan offer creation interface

  • Offers: Browse available loan offers

  • My Loans: Manage active loans and offers

  • Analytics: Protocol metrics and insights

  • Rewards: $DREAM token rewards management

🎣 Custom Hooks

// Core protocol interaction
useP2PLending(); // Main contract interactions
useSubgraphQuery(); // Cached data fetching
useLivePriceComparison(); // Real-time price updates
useTokenBalance(); // Token balance management
useRewards(); // Reward system integration

🧩 UI Components

  • TransactionModal: Multi-step transaction progress

  • LoanHealthManager: Collateral management interface

  • PartialRepaymentManager: Flexible repayment options

  • TokenSelector: Token selection with balance display

  • QuickMintTokens: Testnet token minting

💳 Wallet Integration

  • Reown AppKit: Modern wallet connection

  • Multi-wallet Support: MetaMask, WalletConnect, etc.

  • Network Management: Automatic Somnia L1 configuration

  • Transaction Management: Gas estimation and confirmation

⛓️ Blockchain Layer (Somnia L1)

Network Specifications

  • Chain ID: 50312

  • Consensus: Proof of Stake

  • TPS: 400,000+

  • Block Time: ~1 second

  • Finality: Instant

Smart Contract Architecture

🏛️ DreamLend Contract

Address: 0xddDa4e2B1B8E6f06086F103dA6358E7aCbd020ec

Core Functions:

  • Loan offer creation and management

  • Collateral handling and validation

  • Interest calculation and accrual

  • Liquidation logic and execution

  • Partial repayment support

Security Features:

  • ReentrancyGuard protection

  • SafeERC20 token transfers

  • Oracle price validation

  • Access control modifiers

🎁 RewardsDistributor Contract

Address: 0x1ee1E4d84636FFDb8de6Dc684475C8f2Bdf5699c

Functions:

  • Reward accrual tracking

  • Distribution logic

  • Claim processing

  • Staking mechanisms

💎 DreamerToken Contract

Address: 0xf68F7B7FD9629f4990A5AB7181C2EE0E8b496B4B

Features:

  • ERC20 standard compliance

  • Mintable by authorized contracts

  • Burnable for deflationary mechanics

  • Governance capabilities (future)

🪙 Mock Tokens (Testnet)

  • MUSDT: Mock Tether USD (6 decimals)

  • MUSDC: Mock USD Coin (6 decimals)

  • MWBTC: Mock Wrapped Bitcoin (8 decimals)

  • MARB: Mock Arbitrum (18 decimals)

  • MSOL: Mock Solana (9 decimals)

🔮 Oracle Layer

DIA Oracle V2 Integration

Address: 0x9206296Ea3aEE3E6bdC07F7AaeF14DfCf33d865D

Price Feed Architecture

interface AggregatorV3Interface {
    function latestRoundData() external view returns (
        uint80 roundId,
        int256 answer,
        uint256 startedAt,
        uint256 updatedAt,
        uint80 answeredInRound
    );
}

Supported Price Feeds

  • USDT/USD: 0x67d2C2a87A17b7267a6DBb1A59575C0E9A1D1c3e

  • USDC/USD: 0x235266D5ca6f19F134421C49834C108b32C2124e

  • BTC/USD: 0x4803db1ca3A1DA49c3DB991e1c390321c20e1f21

  • ARB/USD: 0x74952812B6a9e4f826b2969C6D189c4425CBc19B

  • SOL/USD: 0xD5Ea6C434582F827303423dA21729bEa4F87D519

Security Features

  • Staleness Protection: Max 1-hour price age

  • Decimal Normalization: All prices in 8 decimals

  • Fallback Mechanisms: Multiple oracle sources

  • Circuit Breakers: Extreme price change protection

📊 Data Layer

The Graph Subgraph

Endpoint: https://api.subgraph.somnia.network/api/public/d5671b32-2846-489e-a577-e7d9702dd17b/subgraphs/dreamlend-graph/v0.0.3/

Indexed Entities

  • Loans: Complete loan lifecycle data

  • Users: Aggregated user statistics

  • ProtocolStats: Global protocol metrics

  • Events: All contract events with metadata

Caching Strategy

  • Stale-While-Revalidate: Serve cached data while fetching updates

  • Cache Duration: 3 minutes for loan data

  • Invalidation: Manual cache clearing after transactions

  • Optimization: Parallel queries and data prefetching

🔄 Data Flow Architecture

1. User Interaction Flow

sequenceDiagram
    participant U as User
    participant F as Frontend
    participant W as Wallet
    participant C as Contract
    participant O as Oracle
    participant S as Subgraph

    U->>F: Create Loan Offer
    F->>W: Request Transaction
    W->>C: Execute createLoanOffer()
    C->>O: Validate Prices
    C->>C: Store Loan Data
    C->>S: Emit Events
    S->>F: Update UI Data
    F->>U: Show Success

2. Price Update Flow

sequenceDiagram
    participant O as Oracle
    participant C as Contract
    participant F as Frontend
    participant U as User

    O->>O: Update Price Feeds
    F->>O: Fetch Latest Prices
    F->>C: Check Loan Health
    C->>O: Validate Price Staleness
    C->>F: Return Health Status
    F->>U: Display Health Updates

3. Liquidation Flow

sequenceDiagram
    participant L as Liquidator
    participant F as Frontend
    participant C as Contract
    participant O as Oracle
    participant R as Rewards

    L->>F: Monitor Unhealthy Loans
    F->>C: Check Liquidation Eligibility
    C->>O: Verify Current Prices
    L->>C: Execute Liquidation
    C->>R: Distribute Rewards
    C->>F: Update Loan Status

🛡️ Security Architecture

Smart Contract Security

  • Audited Code: Professional security audit completed

  • Formal Verification: Critical functions mathematically verified

  • Bug Bounty: Ongoing security incentive program

  • Upgrade Mechanisms: Controlled upgrade paths

Oracle Security

  • Multiple Sources: Redundant price feed providers

  • Staleness Checks: Automatic price age validation

  • Circuit Breakers: Extreme price change protection

  • Fallback Systems: Backup oracle integration

Frontend Security

  • Input Validation: Client and server-side validation

  • XSS Protection: Content Security Policy headers

  • HTTPS Only: Encrypted communication

  • Wallet Security: Secure key management practices

⚡ Performance Architecture

Scalability Features

  • Somnia L1: 400k+ TPS capacity

  • Efficient Contracts: Gas-optimized smart contracts

  • Batch Operations: Multiple actions in single transaction

  • State Optimization: Minimal on-chain storage

Frontend Performance

  • Next.js Optimization: Static generation and caching

  • Code Splitting: Lazy loading of components

  • Image Optimization: Automatic image compression

  • CDN Integration: Global content delivery

Data Performance

  • Subgraph Indexing: Fast blockchain data queries

  • Caching Layers: Multiple levels of data caching

  • Parallel Fetching: Concurrent API requests

  • Pagination: Efficient large dataset handling

🔮 Future Architecture

Planned Enhancements

  • Multi-chain Support: Cross-chain lending bridges

  • Advanced Oracles: Chainlink integration

  • Layer 2 Scaling: Additional scaling solutions

  • Mobile Apps: Native iOS and Android applications

Governance Integration

  • DAO Structure: Decentralized governance implementation

  • Proposal System: Community-driven protocol updates

  • Voting Mechanisms: $DREAM token-based voting

  • Treasury Management: Community-controlled funds


This architecture enables DreamLend to provide institutional-grade P2P lending with amazing user experience on the fastest blockchain.

Last updated