TechSetupGuides
AdvancedWeb3AINext.jsIPFSThe GraphRainbowKitLangChainBlockchainDecentralized StorageSmart Contracts

Web3 + AI Hybrid Stack Setup Guide (IPFS + The Graph + LangChain)

Complete setup guide for building a full-stack Web3 application with AI capabilities using Next.js, IPFS, The Graph, RainbowKit, LangChain, and Vercel Edge Functions.

  1. Step 1

    Project Initialization and Core Dependencies

    Start by creating a new Next.js project with TypeScript and installing the core Web3 and AI dependencies.

    This setup uses Next.js 14+ with the App Router for optimal performance and TypeScript for type safety. We'll install the essential Web3 libraries (ethers, wagmi, viem) and AI orchestration tools (LangChain).

    # Create Next.js project with TypeScript
    npx create-next-app@latest web3-ai-app --typescript --tailwind --app --no-src-dir
    cd web3-ai-app
    
    # Install Web3 core dependencies
    npm install wagmi viem @tanstack/react-query
    npm install @rainbow-me/rainbowkit
    
    # Install IPFS client
    npm install ipfs-http-client
    
    # Install The Graph client
    npm install @apollo/client graphql
    
    # Install LangChain for AI
    npm install langchain @langchain/openai
    
    # Install Vercel AI SDK
    npm install ai
  2. Step 2

    RainbowKit Multi-Chain Wallet Configuration

    Set up RainbowKit to support multiple blockchain networks with a beautiful, customizable wallet connection interface.

    RainbowKit provides the best-in-class wallet connection UX, supporting major wallets like MetaMask, WalletConnect, Coinbase Wallet, and more. This configuration enables multi-chain support for Ethereum mainnet, Polygon, Optimism, and Arbitrum.

    // lib/wagmi.ts
    import { getDefaultConfig } from '@rainbow-me/rainbowkit';
    import { mainnet, polygon, optimism, arbitrum, base } from 'wagmi/chains';
    
    export const config = getDefaultConfig({
      appName: 'Web3 AI Hybrid App',
      projectId: process.env.NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID!,
      chains: [mainnet, polygon, optimism, arbitrum, base],
      ssr: true, // Enable SSR for Next.js App Router
    });
    
    // app/providers.tsx
    'use client';
    import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
    import { RainbowKitProvider, darkTheme } from '@rainbow-me/rainbowkit';
    import { WagmiProvider } from 'wagmi';
    import { config } from '@/lib/wagmi';
    import '@rainbow-me/rainbowkit/styles.css';
    
    const queryClient = new QueryClient();
    
    export function Providers({ children }: { children: React.ReactNode }) {
      return (
        <WagmiProvider config={config}>
          <QueryClientProvider client={queryClient}>
            <RainbowKitProvider theme={darkTheme()}>
              {children}
            </RainbowKitProvider>
          </QueryClientProvider>
        </WagmiProvider>
      );
    }
    ⚠ Heads up: Never commit your NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID to version control. Get a free project ID from cloud.walletconnect.com
  3. Step 3

    IPFS Setup with Pinning Service Integration

    Configure IPFS for decentralized storage with reliable pinning using services like Pinata, Web3.Storage, or Infura IPFS.

    IPFS Pinning Best Practices:

    • Use dedicated pinning services for production (files pinned only locally are lost when your node goes offline)
    • Implement content addressing with CID verification
    • Cache frequently accessed content with a CDN gateway
    • Consider IPFS Cluster for redundancy across multiple nodes
    // lib/ipfs.ts
    import { create } from 'ipfs-http-client';
    
    // Configuration for Infura IPFS (alternative: Pinata, Web3.Storage)
    const projectId = process.env.IPFS_PROJECT_ID;
    const projectSecret = process.env.IPFS_PROJECT_SECRET;
    const auth = 'Basic ' + Buffer.from(projectId + ':' + projectSecret).toString('base64');
    
    export const ipfsClient = create({
      host: 'ipfs.infura.io',
      port: 5001,
      protocol: 'https',
      headers: {
        authorization: auth,
      },
    });
    
    // Upload file to IPFS with pinning
    export async function uploadToIPFS(file: File): Promise<string> {
      try {
        const buffer = await file.arrayBuffer();
        const result = await ipfsClient.add(Buffer.from(buffer), {
          pin: true, // Ensure content is pinned
          progress: (bytes) => console.log(`Uploaded ${bytes} bytes`),
        });
        return result.cid.toString();
      } catch (error) {
        console.error('IPFS upload error:', error);
        throw new Error('Failed to upload to IPFS');
      }
    }
    
    // Retrieve content from IPFS
    export async function retrieveFromIPFS(cid: string): Promise<Uint8Array> {
      const chunks = [];
      for await (const chunk of ipfsClient.cat(cid)) {
        chunks.push(chunk);
      }
      return Buffer.concat(chunks);
    }
    
    // Generate IPFS gateway URL (use public gateway for read)
    export function getIPFSUrl(cid: string): string {
      return `https://ipfs.io/ipfs/${cid}`;
    }
    ⚠ Heads up: IPFS pinning services have storage limits and costs. Monitor your pinned content and implement cleanup strategies for unused data.
  4. Step 4

    The Graph Subgraph Development and Deployment

    Create and deploy a subgraph to index blockchain data efficiently using The Graph protocol.

    The Graph enables:

    • Fast, indexed queries of blockchain data without running your own node
    • Real-time updates as new blocks are mined
    • GraphQL API for flexible data retrieval
    • Support for multiple chains (Ethereum, Polygon, Arbitrum, etc.)

    Subgraph Development Workflow:

    1. Define your schema in schema.graphql
    2. Map contract events to entities
    3. Deploy to The Graph's hosted service or decentralized network
    # Install The Graph CLI
    npm install -g @graphprotocol/graph-cli
    
    # Initialize a new subgraph
    graph init --product subgraph-studio my-web3-subgraph
    
    # Navigate to subgraph directory
    cd my-web3-subgraph
  5. Step 5

    Subgraph Schema and Mapping Configuration

    Define your subgraph schema to specify which blockchain events and entities to index.

    This example tracks an NFT contract with metadata stored on IPFS. The schema defines entities that The Graph will index and make queryable via GraphQL.

    # schema.graphql
    type NFT @entity {
      id: ID!
      tokenId: BigInt!
      owner: Bytes!
      metadataURI: String!
      metadataCID: String # IPFS CID extracted from URI
      mintedAt: BigInt!
      transfers: [Transfer!]! @derivedFrom(field: "nft")
    }
    
    type Transfer @entity {
      id: ID!
      nft: NFT!
      from: Bytes!
      to: Bytes!
      transactionHash: Bytes!
      timestamp: BigInt!
    }
    
    type Metadata @entity {
      id: ID! # IPFS CID
      name: String
      description: String
      image: String
      attributes: [Attribute!]!
    }
    
    type Attribute @entity {
      id: ID!
      traitType: String!
      value: String!
    }
  6. Step 6

    Subgraph Mapping Implementation

    Implement event handlers to process blockchain events and populate your subgraph entities.

    Mappings transform raw blockchain events into structured, queryable data. This example handles NFT Transfer events and extracts IPFS CIDs from token URIs.

    // src/mapping.ts
    import { Transfer as TransferEvent } from '../generated/MyNFT/MyNFT';
    import { NFT, Transfer } from '../generated/schema';
    import { MyNFT } from '../generated/MyNFT/MyNFT';
    
    export function handleTransfer(event: TransferEvent): void {
      let tokenId = event.params.tokenId.toString();
      let nft = NFT.load(tokenId);
      
      // Create NFT entity if this is a mint (from address 0x0)
      if (nft == null) {
        nft = new NFT(tokenId);
        nft.tokenId = event.params.tokenId;
        
        // Fetch metadata URI from contract
        let contract = MyNFT.bind(event.address);
        let metadataURI = contract.try_tokenURI(event.params.tokenId);
        if (!metadataURI.reverted) {
          nft.metadataURI = metadataURI.value;
          
          // Extract IPFS CID from URI (e.g., ipfs://QmXxx or https://ipfs.io/ipfs/QmXxx)
          let uri = metadataURI.value;
          if (uri.startsWith('ipfs://')) {
            nft.metadataCID = uri.slice(7);
          } else if (uri.includes('/ipfs/')) {
            let parts = uri.split('/ipfs/');
            nft.metadataCID = parts[1];
          }
        }
        
        nft.mintedAt = event.block.timestamp;
      }
      
      // Update owner
      nft.owner = event.params.to;
      nft.save();
      
      // Create transfer record
      let transfer = new Transfer(
        event.transaction.hash.toHex() + '-' + event.logIndex.toString()
      );
      transfer.nft = tokenId;
      transfer.from = event.params.from;
      transfer.to = event.params.to;
      transfer.transactionHash = event.transaction.hash;
      transfer.timestamp = event.block.timestamp;
      transfer.save();
    }
  7. Step 7

    Deploy and Query The Graph Subgraph

    Deploy your subgraph to The Graph's Studio and set up Apollo Client to query the indexed data.

    Deployment Options:

    • Subgraph Studio (recommended): Decentralized network with high reliability
    • Hosted Service: Being deprecated, migrate to Studio
    • Self-hosted: Run your own Graph Node (advanced)
    # Deploy to Subgraph Studio
    graph codegen  # Generate types from schema
    graph build    # Build the subgraph
    graph deploy --studio my-web3-subgraph
    
    # Your subgraph will be available at:
    # https://api.studio.thegraph.com/query/<deploy-key>/my-web3-subgraph/version/latest
  8. Step 8

    Apollo Client Setup for The Graph Queries

    Configure Apollo Client to efficiently query your subgraph with caching and real-time updates.

    Apollo Client provides a powerful GraphQL client with built-in caching, optimistic UI updates, and React hooks for easy integration.

    // lib/apollo-client.ts
    import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
    
    const SUBGRAPH_URL = process.env.NEXT_PUBLIC_SUBGRAPH_URL!;
    
    export const apolloClient = new ApolloClient({
      uri: SUBGRAPH_URL,
      cache: new InMemoryCache(),
    });
    
    // Example query: Get NFTs with IPFS metadata
    export const GET_NFTS = gql`
      query GetNFTs($first: Int!, $skip: Int!, $owner: Bytes) {
        nfts(
          first: $first
          skip: $skip
          where: { owner: $owner }
          orderBy: mintedAt
          orderDirection: desc
        ) {
          id
          tokenId
          owner
          metadataURI
          metadataCID
          mintedAt
          transfers {
            from
            to
            timestamp
          }
        }
      }
    `;
    
    // Example usage in a component
    export async function fetchUserNFTs(address: string) {
      const { data } = await apolloClient.query({
        query: GET_NFTS,
        variables: {
          first: 50,
          skip: 0,
          owner: address.toLowerCase(),
        },
      });
      return data.nfts;
    }
  9. Step 9

    LangChain Integration for AI-Powered Smart Contract Analysis

    Set up LangChain to provide AI-powered insights and analysis of smart contract code and blockchain data.

    LangChain enables:

    • Natural language queries over blockchain data
    • Smart contract security analysis
    • Automated contract documentation
    • Risk assessment of DeFi protocols

    Key Components:

    • LLM: OpenAI GPT-4 or Claude for reasoning
    • Vector Store: Store contract embeddings for semantic search
    • Tools: Custom tools for blockchain queries
    • Agents: Autonomous AI that can interact with multiple data sources
    // lib/langchain.ts
    import { ChatOpenAI } from '@langchain/openai';
    import { PromptTemplate } from 'langchain/prompts';
    import { LLMChain } from 'langchain/chains';
    import { Tool } from 'langchain/tools';
    import { initializeAgentExecutorWithOptions } from 'langchain/agents';
    import { apolloClient, GET_NFTS } from './apollo-client';
    
    // Initialize LLM
    const model = new ChatOpenAI({
      modelName: 'gpt-4-turbo-preview',
      temperature: 0.2, // Lower temperature for more deterministic analysis
      openAIApiKey: process.env.OPENAI_API_KEY,
    });
    
    // Custom tool: Query blockchain data via The Graph
    class BlockchainQueryTool extends Tool {
      name = 'blockchain_query';
      description = 'Query blockchain data indexed by The Graph. Use this to get NFT ownership, transfer history, and metadata.';
    
      async _call(query: string): Promise<string> {
        try {
          // Parse natural language query into GraphQL (simplified example)
          const { data } = await apolloClient.query({
            query: GET_NFTS,
            variables: { first: 10, skip: 0 },
          });
          return JSON.stringify(data.nfts, null, 2);
        } catch (error) {
          return `Error querying blockchain: ${error}`;
        }
      }
    }
    
    // Custom tool: Analyze smart contract code
    class ContractAnalysisTool extends Tool {
      name = 'analyze_contract';
      description = 'Analyze Solidity smart contract code for security vulnerabilities, gas optimization, and best practices.';
    
      async _call(contractCode: string): Promise<string> {
        const prompt = PromptTemplate.fromTemplate(`
    Analyze the following Solidity smart contract for:
    1. Security vulnerabilities (reentrancy, integer overflow, access control)
    2. Gas optimization opportunities
    3. Best practice violations
    4. Compliance with common standards (ERC-20, ERC-721, etc.)
    
    Contract Code:
    {contractCode}
    
    Provide a detailed analysis with severity ratings and recommendations.
        `);
    
        const chain = new LLMChain({ llm: model, prompt });
        const result = await chain.call({ contractCode });
        return result.text;
      }
    }
    
    // Initialize agent with tools
    export async function createWeb3AIAgent() {
      const tools = [
        new BlockchainQueryTool(),
        new ContractAnalysisTool(),
      ];
    
      const agent = await initializeAgentExecutorWithOptions(tools, model, {
        agentType: 'openai-functions',
        verbose: true,
      });
    
      return agent;
    }
    
    // Example: Analyze a contract from user input
    export async function analyzeSmartContract(contractCode: string): Promise<string> {
      const agent = await createWeb3AIAgent();
      const result = await agent.call({
        input: `Analyze this smart contract and identify any security issues: ${contractCode}`,
      });
      return result.output;
    }
    ⚠ Heads up: AI analysis should complement, not replace, professional security audits. Always have critical contracts audited by security firms before mainnet deployment.
  10. Step 10

    Vercel Edge Functions for AI API Routes

    Deploy AI-powered endpoints using Vercel Edge Functions for low-latency, globally distributed responses.

    Edge Functions Benefits:

    • Execute at the edge, close to users (reduced latency)
    • Serverless auto-scaling
    • Streaming responses for LLM outputs
    • Built-in Web3 libraries support

    Edge Runtime has some limitations (no Node.js APIs), but the Vercel AI SDK is optimized for edge deployment.

    // app/api/analyze-contract/route.ts
    import { OpenAIStream, StreamingTextResponse } from 'ai';
    import { Configuration, OpenAIApi } from 'openai-edge';
    
    // Edge Runtime configuration
    export const runtime = 'edge';
    
    const config = new Configuration({
      apiKey: process.env.OPENAI_API_KEY,
    });
    const openai = new OpenAIApi(config);
    
    export async function POST(req: Request) {
      const { contractCode } = await req.json();
    
      if (!contractCode) {
        return new Response('Missing contract code', { status: 400 });
      }
    
      const prompt = `Analyze this Solidity smart contract for security vulnerabilities, gas optimizations, and best practices:\n\n${contractCode}`;
    
      const response = await openai.createChatCompletion({
        model: 'gpt-4-turbo-preview',
        stream: true,
        messages: [
          {
            role: 'system',
            content: 'You are a smart contract security expert. Analyze contracts for vulnerabilities, provide severity ratings, and suggest fixes.',
          },
          {
            role: 'user',
            content: prompt,
          },
        ],
        temperature: 0.2,
        max_tokens: 2000,
      });
    
      // Stream the response back to the client
      const stream = OpenAIStream(response);
      return new StreamingTextResponse(stream);
    }
  11. Step 11

    Smart Contract Interaction with Safety Guards

    Implement safe smart contract interaction patterns with transaction simulation, gas estimation, and error handling.

    Safety Best Practices:

    • Always simulate transactions before execution
    • Estimate gas and add buffer (10-20%)
    • Validate contract addresses and function signatures
    • Implement slippage protection for DEX interactions
    • Use multicall for batched reads
    • Set appropriate transaction deadlines
    // lib/contract-interaction.ts
    import { useContractWrite, usePrepareContractWrite, useWaitForTransaction } from 'wagmi';
    import { parseEther, formatEther } from 'viem';
    
    // Example: Safe NFT minting with transaction simulation
    export function useSafeMint(contractAddress: `0x${string}`, abi: any) {
      // Step 1: Prepare and simulate transaction
      const { config, error: prepareError } = usePrepareContractWrite({
        address: contractAddress,
        abi: abi,
        functionName: 'mint',
        args: [1], // quantity
        value: parseEther('0.1'), // mint price
        // Wagmi automatically simulates the transaction
      });
    
      // Step 2: Execute transaction
      const { data, write, isLoading: isWriteLoading } = useContractWrite(config);
    
      // Step 3: Wait for confirmation
      const { isLoading: isTxLoading, isSuccess } = useWaitForTransaction({
        hash: data?.hash,
        confirmations: 2, // Wait for 2 block confirmations
      });
    
      return {
        mint: write,
        isLoading: isWriteLoading || isTxLoading,
        isSuccess,
        error: prepareError,
        txHash: data?.hash,
      };
    }
    
    // Example: Gas estimation utility
    export async function estimateGasWithBuffer(
      client: any,
      transaction: any
    ): Promise<bigint> {
      try {
        const estimatedGas = await client.estimateGas(transaction);
        // Add 20% buffer to estimated gas
        return (estimatedGas * 120n) / 100n;
      } catch (error) {
        console.error('Gas estimation failed:', error);
        throw new Error('Transaction would fail. Please check parameters.');
      }
    }
    
    // Example: Safe multicall for batch reads
    import { multicall } from '@wagmi/core';
    
    export async function batchReadNFTMetadata(
      contractAddress: `0x${string}`,
      tokenIds: bigint[]
    ) {
      const contract = {
        address: contractAddress,
        abi: [/* ERC721 ABI */],
      };
    
      const results = await multicall({
        contracts: tokenIds.map(tokenId => ({
          ...contract,
          functionName: 'tokenURI',
          args: [tokenId],
        })),
      });
    
      return results.map((result, i) => ({
        tokenId: tokenIds[i],
        uri: result.status === 'success' ? result.result : null,
        error: result.status === 'failure' ? result.error : null,
      }));
    }
  12. Step 12

    Web3 Security Best Practices Implementation

    Implement comprehensive security measures to protect users and prevent common Web3 vulnerabilities.

    Critical Security Measures:

    1. Frontend Security:

    • Never store private keys or mnemonics
    • Validate all user inputs and contract addresses
    • Implement Content Security Policy (CSP)
    • Use HTTPS everywhere

    2. Transaction Security:

    • Display human-readable transaction summaries before signing
    • Verify contract addresses against known registries
    • Implement transaction simulation
    • Add spending limits and approval management

    3. Data Integrity:

    • Verify IPFS content using CIDs
    • Cross-reference blockchain data with multiple sources
    • Implement checksum validation for addresses

    4. User Protection:

    • Educate users about phishing
    • Implement transaction warnings for large amounts
    • Add confirmation steps for irreversible actions
    // lib/security.ts
    import { isAddress, getAddress } from 'viem';
    
    // Validate and normalize Ethereum address
    export function validateAddress(address: string): `0x${string}` | null {
      if (!isAddress(address)) {
        return null;
      }
      return getAddress(address); // Returns checksummed address
    }
    
    // Verify IPFS content integrity
    export async function verifyIPFSContent(
      cid: string,
      expectedHash?: string
    ): Promise<boolean> {
      try {
        const content = await fetch(`https://ipfs.io/ipfs/${cid}`);
        const buffer = await content.arrayBuffer();
        
        if (expectedHash) {
          const hash = await crypto.subtle.digest('SHA-256', buffer);
          const hashArray = Array.from(new Uint8Array(hash));
          const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
          return hashHex === expectedHash;
        }
        
        return true; // CID itself provides content addressing
      } catch (error) {
        console.error('IPFS content verification failed:', error);
        return false;
      }
    }
    
    // Transaction summary for user confirmation
    export interface TransactionSummary {
      type: string;
      to: string;
      value: string;
      estimatedGas: string;
      maxCost: string;
      warning?: string;
    }
    
    export function generateTransactionSummary(
      tx: any,
      gasEstimate: bigint,
      gasPrice: bigint
    ): TransactionSummary {
      const maxCost = (gasEstimate * gasPrice) + (tx.value || 0n);
      
      return {
        type: tx.functionName || 'Transfer',
        to: tx.to,
        value: formatEther(tx.value || 0n),
        estimatedGas: gasEstimate.toString(),
        maxCost: formatEther(maxCost),
        warning: maxCost > parseEther('1') ? 'High value transaction!' : undefined,
      };
    }
    
    // Content Security Policy headers for Next.js
    export const securityHeaders = [
      {
        key: 'Content-Security-Policy',
        value: [
          "default-src 'self'",
          "script-src 'self' 'unsafe-eval' 'unsafe-inline'",
          "style-src 'self' 'unsafe-inline'",
          "img-src 'self' data: https: ipfs.io dweb.link",
          "connect-src 'self' https://*.infura.io https://*.thegraph.com wss://*.walletconnect.com",
          "frame-src 'self' https://verify.walletconnect.com",
        ].join('; '),
      },
      {
        key: 'X-Frame-Options',
        value: 'DENY',
      },
      {
        key: 'X-Content-Type-Options',
        value: 'nosniff',
      },
      {
        key: 'Referrer-Policy',
        value: 'strict-origin-when-cross-origin',
      },
    ];
  13. Step 13

    Environment Configuration and Deployment

    Set up environment variables and deploy your Web3 + AI hybrid application to Vercel.

    Create a .env.local file with all required API keys and configuration. Never commit secrets to version control.

    # .env.local
    
    # RainbowKit / WalletConnect
    NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID=your_project_id_here
    
    # IPFS (Infura, Pinata, or Web3.Storage)
    IPFS_PROJECT_ID=your_infura_project_id
    IPFS_PROJECT_SECRET=your_infura_secret
    # OR
    PINATA_API_KEY=your_pinata_key
    PINATA_SECRET_KEY=your_pinata_secret
    
    # The Graph
    NEXT_PUBLIC_SUBGRAPH_URL=https://api.studio.thegraph.com/query/your-subgraph/your-version/latest
    
    # OpenAI for LangChain
    OPENAI_API_KEY=sk-your-openai-api-key
    
    # Optional: Alchemy or Infura RPC (if not using RainbowKit defaults)
    NEXT_PUBLIC_ALCHEMY_API_KEY=your_alchemy_key
    NEXT_PUBLIC_INFURA_API_KEY=your_infura_key
    
    # Security
    NEXTAUTH_SECRET=your_nextauth_secret_for_backend_auth
    
    # Deployment
    VERCEL_URL=your-app.vercel.app
    ⚠ Heads up: Rotate API keys regularly and monitor usage limits. Use separate keys for development and production.
  14. Step 14

    Deploy to Vercel with Edge Functions

    Deploy your application to Vercel with optimal configuration for Web3 and AI features.

    Deployment Steps:

    1. Push your code to GitHub
    2. Import project in Vercel dashboard
    3. Add environment variables
    4. Configure build settings
    5. Deploy

    Vercel automatically enables:

    • Edge Functions for API routes marked with export const runtime = 'edge'
    • Image optimization
    • Static site generation for public pages
    • Automatic HTTPS
    # Install Vercel CLI (optional, for CLI deployment)
    npm install -g vercel
    
    # Login to Vercel
    vercel login
    
    # Deploy to preview
    vercel
    
    # Deploy to production
    vercel --prod
    
    # Add environment variables via CLI
    vercel env add OPENAI_API_KEY production
    vercel env add NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID production
    vercel env add IPFS_PROJECT_ID production
    vercel env add IPFS_PROJECT_SECRET production
  15. Step 15

    Testing and Monitoring Your Web3 AI Application

    Implement comprehensive testing and monitoring to ensure reliability and catch issues early.

    Testing Strategy:

    1. Smart Contract Testing:

    • Use Hardhat or Foundry for contract tests
    • Test on testnets (Sepolia, Mumbai) before mainnet
    • Perform gas profiling

    2. Frontend Testing:

    • Unit tests for utilities (React Testing Library)
    • Integration tests for contract interactions
    • E2E tests with Playwright

    3. AI Model Testing:

    • Validate LangChain chain outputs
    • Test prompt engineering variations
    • Monitor hallucination rates

    Monitoring:

    • Track transaction failures and reverts
    • Monitor API usage and costs (OpenAI, IPFS, The Graph)
    • Set up alerts for suspicious activity
    • Track user wallet connections and errors
    // __tests__/contract-interaction.test.ts
    import { renderHook, waitFor } from '@testing-library/react';
    import { useContractRead } from 'wagmi';
    import { mockContract } from './test-utils';
    
    describe('Contract Interactions', () => {
      it('should read NFT metadata correctly', async () => {
        const { result } = renderHook(() =>
          useContractRead({
            address: mockContract.address,
            abi: mockContract.abi,
            functionName: 'tokenURI',
            args: [1n],
          })
        );
    
        await waitFor(() => expect(result.current.isSuccess).toBe(true));
        expect(result.current.data).toContain('ipfs://');
      });
    });
    
    // Monitoring with Vercel Analytics
    import { Analytics } from '@vercel/analytics/react';
    import { SpeedInsights } from '@vercel/speed-insights/next';
    
    export default function RootLayout({ children }: { children: React.ReactNode }) {
      return (
        <html lang="en">
          <body>
            {children}
            <Analytics /> {/* Track page views and custom events */}
            <SpeedInsights /> {/* Monitor Core Web Vitals */}
          </body>
        </html>
      );
    }
    
    // Custom error tracking
    export function trackError(error: Error, context: Record<string, any>) {
      console.error('Error:', error, context);
      
      // Send to error tracking service (Sentry, LogRocket, etc.)
      if (typeof window !== 'undefined' && window.gtag) {
        window.gtag('event', 'exception', {
          description: error.message,
          fatal: false,
          ...context,
        });
      }
    }
  16. Step 16

    Example: Complete Web3 AI Feature Implementation

    Here's a complete example of a page that combines all the technologies: wallet connection, IPFS storage, The Graph queries, and AI analysis.

    This example shows an NFT gallery that:

    1. Connects user's wallet via RainbowKit
    2. Queries user's NFTs from The Graph subgraph
    3. Retrieves metadata from IPFS
    4. Uses AI to generate descriptions and analyze rarity
    // app/gallery/page.tsx
    'use client';
    import { ConnectButton } from '@rainbow-me/rainbowkit';
    import { useAccount } from 'wagmi';
    import { useQuery } from '@apollo/client';
    import { useState } from 'react';
    import { GET_NFTS } from '@/lib/apollo-client';
    import { getIPFSUrl } from '@/lib/ipfs';
    
    export default function NFTGallery() {
      const { address, isConnected } = useAccount();
      const [analysis, setAnalysis] = useState<Record<string, string>>({});
    
      // Query NFTs from The Graph
      const { data, loading, error } = useQuery(GET_NFTS, {
        variables: { first: 20, skip: 0, owner: address?.toLowerCase() },
        skip: !isConnected,
      });
    
      // AI analysis of NFT metadata
      async function analyzeNFT(tokenId: string, metadata: any) {
        const response = await fetch('/api/analyze-nft', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ tokenId, metadata }),
        });
        const reader = response.body?.getReader();
        const decoder = new TextDecoder();
        let result = '';
    
        while (true) {
          const { done, value } = await reader!.read();
          if (done) break;
          result += decoder.decode(value);
          setAnalysis(prev => ({ ...prev, [tokenId]: result }));
        }
      }
    
      if (!isConnected) {
        return (
          <div className="flex min-h-screen items-center justify-center">
            <div className="text-center">
              <h1 className="text-3xl font-bold mb-4">Web3 AI NFT Gallery</h1>
              <p className="mb-6 text-gray-600">Connect your wallet to view your NFTs</p>
              <ConnectButton />
            </div>
          </div>
        );
      }
    
      if (loading) return <div className="p-8">Loading your NFTs...</div>;
      if (error) return <div className="p-8 text-red-600">Error: {error.message}</div>;
    
      return (
        <div className="min-h-screen p-8">
          <header className="flex justify-between items-center mb-8">
            <h1 className="text-3xl font-bold">Your NFT Gallery</h1>
            <ConnectButton />
          </header>
    
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            {data?.nfts.map((nft: any) => (
              <div key={nft.id} className="border rounded-lg p-4 hover:shadow-lg transition">
                <img
                  src={getIPFSUrl(nft.metadataCID)}
                  alt={`NFT #${nft.tokenId}`}
                  className="w-full aspect-square object-cover rounded mb-4"
                />
                <h3 className="font-semibold mb-2">Token #{nft.tokenId}</h3>
                <p className="text-sm text-gray-600 mb-2">
                  {nft.transfers.length} transfers
                </p>
                
                <button
                  onClick={() => analyzeNFT(nft.tokenId, nft)}
                  className="w-full bg-blue-600 text-white py-2 rounded hover:bg-blue-700 transition"
                >
                  ✨ AI Analysis
                </button>
                
                {analysis[nft.tokenId] && (
                  <div className="mt-4 p-3 bg-gray-50 rounded text-sm">
                    {analysis[nft.tokenId]}
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      );
    }
  17. Step 17

    Next Steps and Advanced Patterns

    Congratulations! You've built a complete Web3 + AI hybrid application. Here are advanced patterns and features to explore next:

    Advanced Web3 Features:

    • Account Abstraction: Implement ERC-4337 for gasless transactions and social recovery
    • Cross-chain Messaging: Use LayerZero or Wormhole for multi-chain interactions
    • ENS Integration: Resolve ENS names for better UX
    • Gnosis Safe: Add multi-sig wallet support
    • Gasless Transactions: Implement meta-transactions with relayers

    Advanced AI Features:

    • Vector Databases: Use Pinecone or Weaviate for semantic search over contracts
    • Fine-tuned Models: Train custom models on smart contract patterns
    • Multi-agent Systems: Build autonomous agents that coordinate on complex tasks
    • Real-time Anomaly Detection: Monitor blockchain activity for suspicious patterns

    Performance Optimizations:

    • Implement Redis caching for frequently accessed IPFS content
    • Use The Graph's caching directives for better query performance
    • Optimize LangChain chains with streaming and prompt caching
    • Implement progressive loading for large NFT collections

    Production Considerations:

    • Set up proper error tracking (Sentry)
    • Implement rate limiting on API routes
    • Add comprehensive logging and monitoring
    • Create runbooks for incident response
    • Set up automated testing in CI/CD

    Community Resources:

Feature requests

Sign in to suggest features or vote on existing ones.

No feature requests yet.

Discussion

0 people marked this as worked·Sign in to mark your own.

Sign in to join the discussion.

No comments yet.