Integrate the Self Agent Widget Using React

This document provides the integration steps to embed the Self Agent widget in your React application, with support for wallet synchronization.

Prerequisites

Ensure you have a React project set up with one of the following wallet libraries:

  • Wagmi
  • Ethers.js

Integration Steps

1. Project Initialization

  1. Create a new React project or use an existing one:
    npx create-next-app@latest
    
  2. Install dependencies:
    npm install
    
  3. Start the development server:
    npm run dev
    

2. Create Widget Component

  1. Create a new component file IframeRenderer.tsx:

    interface IframeRendererProps {
      isInjectedWallet: boolean;
      address: string;
    }
    
    const IframeRenderer: React.FC<IframeRendererProps> = ({
      isInjectedWallet,
      address,
    }) => {
      const WIDGET_URL = "https://self-agent-widget.vercel.app/";
      const AGENT_ADDRESS = "YOUR_AGENT_ADDRESS";
    
      useEffect(() => {
        if (!address || !isInjectedWallet) return;
    
        const timer = setTimeout(() => {
          document.querySelector("iframe")?.contentWindow?.postMessage(
            { type: "updateAccount", account: address },
            "*"
          );
        }, 2000);
    
        return () => clearTimeout(timer);
      }, [address, isInjectedWallet]);
    
      return (
        <iframe
          height={700}
          width={400}
          src={`${WIDGET_URL}?agent=${AGENT_ADDRESS}`}
        />
      );
    };
    

3. Implement Widget Integration

  1. Option A: Using Wagmi

    // index.tsx
    import { useAccount } from 'wagmi';
    
    export default function Home() {
      const { connector, address } = useAccount();
    
      return (
        <IframeRenderer
          address={address as Address}
          isInjectedWallet={
            connector?.id === "injected" || connector?.id === "eip6963"
          }
        />
      );
    }
    
  2. Option B: Using Ethers.js

    // App.tsx
    import { useState, useEffect } from 'react';
    import { ethers } from 'ethers';
    
    export default function App() {
      const [address, setAddress] = useState<string>();
    
      return (
        <IframeRenderer
          address={address}
          isInjectedWallet={true}
        />
      );
    }
    

Important Notes

  • The widget requires a 2-second delay to ensure proper wallet synchronization
  • Only verified Self agents can integrate the widget
  • The widget handles wallet synchronization to prevent Metamask address mismatch issues

Example Implementations