This document outlines the complete implementation of MeToken creation using Alchemy SDK and Supabase integration, following the requirements specified in your query.
The implementation follows a three-tier architecture:
- Frontend Layer: React components using Account Kit for smart account interactions
- Backend Layer: Supabase Edge Functions and API routes for orchestration
- Blockchain Layer: Alchemy SDK for reliable blockchain interactions
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Frontend │ │ Supabase │ │ Alchemy SDK │
│ (React) │◄──►│ (Backend) │◄──►│ (Blockchain) │
│ │ │ │ │ │
│ • Account Kit │ │ • Edge Functions │ │ • Diamond │
│ • Smart Wallets │ │ • API Routes │ │ Contract │
│ • UI Components │ │ • Database │ │ • DAI Token │
└─────────────────┘ └──────────────────┘ └─────────────────┘
lib/sdk/alchemy/
├── metoken-service.ts # Core Alchemy SDK integration
└── (existing files...)
supabase/functions/
└── create-metoken/
└── index.ts # Edge Function for orchestration
components/UserProfile/
├── AlchemyMeTokenCreator.tsx # Enhanced frontend component
└── (existing files...)
app/api/metokens/
├── alchemy/
│ └── route.ts # API route for Alchemy integration
└── (existing files...)
lib/sdk/supabase/
└── enhanced-schema.sql # Enhanced database schema
Key Features:
- Reliable Blockchain Access: Uses Alchemy's Supernode for consistent data
- Gas Optimization: Leverages Alchemy's gas estimation and optimization
- Transaction Management: Handles approval and creation in sequence
- Error Handling: Comprehensive error handling with detailed messages
Core Functions:
// Create a new MeToken
await alchemyMeTokenService.createMeToken({
name: "My Creative Token",
symbol: "MCT",
hubId: 1,
assetsDeposited: "100.00",
creatorAddress: "0x..."
});
// Get MeToken information
const info = await alchemyMeTokenService.getMeTokenInfo(meTokenAddress);
// Check subscription status
const isSubscribed = await alchemyMeTokenService.isMeTokenSubscribed(meTokenAddress);Purpose: Orchestrates the MeToken creation process and manages data storage.
Workflow:
- Validation: Checks user authentication and input parameters
- Duplicate Prevention: Ensures one MeToken per creator address
- Transaction Tracking: Monitors blockchain transactions
- Data Storage: Stores MeToken data in Supabase database
- Analytics: Records creation transactions for analytics
Features:
- Smart Account Integration: Uses Account Kit for seamless UX
- Real-time Balance Checking: Monitors DAI balance and allowance
- Transaction Status: Shows detailed progress during creation
- Error Handling: User-friendly error messages and recovery options
- Gas Optimization: Automatic gas estimation and optimization
User Experience:
- User enters MeToken details (name, symbol, hub ID, DAI amount)
- Component checks DAI balance and allowance
- If needed, approves DAI for Diamond contract
- Deploys MeToken via METOKEN_FACTORY.create contract call
- Tracks create transaction and calls DIAMOND.mint to mint tokens (with Supabase storage of both create and mint tx data)
- Shows success confirmation with transaction links
New Tables:
metoken_analytics: Trading and performance metricsalchemy_integrations: Alchemy SDK integration trackinggas_optimizations: Gas usage optimization data
Enhanced Features:
- Full-text Search: Search MeTokens by name, symbol, description
- Analytics Views: Pre-computed views for common queries
- Row Level Security: Secure access control
- Automatic Timestamps: Updated_at triggers for all tables
Add these environment variables to your .env.local:
# Alchemy Configuration
NEXT_PUBLIC_ALCHEMY_API_KEY=your_alchemy_api_key
ALCHEMY_SWAP_PRIVATE_KEY=your_private_key_for_server_operations
# Supabase Configuration
NEXT_PUBLIC_SUPABASE_URL=your_supabase_url
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_supabase_anon_key
SUPABASE_SERVICE_ROLE_KEY=your_supabase_service_keyRun the enhanced schema in your Supabase SQL editor:
-- Copy and paste the contents of lib/sdk/supabase/enhanced-schema.sql
-- This will create all necessary tables, indexes, and policies# Install Supabase CLI if not already installed
npm install -g supabase
# Deploy the Edge Function
supabase functions deploy create-metokenUse the new Alchemy MeToken Creator component:
import { AlchemyMeTokenCreator } from '@/components/UserProfile/AlchemyMeTokenCreator';
function MyPage() {
const handleMeTokenCreated = (meTokenAddress: string, transactionHash: string) => {
console.log('MeToken created:', { meTokenAddress, transactionHash });
// Handle success (redirect, show notification, etc.)
};
return (
<AlchemyMeTokenCreator onMeTokenCreated={handleMeTokenCreated} />
);
}- User connects smart wallet using Account Kit
- Component validates MeToken parameters
- Checks DAI balance and allowance
- DAI Approval: If needed, approves DAI for Diamond contract
- MeToken Deployment: Calls METOKEN_FACTORY.create to deploy the MeToken contract
- Token Minting: Calls DIAMOND.mint to mint initial tokens
- Transaction Confirmation: Waits for blockchain confirmation
- Transaction Tracking: Records transaction in Supabase
- MeToken Storage: Stores MeToken data with blockchain info
- Analytics: Updates analytics and metrics
- Success Notification: Shows transaction hash and MeToken address
- External Links: Provides links to BaseScan for verification
- Form Reset: Clears form for next creation
- Free Plan: 300M Compute Units/month (sufficient for development)
- Growth Plan: $49/month (for production scaling)
- Scale Plan: $199/month (for high-volume applications)
- Free Plan: 500MB database, 500K Edge Function invocations (sufficient for MVP)
- Pro Plan: $25/month + usage (for production)
- Mint Fee: Up to 5% (controlled by governance)
- Gas Costs: Optimized using Alchemy's gas estimation
- DAI Collateral: Required for MeToken creation
- Diamond Standard: Uses battle-tested Diamond proxy pattern
- Access Control: Proper ownership and permission management
- Fee Limits: Maximum 5% fee rate enforced by governance
- Row Level Security: Supabase RLS policies protect user data
- Authentication: JWT-based authentication for API access
- Input Validation: Comprehensive validation on all inputs
- Error Handling: Secure error messages without sensitive data
- Account Kit: Secure smart account management
- No Private Keys: Client-side operations use smart accounts
- Environment Variables: Secure storage of API keys
- Trading Metrics: Volume, trades, unique traders
- Liquidity Tracking: Pooled and locked balances
- User Activity: Holder counts and growth
- Gas Optimization: Gas usage and savings tracking
- Transaction Status: Real-time transaction monitoring
- Gas Optimization: Automatic gas price optimization
- Error Tracking: Comprehensive error logging and alerts
- Environment variables configured
- Database schema deployed
- Supabase Edge Functions deployed
- Alchemy API keys configured
- Smart contract addresses verified
- Test MeToken creation flow
- Verify database storage
- Check transaction tracking
- Monitor gas optimization
- Test error handling
1. "Insufficient DAI balance"
- Solution: Use the DAI funding options component
- Check: DAI balance and allowance
2. "Transaction failed"
- Solution: Check gas prices and network congestion
- Retry: With higher gas limit if needed
3. "MeToken already exists"
- Solution: Each address can only create one MeToken
- Check: Existing MeToken in database
4. "Alchemy API errors"
- Solution: Verify API key and rate limits
- Check: Alchemy dashboard for usage
Enable debug logging by setting:
NEXT_PUBLIC_DEBUG_METOKEN=trueThis will provide detailed console logs for troubleshooting.
- Batch Operations: Create multiple MeTokens in one transaction
- Advanced Analytics: Real-time price feeds and market data
- Social Features: MeToken discovery and social trading
- Mobile Support: React Native integration
- Multi-chain: Support for additional networks
- Caching: Redis integration for faster queries
- CDN: Static asset optimization
- Database: Query optimization and indexing
- Blockchain: Batch transaction processing
- Alchemy SDK Documentation
- Account Kit Documentation
- Supabase Documentation
- MeTokens Protocol Documentation
- Base Network Documentation
For technical support or questions:
- Check the troubleshooting section above
- Review the console logs for error details
- Verify environment configuration
- Test with smaller amounts first
- Contact support with specific error messages
This implementation provides a robust, scalable, and user-friendly solution for MeToken creation using Alchemy SDK and Supabase, following all the requirements and best practices outlined in your query.