Skip to content

dylanpersonguy/dcc-lending-protocol

Repository files navigation

DCC Lending Protocol

DCC Lending Protocol

A production-grade DeFi lending & borrowing protocol built for DecentralChain

License: MIT TypeScript RIDE Tests pnpm


Isolated-market lending with RIDE smart contracts, a full TypeScript SDK, oracle price feeds, automated liquidations, a real-time indexer API, and a React frontend — all in one monorepo.

Protocol Spec · State Schema · Architecture Decisions · Security Model


Caution

This protocol is in active development (MVP / v1). It has not been externally audited. Do not deploy to mainnet with real funds until a thorough security audit is complete.


✦ Why DCC Lend?

Most DeFi lending protocols target EVM chains. DCC Lend is purpose-built for the DecentralChain ecosystem — a Waves-derived, account-model blockchain with RIDE smart contracts. Every design choice optimizes for RIDE's strengths: deterministic execution, on-chain key-value storage, and composable InvokeScript transactions.

⚡ Core Protocol

  • Isolated markets — no cross-collateral contagion
  • Kinked interest rate model — capital-efficient two-slope curves
  • Partial liquidations — bounded risk reduction with configurable close factors
  • Integer-only mathbigint everywhere, explicit rounding (down for health, up for debt)
  • Oracle price feeds — multi-source with staleness & circuit breaker checks

🛡️ Security Posture

  • 22 protocol invariants — verified at every state transition
  • Admin-curated markets — no permissionless asset listing
  • Emergency pause system — per-market and global kill switches
  • Role-based access — admin, guardian, oracle feeder separation
  • Comprehensive threat model — documented attack surfaces and mitigations

✦ Architecture

                        ┌─────────────────────────────────┐
                        │        DecentralChain           │
                        │                                 │
                        │   ┌───────────────────────┐     │
                        │   │   Lending Pool (RIDE)  │     │
                        │   │                       │     │
                        │   │  deposit · withdraw   │     │
                        │   │  borrow  · repay      │     │
                        │   │  liquidate · accrue   │     │
                        │   │  updatePrice · admin  │     │
                        │   └───────────┬───────────┘     │
                        │               │                 │
                        └───────────────┼─────────────────┘
                                        │
              ┌─────────────────────────┼─────────────────────────┐
              │                         │                         │
     ┌────────▼────────┐     ┌──────────▼─────────┐    ┌────────▼────────┐
     │  Oracle Publisher│     │  Liquidation Bot   │    │    Indexer      │
     │                 │     │                    │    │    + REST API   │
     │  Binance        │     │  Position Scanner  │    │                │
     │  CoinGecko      │     │  Risk Evaluator    │    │  Block Poller  │
     │  Deviation Gate │     │  Profit Calculator │    │  Drizzle ORM   │
     │  Circuit Breaker│     │  Tx Executor       │    │  Fastify       │
     └─────────────────┘     └────────────────────┘    └───────┬────────┘
                                                               │
                                                     ┌─────────▼─────────┐
                                                     │   Frontend dApp   │
                                                     │                   │
                                                     │  React · Vite     │
                                                     │  TailwindCSS      │
                                                     │  TanStack Query   │
                                                     └───────────────────┘

✦ Monorepo Packages

This project uses a pnpm workspace monorepo with 8 focused packages:

Package Purpose Key Tech
dcc-lend-core RIDE smart contracts & deployment scripts RIDE
dcc-lend-sdk Math helpers, risk engine, tx builders, types TypeScript, bigint
dcc-lend-config Chain configs, market definitions, risk bounds Zod schemas
dcc-lend-oracle Multi-source oracle price publisher Binance, CoinGecko
dcc-lend-liquidator Automated liquidation bot with profitability checks pino logging
dcc-lend-indexer Block indexer + Fastify REST API PostgreSQL, Drizzle ORM
dcc-lend-web Frontend dApp React 18, Vite, TailwindCSS
dcc-lend-devops Docker, CI/CD, monitoring, deployment Docker Compose, GitHub Actions

✦ Quick Start

Prerequisites

Tool Version Purpose
Node.js >= 20 Runtime
pnpm >= 9 Package manager
Docker Latest PostgreSQL + containerized services
PostgreSQL >= 16 Indexer database

Install & Build

# Clone the repository
git clone https://github.com/dylanpersonguy/dcc-lending-protocol.git
cd dcc-lending-protocol

# Install all dependencies
pnpm install

# Build shared packages
pnpm --filter dcc-lend-config build
pnpm --filter dcc-lend-sdk build

# Run the full test suite (128 tests)
pnpm --filter dcc-lend-sdk test

Environment Setup

cp .env.example .env
# .env — minimal configuration
NODE_URL=https://nodes-testnet.wavesnodes.com
CONTRACT_ADDRESS=3N...your_contract_address
DATABASE_URL=postgresql://dcc:dcc_local_dev@localhost:5432/dcc_lend
CHAIN_ID=T
MARKET_IDS=DCC_USDN,BTC_USDN,ETH_USDN

Run Services

# Start PostgreSQL + all services with Docker
cd packages/dcc-lend-devops/docker
docker compose up -d

# — OR — run individual services in dev mode:
pnpm --filter dcc-lend-indexer dev     # Indexer + API on :3100
pnpm --filter dcc-lend-web dev         # Frontend on :5173
pnpm --filter dcc-lend-oracle dev      # Oracle publisher
pnpm --filter dcc-lend-liquidator dev  # Liquidation bot

✦ Protocol Mechanics

Interest Rate Model

DCC Lend uses a kinked two-slope model for capital-efficient rate curves:

Rate
 │                              ╱
 │                            ╱
 │                          ╱    ← slope₂ (steep)
 │                        ╱
 │              ─────────╱ kink
 │            ╱
 │          ╱  ← slope₁ (gentle)
 │        ╱
 │──────╱
 └─────────────────────────────── Utilization
 0%           80% (kink)      100%

Below the kink: rate = base + slope₁ × (util / kink) Above the kink: rate = base + slope₁ + slope₂ × (util − kink) / (1 − kink)

Math Precision

Constant Value Purpose
BPS_BASE 10,000 Basis points (1 bps = 0.01%)
INDEX_PRECISION 10¹⁸ Borrow/supply index scaling
PRICE_PRECISION 10⁶ Oracle price scaling
SECONDS_PER_YEAR 31,536,000 Rate annualization

Rounding Policy

Context Direction Rationale
Health factor Down Conservative — protects protocol
Borrow power Down Conservative — limits over-borrowing
Debt calculation Up Protocol never under-counts obligations
Interest accrual Up Lenders never receive less than owed
Liquidation seized Down Liquidator receives less in edge cases

✦ API Endpoints

The indexer exposes a RESTful API on port 3100:

Method Endpoint Description
GET /health Service health + last indexed block
GET /api/v1/markets All markets
GET /api/v1/markets/:id Single market detail
GET /api/v1/markets/:id/positions Positions in a market (paginated)
GET /api/v1/markets/:id/history Historical snapshots
GET /api/v1/users/:addr/positions All positions for a wallet
GET /api/v1/oracle/prices Current oracle prices
GET /api/v1/events Protocol events (filterable)
GET /api/v1/stats Aggregate protocol statistics

✦ Testing

# Run all SDK unit tests (128 tests across 4 suites)
pnpm --filter dcc-lend-sdk test

# Watch mode
pnpm --filter dcc-lend-sdk test:watch

Test suites:

Suite Tests Coverage
math.test.ts 44 divDown, divUp, mulDivDown, mulDivUp, bpsMul, clamp
interest.test.ts 39 Utilization, borrow/supply rates, accrual, index updates
risk.test.ts 32 Health factor, borrow power, liquidation quotes, max withdrawable
contract-logic.test.ts 13 Full lifecycle, liquidation flows, edge cases, invariants

✦ Project Structure

dcc-lending-protocol/
├── .github/workflows/         # CI/CD pipelines
│   ├── ci.yml                 # Lint → Typecheck → Test → Build → Docker
│   └── deploy.yml             # Testnet deployment
├── docs/
│   ├── specs/                 # Protocol spec, state schema
│   ├── adrs/                  # 5 Architecture Decision Records
│   └── security/              # Threat model, operational checklist
├── packages/
│   ├── dcc-lend-config/       # Shared constants, schemas, key builders
│   ├── dcc-lend-sdk/          # Core math, risk engine, tx builders
│   ├── dcc-lend-core/         # RIDE contract + deploy scripts
│   ├── dcc-lend-oracle/       # Price feed publisher service
│   ├── dcc-lend-liquidator/   # Liquidation bot service
│   ├── dcc-lend-indexer/      # Block indexer + Fastify API
│   ├── dcc-lend-web/          # React frontend
│   └── dcc-lend-devops/       # Docker, monitoring, scripts
├── package.json               # Root workspace config
├── pnpm-workspace.yaml
└── tsconfig.json              # Shared TypeScript config

✦ Documentation

Document Description
Protocol Specification Complete protocol mechanics (400+ lines)
State Schema All on-chain key-value patterns
Threat Model Attack surfaces, invariants, emergency procedures
ADR-001: Isolated Markets Why no shared collateral pools
ADR-002: Integer Math Rounding policy rationale
ADR-003: Kinked Interest Rate Two-slope model design
ADR-004: RIDE Architecture Contract design patterns
ADR-005: Partial Liquidation Liquidation mechanics

✦ Design Principles

🔒Security FirstEvery state transition is validated against 22 protocol invariants
🧮Deterministic MathInteger-only arithmetic with explicit rounding — no floating point anywhere
🏗️Minimal & AuditableNo flash loans, no leverage loops, no complex composability — just clean lending
🧱Isolated MarketsEach market is independent — a bad oracle in one market can't cascade
🛑Emergency ReadyPer-market pause, global pause, guardian role, admin transfer with acceptance
📐Partial LiquidationsConfigurable close factor prevents value extraction and market manipulation

✦ Security

This protocol manages financial assets. Before any mainnet deployment:

  • Complete external smart contract audit
  • Economic attack simulation (oracle manipulation, liquidation cascading)
  • Formal verification of core invariants
  • Bug bounty program established
  • Multi-sig admin governance deployed

See the full Threat Model and Operational Checklist.


✦ Contributing

Contributions are welcome. Please:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feat/my-feature)
  3. Write tests for new functionality
  4. Ensure all 128+ tests pass (pnpm --filter dcc-lend-sdk test)
  5. Open a Pull Request

✦ License

This project is licensed under the MIT License.



Built for DecentralChain · Powered by RIDE · TypeScript SDK

Made with precision by @dylanpersonguy

About

A production-grade DeFi lending & borrowing protocol for DecentralChain — featuring RIDE smart contracts, TypeScript SDK, oracle publisher, liquidation bot, indexer API, and React frontend.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages