hackquest logo

SubPay Automator

SubPay Automator is a decentralized subscription management platform that combines AI intelligence with blockchain technology to automate recurring payments

ビデオ

説明

SubPay Automator 🚀

AI-Powered Web3 Subscription Management on Monad Testnet

SubPay Automator is a decentralized subscription management platform that combines AI intelligence with blockchain technology to automate recurring payments. Built for the Monad Hackathon, it leverages MetaMask Smart Accounts, Delegation Toolkit, Envio indexing, and Gemini AI to provide a seamless Web3 subscription experience.

Site live link: https://subpay-automator.lovable.app/

Table of Contents


🎯 Introduction

SubPay Automator solves the problem of managing multiple digital subscriptions across platforms that traditionally only accept fiat currency. By bridging Web3 wallets with traditional payment rails, users can:

  • Automate payments using crypto assets (MON tokens)

  • Get AI-powered recommendations for new subscriptions

  • Track spending across all subscriptions in one dashboard

  • Convert crypto to fiat seamlessly for merchant payments

  • Manage delegations to allow AI agents to execute payments on your behalf

The platform targets Web3 users who want to use their crypto assets for everyday subscriptions like Netflix, Spotify, and productivity tools, while maintaining full control through MetaMask Smart Accounts.


💡 Use Cases

1. Automated Subscription Payments

Users delegate payment permissions to the SubPay AI agent, which monitors due dates and automatically converts crypto to fiat for payment execution—no manual signing required for recurring charges.

2. AI-Driven Subscription Discovery

Based on your interests and past subscriptions, the Gemini AI recommends new services, calculates cost optimization opportunities, and suggests cancellations for unused subscriptions.

3. Multi-Currency Support

The platform supports both USD and INR, with automatic conversion rates calculated in real-time, making it accessible to global users.

4. Transparent On-Chain Logging

All payment activities are logged on-chain via Monad smart contracts and indexed by Envio for transparent audit trails and analytics.

5. Low Balance Alerts

AI monitors your wallet balance and alerts you before payments fail, with automatic top-up suggestions based on upcoming dues.


🔄 How It Works

End-to-End Payment Flow

🏗️ Architecture

System Architecture Diagram

Data Flow Architecture

User Wallet (MetaMask) 
    ↓ [delegation granted]
AI Agent (SubPay)
    ↓ [monitors subscriptions]
Smart Contract (Monad)
    ↓ [emits events]
Envio Indexer
    ↓ [indexes & stores]
Dashboard (React)
    ↓ [displays to user]


-


🛠️ Technology Stack

Core Technologies

Technology

Purpose

Integration

React 18

Frontend framework

Component-based UI architecture

TypeScript

Type safety

End-to-end type checking

Vite

Build tool

Fast development server

Tailwind CSS

Styling

Utility-first responsive design

shadcn/ui

Component library

Pre-built accessible components

Web3 Stack

Technology

Purpose

Integration

Wagmi 2.x

React hooks for Ethereum

Wallet connection & blockchain interactions

Viem

Ethereum client

Low-level blockchain operations

MetaMask SDK

Smart Account integration

ERC-4337 account abstraction

Delegation Toolkit

Permission management

Gasless transactions & automated actions

Blockchain Infrastructure

Technology

Purpose

Integration

Monad Testnet

Layer 1 blockchain

EVM-compatible testnet for smart contracts & transactions

Envio HyperIndex

Event indexing

Real-time blockchain data querying

Envio HyperSync

Fast data sync

Efficient historical data retrieval

Monad Testnet Details

Network Information:

RPC Endpoints:

  • Primary: https://testnet-rpc.monad.xyz (QuickNode - 25 rps, batch requests: 100, archive support)

  • Alternative: https://rpc.ankr.com/monad_testnet (Ankr - 300 reqs/10s)

  • Monad Foundation: https://rpc-testnet.monadinfra.com (20 rps, archive support)

WebSocket Endpoints:

  • wss://testnet-rpc.monad.xyz

  • wss://rpc-testnet.monadinfra.com

Key Testnet Contracts:

  • USDC (testnet): 0xf817257fed379853cDe0fa4F97AB987181B1E5Ea

  • USDT (testnet): 0x88b8E2161DEDC77EF4ab7585569D2415a1C1055D

  • WBTC (testnet): 0xcf5a6076cfa32686c0Df13aBaDa2b40dec133F1d

  • Wrapped Monad: 0x760AfE86e5de5fa0Ee542fc7B7B713e1c5425701

  • Multicall3: 0xcA11bde05977b3631167028862bE2a173976CA11

AI Integration

Technology

Purpose

Integration

Google Gemini 2.0 Flash

Large Language Model

Subscription recommendations & chat

Gemini API

REST API

Direct HTTP calls from frontend


✨ Feature Breakdown

1. MetaMask Smart Account Integration

File: src/components/WalletConnect.tsx

How it works:

  • Uses Wagmi's useAccount and useConnect hooks to connect to MetaMask

  • Detects if user has MetaMask Smart Account capabilities

  • Displays wallet address and MON balance in real-time

  • Supports ERC-4337 account abstraction for gasless transactions

Resource Integration:

  • MetaMask SDK: Provides Smart Account detection and connection

  • Wagmi: Handles React state management for wallet connection

  • Monad Testnet: Chain configuration for Monad network

Code Example:

const { address, isConnected } = useAccount();
const { connect, connectors } = useConnect();
const { data: balance } = useBalance({
  address,
  chainId: 10143, // Monad testnet
});

2. Monad Network Integration & Setup Helper

Files:

  • src/config/monad.ts - Monad Testnet chain configuration

  • src/config/wagmi.ts - Wagmi configuration for Monad

  • src/components/AddMonadNetwork.tsx - Network setup UI component

How it works:

  1. Chain Configuration (src/config/monad.ts):

    • Defines Monad Testnet as a custom Wagmi chain

    • Configures multiple RPC endpoints for redundancy

    • Sets up WebSocket connections for real-time updates

    • Includes testnet token addresses for future DeFi integrations

  2. Wagmi Setup (src/config/wagmi.ts):

    • Creates Wagmi config with Monad chain

    • Configures injected connector (MetaMask)

    • Sets up HTTP transport for RPC communication

  3. User-Facing Network Helper (src/components/AddMonadNetwork.tsx):

    • Detects if user has Monad Testnet configured

    • One-click button to add network via MetaMask API

    • Displays network specifications and requirements

    • Links to testnet faucet for MON tokens

Resource Integration:

  • Monad Testnet: EVM-compatible Layer 1 with high throughput

  • MetaMask API: wallet_addEthereumChain RPC method

  • Wagmi Chains: Custom chain configuration support

  • Multiple RPC Providers: QuickNode, Ankr, Monad Foundation

Code Example (src/config/monad.ts):

import { Chain } from 'wagmi/chains';

export const monadTestnet: Chain = {
  id: 10143,
  name: 'Monad Testnet',
  nativeCurrency: {
    decimals: 18,
    name: 'Monad',
    symbol: 'MON',
  },
  rpcUrls: {
    default: { 
      http: ['https://testnet-rpc.monad.xyz'],
      webSocket: ['wss://testnet-rpc.monad.xyz']
    },
    public: { 
      http: [
        'https://testnet-rpc.monad.xyz',
        'https://rpc.ankr.com/monad_testnet',
        'https://rpc-testnet.monadinfra.com'
      ]
    },
  },
  blockExplorers: {
    default: { name: 'MonadExplorer', url: 'https://testnet.monadexplorer.com' },
  },
  testnet: true,
};

// Testnet token addresses for DeFi integrations
export const MONAD_TESTNET_TOKENS = {
  USDC: '0xf817257fed379853cDe0fa4F97AB987181B1E5Ea',
  USDT: '0x88b8E2161DEDC77EF4ab7585569D2415a1C1055D',
  WBTC: '0xcf5a6076cfa32686c0Df13aBaDa2b40dec133F1d',
  WrappedMonad: '0x760AfE86e5de5fa0Ee542fc7B7B713e1c5425701',
};

MetaMask Integration (src/components/AddMonadNetwork.tsx):

await window.ethereum.request({
  method: 'wallet_addEthereumChain',
  params: [{
    chainId: '0x279F', // 10143 in hex
    chainName: 'Monad Testnet',
    nativeCurrency: {
      name: 'Monad',
      symbol: 'MON',
      decimals: 18,
    },
    rpcUrls: ['https://testnet-rpc.monad.xyz'],
    blockExplorerUrls: ['https://testnet.monadexplorer.com'],
  }],
});

Why Monad:

  • High Performance: Monad offers parallel execution and MonadBFT consensus

  • EVM Compatibility: Full compatibility with existing Ethereum tooling

  • Low Latency: Optimized for fast transaction finality

  • Developer-Friendly: Extensive documentation and testnet resources


3. AI Subscription Recommendations

File: src/components/AIRecommendations.tsx

How it works:

  • User inputs interests and past subscriptions

  • Frontend calls Gemini API with structured prompt

  • AI analyzes input and returns personalized recommendations

  • Each recommendation includes name, cost, description, and reasoning

  • "Add to SubPay" button simulates adding subscription with loading states

Resource Integration:

  • Gemini 2.0 Flash API: Powers recommendation engine

  • Custom Prompt Engineering: Structured JSON response format

  • State Management: React hooks for loading states

Gemini Integration Code:

const response = await fetch(
  'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent',
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-goog-api-key': GEMINI_API_KEY,
    },
    body: JSON.stringify({
      contents: [{
        parts: [{
          text: `Based on user interests: ${interests}, suggest 3-5 subscriptions...`
        }]
      }]
    })
  }
);

4. AI Chat Assistant (SubPay Copilot)

File: src/components/AIChat.tsx

How it works:

  • Floating chat widget accessible from any page

  • Maintains conversation context across messages

  • Queries real application state (balance, subscriptions, transactions)

  • Provides actionable responses with data from the app

Resource Integration:

  • Gemini API: Conversational AI backend

  • React Context: Accesses app state for contextual responses

  • Custom System Prompts: Guides AI to provide SubPay-specific answers

Example Queries:

  • "When is my next Netflix payment?"

  • "Show my transaction history"

  • "Convert 10 MON to USD now"


5. Delegation Toolkit (Future Integration)

Files:

  • src/contracts/DelegationManager.sol (planned)

  • src/hooks/useDelegation.ts (planned)

How it will work:

  • User grants specific permissions to SubPay AI agent

  • Scope-limited delegations (only transfer to specific addresses)

  • Time-limited delegations (auto-expire after period)

  • AI can execute transactions without user signatures

Resource Integration:

  • MetaMask Delegation Toolkit: ERC-7710 implementation

  • Smart Account: Required for delegation support

  • Monad Smart Contracts: Delegation storage and verification

Planned Implementation:

// Grant delegation for automated payments
await delegationManager.delegate({
  to: SUBPAY_AGENT_ADDRESS,
  functionSelector: 'transfer(address,uint256)',
  conditions: {
    maxAmount: parseEther('100'),
    validUntil: Date.now() + 30 * 24 * 60 * 60 * 1000, // 30 days
  }
});

6. Envio Event Indexing (Future Integration)

Files:

  • envio-config.yaml (planned)

  • src/services/envioAPI.ts (planned)

How it will work:

  • Listens to on-chain events from SubPay smart contracts

  • Indexes PaymentRecorded, SubscriptionAdded events

  • Provides GraphQL API for querying indexed data

  • Powers real-time dashboard updates

Resource Integration:

  • Envio HyperIndex: Event indexing engine

  • Envio HyperSync: Fast historical data retrieval

  • Monad Integration: Configured for Monad testnet

Planned Configuration:

name: subpay-indexernetworks:- name: monad-testnet
    chain_id: 10143
    rpc_url: https://testnet-rpc.monad.xyzcontracts:- name: PaymentLedger
    address: "0x..."
    events:
      - PaymentRecorded
      - SubscriptionAdded

7. Multi-Currency Support

File: src/components/CurrencySelector.tsx

How it works:

  • Toggle between USD and INR display

  • Automatic conversion rates (1 USD = 83.5 INR)

  • All prices update dynamically when currency changes

  • Currency preference saved in component state

Resource Integration:

  • Exchange Rate API: (Future: integrate live rates)

  • React State Management: Currency context provider


8. Financial Insights Dashboard

File: src/components/FinancialInsights.tsx

How it works:

  • Calculates total monthly spending from subscriptions

  • Identifies most expensive subscription

  • AI-powered spending forecast for next 30 days

  • Suggests optimization opportunities

Resource Integration:

  • Gemini AI: Predictive analytics for spending trends

  • Mock Data: Transaction history analysis

  • Recharts: Data visualization (planned)


📂 File Structure & Resource Mapping

src/
├── config/
│   ├── monad.ts              # Monad Testnet configuration (Chain ID, RPC, Explorer)
│   └── wagmi.ts              # Wagmi setup for Web3 connections
├── components/
│   ├── WalletConnect.tsx     # MetaMask Smart Account connection
│   ├── AddMonadNetwork.tsx   # One-click network setup (MetaMask API)
│   ├── BalanceCard.tsx       # Real-time MON balance (Wagmi useBalance)
│   ├── AIRecommendations.tsx # Gemini AI subscription suggestions
│   ├── AIChat.tsx            # Gemini AI conversational assistant
│   ├── CurrencySelector.tsx  # USD/INR toggle
│   ├── ActiveSubscriptions.tsx   # Subscription management UI
│   ├── TransactionHistory.tsx    # Payment history display
│   ├── FinancialInsights.tsx     # AI spending analytics
│   ├── UpcomingPayments.tsx      # Due date tracking
│   └── Settings.tsx              # User preferences
├── services/
│   └── geminiAI.ts           # Gemini API integration (all AI features)
├── types/
│   └── subscription.ts       # TypeScript interfaces
├── data/
│   └── mockData.ts           # Demo data for testing
└── pages/
    └── Index.tsx             # Main dashboard (assembles all components)

Resource-to-File Mapping

Resource

Primary Files

Purpose

MetaMask Smart Accounts

WalletConnect.tsx, wagmi.ts

Wallet connection & Smart Account detection

Monad Testnet

monad.ts, AddMonadNetwork.tsx

Chain configuration & network setup

Gemini AI

geminiAI.ts, AIRecommendations.tsx, AIChat.tsx

All AI-powered features

Delegation Toolkit

(Future) useDelegation.ts

Automated payment permissions

Envio

(Future) envioAPI.ts

Event indexing & analytics


🚀 Installation

Prerequisites

  • Node.js 18+ and npm

  • MetaMask browser extension

  • MON testnet tokens (from Monad Faucet)

Steps

# Clone the repository
git clone <YOUR_GIT_URL>
cd subpay-automator

# Install dependencies
npm install

# Start development server
npm run dev

The app will be available at http://localhost:5173


🔐 Environment Variables

Important: This project uses a public Gemini API key for demo purposes. In production, you should:

  1. Create a .env.local file (ignored by git):

VITE_GEMINI_API_KEY=your_api_key_here
  1. Remove the hardcoded key from src/services/geminiAI.ts

  2. Add .env.local to .gitignore:

.env.local
.env*.local

Current Implementation: The Gemini API key is currently in src/services/geminiAI.ts with a fallback for development:

const GEMINI_API_KEY = import.meta.env.VITE_GEMINI_API_KEY || 'AIzaSyDWCgAHBZJFyyLJLMDkbxafv9ssJ4hfu2E';

📦 Deployment

Via Lovable (Recommended)

  1. Click Publish button in Lovable editor

  2. Your app will be deployed to yourproject.lovable.app

  3. Custom domain available on paid plans

Manual Deployment

# Build for production
npm run build

# Preview production build
npm run preview

# Deploy to your preferred hosting (Vercel, Netlify, etc.)

Environment Variables for Production

Set these in your hosting platform:

  • VITE_GEMINI_API_KEY - Your Gemini API key

  • (Future) VITE_ENVIO_API_URL - Envio indexer endpoint

  • (Future) VITE_SUBPAY_CONTRACT_ADDRESS - Deployed contract address


🔗 Resources & Documentation


🏆 Hackathon Tracks

This project competes in:

  • Best On-chain Automation - Automated subscription payments via delegations

  • Envio Bonus Track - Event indexing for transaction history


👥 Team

Built with ❤️ for the Monad Hackathon


⚡ Powered by Monad | 🤖 AI by Gemini | 🔗 Indexed by Envio | 🦊 Built on MetaMask Smart Accounts

テックスタック

React
Next
Web3
typescript
javascript
チームリーダー
TTech Revenger
オープンソース
業界
AISocialFiDeFi