Skip to content

AndresNinou/MagicPay

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

12 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

MagicPay - AI-Agent Crypto-to-Fiat Bridge

Ethereum FastAPI Next.js PYUSD ASI Agents MCP TheGraph Fern Dynamic Hardhat Nora AI Zircuit

🎯 Problem Statement

The fundamental barrier to crypto adoption is the recipient onboarding problem:

πŸ€” The Core Challenge

"I have crypto, but my family/friends don't know how to receive it"

Crypto holders face a critical dilemma: They want to send value using their digital assets, but recipients lack the knowledge, tools, or willingness to interact with crypto directly.

🚫 Crypto Onboarding Barriers

  • Technical complexity: Wallet setup, seed phrases, gas fees
  • Fear and confusion: "What is MetaMask? How do I keep my crypto safe?"
  • Learning curve: Understanding addresses, networks, transaction confirmations
  • Security concerns: "What if I lose my private key?"

⏰ Current Broken Solutions

  • Force education: "Just download a wallet and I'll teach you" β†’ 90% never follow through
  • Centralized exchanges: Require KYC, high fees, still complex for beginners
  • P2P meetups: Unsafe, inconvenient, doesn't scale
  • Traditional rails: Convert to fiat, use banks β†’ defeats the purpose of crypto

πŸ“Š The Gap

  • 1 billion+ people own cryptocurrency globally
  • 85% of recipients have never used a crypto wallet
  • $2.8 trillion crypto market cap trapped by usability barriers
  • Family remittances represent 40% of desired crypto use cases

🚧 Real-World Impact

  • Crypto holders can't easily help family members financially
  • Cross-border payments still rely on expensive traditional systems
  • Financial inclusion remains limited despite crypto's potential
  • Mass adoption stalled by the "last mile" problem

πŸš€ Our Solution

MagicPay eliminates crypto onboarding barriers with two powerful modes that cater to different user preferences:

πŸŽ›οΈ Dual-Mode Experience

πŸ“‹ 1. Traditional Mode

Classic Web Interface - Familiar point-and-click experience

  • βœ… Web app at magicpay.live
  • βœ… Standard forms and buttons
  • βœ… Perfect for users comfortable with typical crypto interfaces

πŸ€– 2. Agent Mode (AI-Powered)

Natural Language Crypto Operations - Revolutionary AI-first approach

Powered by cutting-edge AI infrastructure:

  • 🧠 ASI Agents Framework: Autonomous agents that understand crypto operations
  • πŸ”— MCP Integration: Model Context Protocol for seamless AI-wallet communication
  • πŸ“Š TheGraph Protocol: Real-time blockchain data and analytics
  • πŸ’¬ Natural Language: "Send $100 PYUSD to mom@email.com for groceries"

Agent Mode Benefits:

  • πŸ’¬ Conversational Interface: Talk to your crypto like a financial assistant
  • πŸš€ Zero Learning Curve: No need to understand wallets, gas, or addresses
  • πŸ”„ Smart Automation: AI handles complex blockchain interactions
  • πŸ“± Voice & Text: Multiple interaction modalities
  • 🌐 Multi-Platform: Web, Telegram Mini Apps, and more

✨ Core Innovation: "Send Crypto, Receive Choice"

The breakthrough: Recipients don't need to understand crypto, set up wallets, or learn blockchain technology. They simply receive money in their preferred method.

🎯 How We Solve the Onboarding Problem

  1. πŸ”— Email-Only Recipients: Send to any email address - no wallet needed
  2. πŸ›οΈ Direct Bank Deposits: Recipients get local currency in their existing bank account
  3. πŸ“± Stripe-Like Experience: Familiar, trusted UX that anyone can use
  4. πŸ€– AI-Assisted Onboarding: Agent Mode guides users through natural conversation
  5. πŸ”’ Secure Escrow: 30-day protection - no risk for senders or recipients
  6. ⚑ Instant Value Transfer: Crypto speed with traditional convenience
  7. 🌍 Global Reach: Works anywhere with email and banking

πŸ’‘ The MagicPay Advantage

For Crypto Holders (Senders):

  • βœ… Traditional Mode: Send PYUSD from your wallet with familiar interface
  • βœ… Agent Mode: "Send $50 to John for dinner" - AI handles everything
  • βœ… No need to teach recipients about crypto
  • βœ… Full blockchain transparency and control
  • βœ… Escrow protection with automatic refunds

For Non-Crypto Recipients:

  • βœ… Just click an email link - no app downloads
  • βœ… Choose bank deposit or (optionally) learn crypto
  • βœ… Familiar form experience like online shopping
  • βœ… Get local currency in existing bank account
  • βœ… No wallet setup, seed phrases, or gas fees

πŸ”§ How We Solve It

graph TB
    subgraph "Traditional Remittance"
        A1[Sender] --> B1[Local Bank]
        B1 --> C1[SWIFT Network]
        C1 --> D1[Correspondent Bank]
        D1 --> E1[Recipient Bank]
        E1 --> F1[Recipient]
        
        style B1 fill:#ffcccc
        style C1 fill:#ffcccc
        style D1 fill:#ffcccc
        style E1 fill:#ffcccc
    end
    
    subgraph "MagicPay Solution"
        A2[Sender] --> B2[MagicPay dApp]
        B2 --> C2[Smart Contract Escrow]
        C2 --> D2[PYUSD Transfer]
        D2 --> E2[Fern Off-Ramp API]
        E2 --> F2[Recipient Bank Account]
        
        style B2 fill:#ccffcc
        style C2 fill:#ccffcc
        style D2 fill:#ccffcc
        style E2 fill:#ccffcc
    end
Loading

πŸ—οΈ Technology Architecture

🌐 System Overview

graph TB
    subgraph "Frontend Layer"
        FE1[Next.js Web App]
        FE2[React Components]
        FE3[Web3 Integration]
    end
    
    subgraph "API Layer"
        API1[FastAPI Backend]
        API2[Authentication]
        API3[Transfer Logic]
        API4[Fern Integration]
    end
    
    subgraph "Blockchain Layer"
        BC1[Ethereum Mainnet]
        BC2[Sepolia Testnet]
        BC3[Smart Contracts]
        BC4[PYUSD Token]
    end
    
    subgraph "Data Layer"
        DB1[PostgreSQL]
        DB2[Transfer Records]
        DB3[User Profiles]
    end
    
    subgraph "External Services"
        EXT1[Fern Off-Ramp API]
        EXT2[Alchemy RPC]
        EXT3[Mailgun Emails]
    end
    
    FE1 --> API1
    FE3 --> BC3
    API1 --> DB1
    API4 --> EXT1
    API1 --> BC3
    BC3 --> BC4
    
    style FE1 fill:#e1f5fe
    style API1 fill:#f3e5f5
    style BC3 fill:#fff3e0
    style DB1 fill:#e8f5e8
    style EXT1 fill:#fce4ec
Loading

πŸ“‹ Component Breakdown

Component Technology Purpose Network
Frontend Next.js 14, React 18, TailwindCSS User interface for transfers and claims Web
Backend FastAPI, Python 3.12, SQLAlchemy Business logic and API endpoints Server
Smart Contracts Solidity, Hardhat, OpenZeppelin Secure escrow with timeout protection Ethereum
Database PostgreSQL, Prisma ORM User profiles and transaction records Server
Stablecoin PYUSD (PayPal USD) Price-stable digital currency Ethereum
Off-Ramp Fern API Bank deposit integration External

πŸ”„ User Flow & Process

πŸ“€ Send Money Process

sequenceDiagram
    participant S as Sender
    participant FE as Frontend
    participant BE as Backend
    participant SC as Smart Contract
    participant PY as PYUSD Token
    
    S->>FE: 1. Enter recipient email & amount
    FE->>BE: 2. Create transfer record
    BE-->>FE: 3. Return transfer ID & claim token
    
    FE->>S: 4. Request PYUSD approval
    S->>PY: 5. Approve PYUSD spending
    
    FE->>SC: 6. Execute escrow deposit
    SC->>PY: 7. Transfer PYUSD to escrow
    SC-->>FE: 8. Return transaction hash
    
    FE->>BE: 9. Confirm transaction
    BE->>BE: 10. Update transfer status to "FUNDED"
    BE->>S: 11. Send email notification
Loading

πŸ’Έ Claim Money Process

sequenceDiagram
    participant R as Recipient
    participant FE as Frontend  
    participant BE as Backend
    participant F as Fern API
    participant B as Bank Account
    
    R->>FE: 1. Access claim link from email
    FE->>BE: 2. Validate claim token
    BE-->>FE: 3. Return transfer details
    
    R->>FE: 4. Choose claim method (Bank/Crypto)
    
    alt Bank Deposit
        FE->>BE: 5. Initiate Fern flow
        BE->>F: 6. Create payment account
        F-->>BE: 7. Return hosted form URL
        BE-->>FE: 8. Redirect to Fern form
        
        R->>F: 9. Complete bank details
        F-->>FE: 10. Redirect back with completion
        
        FE->>BE: 11. Complete payout
        BE->>F: 12. Create transaction
        F->>B: 13. Bank deposit
    else Crypto Claim
        FE->>BE: 5. Request crypto claim
        BE->>SC: 6. Execute contract claim
        SC->>PY: 7. Transfer PYUSD to recipient
    end
Loading

πŸ” Smart Contract Architecture

πŸ“‹ MagicPayEscrow Contract

Contract Address (Sepolia): 0x71Dbaa17656BdcFa40d5D8F36833477d99d2e17A PYUSD Token (Sepolia): 0xCaC524BcA292aaade2DF8A05cC58F0a65B1B3bB9

contract MagicPayEscrow {
    struct Deposit {
        address sender;          // Who sent the funds
        uint256 amount;          // Amount in PYUSD wei (6 decimals)
        uint256 timestamp;       // When deposit was created
        bool claimed;           // Whether funds were claimed
    }
    
    mapping(bytes32 => Deposit) public deposits;
    uint256 public constant TIMEOUT_PERIOD = 30 days;
    
    function createDeposit(uint256 amount, bytes32 claimToken) external;
    function claimDeposit(bytes32 claimToken) external;
    function refundDeposit(bytes32 claimToken) external;
}

πŸ›‘οΈ Security Features

graph TB
    subgraph "Smart Contract Security"
        SC1[Access Control]
        SC2[Reentrancy Protection]
        SC3[Overflow Protection]
        SC4[Event Logging]
    end
    
    subgraph "Escrow Protection"
        ES1[30-Day Timeout]
        ES2[Unique Claim Tokens]
        ES3[Single Claim Only]
        ES4[Automatic Refunds]
    end
    
    subgraph "Backend Security"
        BE1[Input Validation]
        BE2[Database Encryption]
        BE3[API Rate Limiting]
        BE4[Secure Headers]
    end
    
    SC1 --> ES1
    SC2 --> ES2
    SC3 --> ES3
    SC4 --> ES4
    
    style SC1 fill:#ffebee
    style ES1 fill:#e8f5e8
    style BE1 fill:#f3e5f5
Loading

πŸ’Ύ Database Schema

πŸ“Š Entity Relationship Diagram

erDiagram
    User ||--o{ Transfer : creates
    User ||--o{ Transfer : receives
    
    User {
        string id PK
        string email
        string walletAddress
        timestamp createdAt
    }
    
    Transfer {
        string id PK
        string senderId FK
        string recipientId FK
        string recipientEmail
        decimal amountUSD
        string amountPYUSD
        string status
        string claimToken
        string onChainTxHash
        string offRampTxId
        timestamp createdAt
        timestamp updatedAt
    }
Loading

πŸ“ˆ Transfer Status Flow

stateDiagram-v2
    [*] --> PENDING : Transfer Created
    PENDING --> FUNDED : Escrow Deposit Complete
    FUNDED --> CLAIMED_CRYPTO : Direct Crypto Claim
    FUNDED --> CLAIMED_BANK : Fern Bank Payout
    FUNDED --> REFUNDED : 30-Day Timeout
    CLAIMED_CRYPTO --> [*]
    CLAIMED_BANK --> [*] 
    REFUNDED --> [*]
    
    note right of PENDING : Awaiting blockchain transaction
    note right of FUNDED : PYUSD locked in escrow
    note right of CLAIMED_CRYPTO : Recipient received crypto
    note right of CLAIMED_BANK : Recipient received fiat
    note right of REFUNDED : Sender received refund
Loading

🌍 Network Configuration

⚑ Supported Networks

Network Chain ID PYUSD Address Status
Ethereum Mainnet 1 0x6c3ea9036406852006290770BEdFcAbA0e23A0e8 🟒 Production
Sepolia Testnet 11155111 0xCaC524BcA292aaade2DF8A05cC58F0a65B1B3bB9 🟑 Testing

πŸ”§ Environment Variables

# Backend Configuration
DATABASE_URL="postgresql://user:pass@host:port/db"
SECRET_KEY="your-secret-key"
FERN_API_KEY="fern-production-key"

# Blockchain Configuration  
BASE_SEPOLIA_RPC_URL="https://eth-sepolia.g.alchemy.com/v2/YOUR_KEY"
ETHEREUM_MAINNET_RPC_URL="https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY"
OPERATOR_PRIVATE_KEY="0x..."
ESCROW_CONTRACT_ADDRESS="0x71Dbaa17656BdcFa40d5D8F36833477d99d2e17A"

# Email Configuration
MAILGUN_API_KEY="your-mailgun-key"
MAILGUN_DOMAIN="your-domain.mailgun.org"

πŸš€ Quick Start Guide

πŸ“‹ Prerequisites

  • Node.js: 18+
  • Python: 3.12+
  • PostgreSQL: 14+
  • Git: Latest

πŸ”§ Installation

  1. Clone Repository
git clone https://github.com/yourusername/MagicPay.git
cd MagicPay
  1. Backend Setup
cd backend
python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate
pip install -r requirements.txt

# Setup database
createdb magicpay
cp .env.example .env
# Edit .env with your configuration

# Run migrations
python -m alembic upgrade head

# Start server
uvicorn app.main:app --reload --port 8000
  1. Frontend Setup
cd frontend
npm install
cp .env.local.example .env.local
# Edit .env.local with your configuration

# Start development server
npm run dev
  1. Smart Contracts Setup
cd contracts
npm install
cp .env.example .env
# Edit .env with your configuration

# Compile contracts
npx hardhat compile

# Run tests
npx hardhat test

# Deploy to testnet
npm run deploy:sepolia

πŸ§ͺ Testing

# Backend tests
cd backend
pytest

# Frontend tests  
cd frontend
npm test

# Smart contract tests
cd contracts
npx hardhat test

# Integration tests
npm run test:integration

πŸ“‘ API Documentation

πŸ”— Core Endpoints

Transfer Management

POST /api/v1/transfers/create

{
  "recipientEmail": "user@example.com",
  "amountUSD": 100.00,
  "senderWallet": "0x..."
}

POST /api/v1/transfers/execute

{
  "transferId": "uuid",
  "txHash": "0x..."
}

POST /api/v1/transfers/complete

{
  "claimToken": "secure-token",
  "recipientId": "uuid",
  "claimMethod": "bank|crypto"
}

Fern Integration

POST /api/v1/transfers/complete-fern-return

{
  "claimToken": "secure-token"
}

GET /api/v1/transfers/fern-status/{claimToken}

{
  "status": "completed|pending|failed",
  "customerStatus": "active|pending"
}

πŸ“Š Response Format

{
  "status": "success|error",
  "data": {
    "transferId": "uuid",
    "claimToken": "secure-token",
    "blockchainTxHash": "0x...",
    "status": "FUNDED"
  },
  "message": "Transfer completed successfully"
}

πŸ”’ Security & Compliance

πŸ›‘οΈ Security Measures

  • Smart Contract Auditing: OpenZeppelin patterns
  • Access Control: Role-based permissions
  • Input Validation: Comprehensive sanitization
  • Rate Limiting: API request throttling
  • Encryption: Database field encryption
  • Secure Headers: CSRF/XSS protection

βš–οΈ Compliance Features

  • Transaction Logging: Complete audit trails
  • KYC Integration: Fern API compliance
  • AML Monitoring: Suspicious activity detection
  • Data Privacy: GDPR compliance ready
  • Regulatory Reporting: Export capabilities

πŸ“ˆ Performance & Scaling

⚑ Performance Metrics

Metric Target Current
API Response Time <200ms 150ms
Transaction Confirmation <30 seconds 25 seconds
Database Queries <50ms 35ms
Frontend Load Time <3 seconds 2.1 seconds
Uptime 99.9% 99.95%

πŸš€ Scaling Strategy

graph TB
    subgraph "Current Architecture"
        A1[Single Backend Instance]
        A2[Single Database]
        A3[Single Frontend Deploy]
    end
    
    subgraph "Scaled Architecture"
        B1[Load Balancer]
        B2[Backend Cluster]
        B3[Database Cluster]
        B4[CDN Distribution]
        B5[Redis Cache]
    end
    
    A1 --> B1
    A2 --> B3
    A3 --> B4
    
    B1 --> B2
    B2 --> B5
    B5 --> B3
Loading

🀝 Contributing

πŸ“ Development Workflow

  1. Fork Repository
  2. Create Feature Branch: git checkout -b feature/awesome-feature
  3. Commit Changes: git commit -m 'Add awesome feature'
  4. Run Tests: npm test && pytest
  5. Push Branch: git push origin feature/awesome-feature
  6. Open Pull Request

🎯 Code Standards

  • Backend: Black formatting, PEP 8 compliance
  • Frontend: ESLint, Prettier formatting
  • Solidity: Solhint linting, OpenZeppelin patterns
  • Git: Conventional commit messages

πŸ—ΊοΈ Roadmap

Last Updated: August 17, 2025

πŸ”₯ Phase 1: MVP βœ…

  • Basic transfer functionality
  • Smart contract escrow (Sepolia deployment)
  • Fern integration with hosted bank forms
  • Web interface at magicpay.live
  • PYUSD network auto-detection
  • Traditional mode with full functionality

πŸ€– Phase 2: AI Integration 🚧

  • ASI Agents Framework integration
  • MCP (Model Context Protocol) implementation
  • TheGraph Protocol for blockchain analytics
  • Agent Mode Launch
  • Natural language transaction processing
  • Voice interface integration
  • Conversational UX optimization

πŸ“± Phase 3: Multi-Platform Expansion

  • Mobile app (React Native)
  • WhatsApp integration
  • Discord bot integration
  • Advanced AI assistant features

🌟 Phase 4: Scale & Enterprise

  • Ethereum Mainnet deployment
  • Layer 2 integration (Polygon, Arbitrum, Base)
  • Multi-currency support (USDC, USDT, DAI)
  • Enterprise API and white-label solutions
  • Global partnerships and regulatory compliance

🌐 Live App: magicpay.live
πŸ“± Telegram: Available as Telegram Mini App (Q4 2025)


Built with ❀️ by the MagicPay Team

Transforming cross-border remittances through blockchain technology

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors