Skip to content

heirlabs/defai-cli

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🚀 DeFAI Platform - Developer Guide

DeFAI Logo

The Future of Decentralized Finance with AI Collaboration

Solana Anchor TypeScript Next.js

Live Demo | Documentation | API Reference | Discord


🌟 Overview

DeFAI is a comprehensive decentralized finance ecosystem on Solana that merges traditional DeFi mechanics with AI-powered trading and digital estate planning. The platform enables users to:

  • 🎯 Swap legacy tokens for tiered NFTs with bonus rewards
  • 💰 Stake tokens for sustainable passive income
  • 🏛️ Manage digital estates with programmable inheritance
  • 🤖 Collaborate with AI agents for joint trading strategies
  • 🛍️ Deploy custom DeFi applications through our App Factory
  • 🔒 Secure operations with enterprise-grade security features
  • 📊 Monitor performance with comprehensive observability
  • 🧪 Test features with A/B testing and feature flags
  • 📈 Market with email campaigns and referral programs

🏗️ Architecture

Smart Contracts (Programs)

Program Address Description
defai_swap 5pmceM9vG9gpLCM8W7wTC92m8GsXnZEpE7wmbbHpFUeT Token-to-NFT exchange with vesting
defai_staking 6t8UH9GGn3ZRMkFvV5CqSe1Rs9fYzQpeEkv4hbDPG6zd Tiered staking system
defai_estate 5uSkqdymvdisnz5542buDEoriDsvopAwym9WpccuTpjg Digital inheritance management
defai_app_factory 4cxwMECNtqo5CEFYEU5aArZDL5CUs64H1imobByYA261 App marketplace & SFT minting

Tech Stack

graph TB
    subgraph Frontend
        A[Next.js 14.2.3] --> B[TypeScript]
        A --> C[Tailwind CSS]
        A --> D[Solana Wallet Adapter]
        A --> E[Framer Motion]
    end
    
    subgraph Backend
        F[Solana Blockchain] --> G[Anchor Framework 0.29.0]
        G --> H[Rust Programs]
        F --> I[Metaplex NFT Standards]
        J[Node.js API] --> K[Express.js]
        J --> L[MongoDB]
        J --> M[Redis Cache]
    end
    
    subgraph Infrastructure
        N[IPFS/Web3 Storage] --> O[Metadata Storage]
        P[Socket.io] --> Q[Real-time Updates]
        R[Monitoring Stack] --> S[Prometheus/Grafana]
        R --> T[ELK Stack]
        R --> U[Sentry]
    end
    
    subgraph Security
        V[Rate Limiting] --> W[Redis Store]
        X[Security Headers] --> Y[CSP/HSTS]
        Z[Input Validation] --> AA[Joi Schemas]
    end
    
    Frontend --> Backend
    Backend --> Infrastructure
    Backend --> Security
Loading

📁 Repository Structure

├── programs/              # Solana smart contracts
│   ├── defai_swap/       # Token-to-NFT swap program
│   ├── defai_staking/    # Banking/staking program
│   ├── defai_estate/     # Estate management program
│   └── defai_app_factory/# App marketplace program
├── frontend/             # Next.js web application
├── backend/              # Node.js API & services
├── scripts/              # Deployment & management scripts
├── tests/                # Comprehensive test suite
├── docs/                 # Platform documentation
├── cli/                  # Command-line tools
└── packages/             # Shared packages

Key Files:
├── STARTHERE.md          # Quick start guide
├── ROADMAP.md           # Development roadmap
├── Anchor.toml          # Anchor configuration
└── package.json         # Root package configuration

🚀 Quick Start

Prerequisites

  • Node.js 18+ and npm/yarn
  • Rust 1.70+ and Cargo
  • Solana CLI 1.18+
  • Anchor CLI 0.29.0

Installation

  1. Clone the repository

    git clone https://github.com/defai-ai/platform.git
    cd platform
  2. Install dependencies

    # Root dependencies
    npm install
    
    # Frontend dependencies
    cd frontend && npm install
    
    # Backend dependencies
    cd ../backend && npm install
  3. Set up environment variables

    # Copy example env files
    cp frontend/env.example frontend/.env.local
    cp backend/env.example backend/.env
    
    # Edit with your values
  4. Build Solana programs

    # Build all programs
    anchor build
    
    # Deploy to devnet
    anchor deploy --provider.cluster devnet
  5. Start development servers

    # Terminal 1: Start local validator
    solana-test-validator
    
    # Terminal 2: Frontend
    cd frontend && npm run dev
    
    # Terminal 3: Backend
    cd backend && npm run dev

📦 Program Development

Building a Program

// Example: programs/defai_swap/src/lib.rs
use anchor_lang::prelude::*;

declare_id!("5pmceM9vG9gpLCM8W7wTC92m8GsXnZEpE7wmbbHpFUeT");

#[program]
pub mod defai_swap {
    use super::*;
    
    pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
        // Program logic here
        Ok(())
    }
}

Testing

// Example: tests/defai_swap.ts
import * as anchor from "@coral-xyz/anchor";
import { Program } from "@coral-xyz/anchor";
import { DefaiSwap } from "../target/types/defai_swap";

describe("defai_swap", () => {
  const provider = anchor.AnchorProvider.env();
  anchor.setProvider(provider);
  
  const program = anchor.workspace.DefaiSwap as Program<DefaiSwap>;
  
  it("Initializes correctly", async () => {
    const tx = await program.methods
      .initialize()
      .rpc();
    console.log("Transaction signature:", tx);
  });
});

🎮 Frontend Development

Component Structure

// Example: frontend/src/components/SwapDashboard.tsx
import { useWallet } from '@solana/wallet-adapter-react';
import { useProgram } from '../hooks/useProgram';

export const SwapDashboard: React.FC = () => {
  const { publicKey } = useWallet();
  const program = useProgram();
  
  const handleSwap = async () => {
    // Implement swap logic
  };
  
  return (
    <div className="p-6 bg-gray-900 rounded-lg">
      <h2 className="text-2xl font-bold text-white">Token Swap</h2>
      {/* UI components */}
    </div>
  );
};

State Management

// Using Zustand for element store
import { create } from 'zustand';

interface ElementStore {
  elements: Element[];
  addElement: (element: Element) => void;
  removeElement: (id: string) => void;
}

export const useElementStore = create<ElementStore>((set) => ({
  elements: [],
  addElement: (element) => set((state) => ({ 
    elements: [...state.elements, element] 
  })),
  removeElement: (id) => set((state) => ({ 
    elements: state.elements.filter(e => e.id !== id) 
  })),
}));

🔧 Key Features Implementation

1. Token-to-NFT Swap

// Initialize swap
const swapTokensForNFT = async (tier: string, amount: number) => {
  const tx = await program.methods
    .swap(new BN(amount))
    .accounts({
      user: wallet.publicKey,
      tierMint: getTierMint(tier),
      // ... other accounts
    })
    .rpc();
};

2. Estate Management

// Create estate with beneficiaries
const createEstate = async (beneficiaries: PublicKey[], shares: number[]) => {
  const tx = await program.methods
    .createEstate(beneficiaries, shares)
    .accounts({
      authority: wallet.publicKey,
      estate: estateAccount,
      // ... other accounts
    })
    .rpc();
};

3. AI Agent Integration

// Set up joint account with AI
const setupJointAccount = async (strategy: 'conservative' | 'balanced' | 'aggressive') => {
  const encryptedKey = await encryptWallet(wallet.secretKey, password);
  
  const tx = await program.methods
    .createJointAccount(strategy, encryptedKey)
    .accounts({
      user: wallet.publicKey,
      aiAgent: AI_AGENT_PUBKEY,
      // ... other accounts
    })
    .rpc();
};

4. Staking Implementation

// Stake tokens based on tier
const stakeTokens = async (amount: number) => {
  const tier = getTierFromAmount(amount); // Gold, Titanium, or Infinite
  
  const tx = await program.methods
    .stake(new BN(amount))
    .accounts({
      user: wallet.publicKey,
      stakingAccount: stakingPDA,
      // ... other accounts
    })
    .rpc();
};

🔐 Security Features

Enterprise-Grade Security Implementation

The platform implements comprehensive security measures following OWASP best practices:

Rate Limiting

  • Redis-backed rate limiting for all API endpoints
  • Configurable limits per tier (Free: 100/hour, Pro: 1000/hour, Enterprise: 10000/hour)
  • Special protection for authentication endpoints (5 attempts per 15 minutes)
  • DDoS protection with automatic IP blocking
// Example rate limiting configuration
const rateLimiter = rateLimit({
  store: new RedisStore({ client: redis }),
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: (req) => getTierLimit(req.user?.tier),
  handler: (req, res) => {
    res.status(429).json({
      error: 'Too many requests',
      retryAfter: req.rateLimit.resetTime
    });
  }
});

Security Headers

  • Content Security Policy (CSP) preventing XSS attacks
  • HTTP Strict Transport Security (HSTS) enforcing HTTPS
  • X-Frame-Options preventing clickjacking
  • X-Content-Type-Options preventing MIME sniffing
  • Complete security headers middleware implementation

Input Validation

  • Joi-based validation for all API inputs
  • SQL injection prevention
  • XSS sanitization
  • File upload restrictions

Authentication & Authorization

  • JWT-based authentication with refresh tokens
  • Role-based access control (RBAC)
  • Multi-factor authentication support
  • Session management with Redis

Security Audit & Testing

Run the comprehensive security test suite:

# Run security tests
npm run security:test

# Generate security report
npm run security:audit

📊 Monitoring & Observability

Complete Monitoring Stack

The platform includes a production-ready monitoring stack with:

Metrics (Prometheus + Grafana)

  • Application metrics: Request rates, response times, error rates
  • Business metrics: User signups, transactions, revenue
  • Infrastructure metrics: CPU, memory, disk usage
  • Custom dashboards for different roles (DevOps, Business, Support)

Logging (ELK Stack)

  • Elasticsearch for log storage and search
  • Logstash for log processing and enrichment
  • Kibana for log visualization and analysis
  • Structured logging with correlation IDs

Error Tracking (Sentry)

  • Real-time error capture and alerting
  • Performance monitoring
  • Release tracking
  • User impact analysis

Distributed Tracing

  • Request flow visualization
  • Performance bottleneck identification
  • Service dependency mapping

Monitoring Setup

Deploy the complete monitoring stack:

# Deploy monitoring infrastructure
kubectl apply -f k8s/monitoring/

# Access dashboards
# Grafana: http://localhost:3000 (admin/admin)
# Kibana: http://localhost:5601
# Prometheus: http://localhost:9090

Key Metrics Tracked

  • SLIs: Availability, latency, error rate, throughput
  • Business KPIs: DAU, conversion rate, ARPU, churn
  • Security: Failed auth attempts, suspicious activities
  • Performance: API response times, database query performance

🧪 A/B Testing & Feature Flags

Feature Flag System

Control feature rollouts and run experiments with our built-in system:

// Using feature flags in code
import { useFeatureFlag } from '@/hooks/useFeatureFlag';

function MyComponent() {
  const isNewUIEnabled = useFeatureFlag('new-ui-design');
  
  return isNewUIEnabled ? <NewUI /> : <OldUI />;
}

A/B Testing Framework

Run controlled experiments to optimize conversions:

// Running an A/B test
import { useABTest } from '@/hooks/useABTest';

function PricingPage() {
  const variant = useABTest('pricing-experiment', {
    control: 'monthly',
    treatment: 'annual-discount'
  });
  
  return variant === 'treatment' ? 
    <AnnualPricing /> : <MonthlyPricing />;
}

Feature Management

  • Admin UI for non-technical users
  • Percentage rollouts for gradual deployments
  • User targeting by attributes
  • Kill switches for instant rollback
  • Experiment analytics integration

📧 Email Marketing & Referral System

Email Marketing Platform

Built-in email marketing capabilities:

  • Campaign Management: Create, schedule, and track campaigns
  • Segmentation: Target users based on behavior and attributes
  • Automation: Welcome series, re-engagement, milestone emails
  • Templates: Responsive HTML templates with personalization
  • Analytics: Open rates, click rates, conversion tracking

Referral Program

Comprehensive referral system with:

  • Multi-tier rewards: Referrer and referee benefits
  • Social sharing: One-click sharing to social platforms
  • Tracking: Attribution and conversion tracking
  • Leaderboards: Gamification elements
  • Fraud prevention: Anti-abuse mechanisms
// Example referral implementation
const referralCode = await referralService.generateCode(userId);
const shareUrl = `https://defai.ai/ref/${referralCode}`;

// Track referral conversion
await referralService.trackConversion(referralCode, newUserId, {
  rewardType: 'subscription_discount',
  rewardValue: 20 // 20% off
});

⚡ Performance Optimization

Optimization Features

  • Advanced Caching

    • Redis caching with compression
    • CDN integration for static assets
    • Database query result caching
    • API response caching
  • Database Optimization

    • Indexed queries for common operations
    • Connection pooling
    • Query optimization
    • Read replicas for scaling
  • Frontend Optimization

    • Code splitting and lazy loading
    • Image optimization with next/image
    • Bundle size optimization
    • PWA support for offline access
  • Request Optimization

    • Request deduplication
    • Batch API calls
    • GraphQL for efficient data fetching
    • WebSocket for real-time updates

Load Testing

Run comprehensive load tests:

# Run k6 load tests
npm run test:load

# Generate performance report
npm run test:load:report

# Test specific scenarios
k6 run -e SCENARIO=spike load-testing/k6-test.js

Performance Metrics

  • API Response Time: p50 < 100ms, p99 < 500ms
  • Page Load Time: < 3s on 3G networks
  • Time to Interactive: < 5s
  • Lighthouse Score: > 90

📊 Deployment

Mainnet Deployment

# 1. Build programs with mainnet configuration
anchor build -- --features mainnet

# 2. Deploy programs
anchor deploy --provider.cluster mainnet

# 3. Initialize program states
npm run init:mainnet

# 4. Deploy backend services
kubectl apply -f k8s/

# 5. Deploy frontend
cd frontend && npm run build
vercel --prod

# 6. Deploy monitoring stack
kubectl apply -f k8s/monitoring/

Production Configuration

Environment Variables

# Frontend .env.production
NEXT_PUBLIC_SOLANA_RPC_URL=https://api.mainnet-beta.solana.com
NEXT_PUBLIC_SWAP_PROGRAM_ID=5pmceM9vG9gpLCM8W7wTC92m8GsXnZEpE7wmbbHpFUeT
NEXT_PUBLIC_STAKING_PROGRAM_ID=6t8UH9GGn3ZRMkFvV5CqSe1Rs9fYzQpeEkv4hbDPG6zd
NEXT_PUBLIC_ESTATE_PROGRAM_ID=5uSkqdymvdisnz5542buDEoriDsvopAwym9WpccuTpjg
NEXT_PUBLIC_APP_FACTORY_PROGRAM_ID=4cxwMECNtqo5CEFYEU5aArZDL5CUs64H1imobByYA261
NEXT_PUBLIC_IPFS_GATEWAY=https://gateway.pinata.cloud
NEXT_PUBLIC_SENTRY_DSN=your-sentry-dsn

# Backend .env.production
NODE_ENV=production
MONGODB_URI=mongodb://mongo:27017/defai
REDIS_URL=redis://redis:6379
AI_AGENT_PRIVATE_KEY=<base58-private-key>
BREVO_API_KEY=<your-brevo-key>
SOCKET_PORT=3001
STRIPE_SECRET_KEY=<your-stripe-key>
STRIPE_WEBHOOK_SECRET=<your-webhook-secret>
SENTRY_DSN=<your-sentry-dsn>
PROMETHEUS_PUSHGATEWAY=http://pushgateway:9091
ELASTICSEARCH_URL=http://elasticsearch:9200

Kubernetes Resources

The platform includes production-ready Kubernetes manifests for:

  • API deployment with horizontal pod autoscaling
  • Background workers for async tasks
  • Monitoring stack (Prometheus, Grafana, ELK)
  • Redis cluster for caching and sessions
  • MongoDB replica set for data persistence

🧪 Testing Suite

Run comprehensive tests:

# Unit tests for all programs
anchor test

# Individual program tests
anchor test --program-name defai_swap
anchor test --program-name defai_staking
anchor test --program-name defai_estate

# Integration tests
npm run test:integration

# Frontend tests
cd frontend && npm run test

# E2E tests
npm run test:e2e

# Security tests
npm run security:test

# Load tests
npm run test:load

# Performance tests
npm run test:performance

🛠️ Development Tools

Element SDK

The DeFAI platform includes a powerful SDK for building custom elements:

# Install SDK packages
npm install @defai/element-sdk
npm install @defai/element-react

# Install CLI globally
npm install -g @defai/element-cli

# Create new element
defai-element create my-element

CLI Tool

The DeFAI CLI provides powerful commands for development:

# Install globally
npm install -g @defai/cli

# Available commands
defai-cli element create <name>     # Create new element
defai-cli element test              # Test element locally
defai-cli element publish           # Publish to marketplace
defai-cli account balance           # Check account balance
defai-cli program deploy            # Deploy programs

Related Repositories

📚 Documentation

🛡️ Security

Audit Status

  • Smart contracts audited by [Pending]
  • Frontend security review completed ✅
  • Penetration testing performed ✅
  • OWASP compliance verified ✅

Security Features

  • Rate limiting on all endpoints
  • Comprehensive security headers
  • Input validation and sanitization
  • SQL injection prevention
  • XSS protection
  • CSRF protection
  • DDoS mitigation

Best Practices

  • Never commit private keys or mnemonics
  • Use environment variables for sensitive data
  • Implement proper error handling
  • Validate all user inputs
  • Use program-derived addresses (PDAs) for authority
  • Enable per-user rate limiting
  • Implement comprehensive monitoring and alerting

🤝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📞 Support

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.


Built with ❤️ by the DeFAI Team

Website | GitHub | Discord

About

CLI

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published