Wagmi

Integrating with wagmi

A step-by-step guide to integrating the Okto-Wagmi adapter into Wagmi-based dApps, enabling smooth wallet connectivity and streamlined user onboarding.

Quick Start Template Available!

Skip the manual setup and get started in minutes with our template repository. Please note that this template is for development and testing purposes only. Be sure to customize and secure it before using in production.

Note that this repository includes multiple branches, each corresponding to a different adapter integration. For integrating Okto with Wagmi, refer to the bmac-react-wagmi-okto branch.

Wagmi is a collection of React hooks for Ethereum, making it easy to interact with wallets and smart contracts. Okto provides seamless integration with Wagmi through its adapter package, allowing you to add social login options via Okto to your existing Wagmi application.

This guide shows how to add Okto wallet support to an existing wagmi application, enabling social login options for your users.

If you're starting from scratch, you have two options:

Installation

Install the Okto wagmi adapter package and other dependencies:

npm i @okto_web3/wagmi-adapter wagmi @tanstack/react-query

Essential Vite Configuration for Wagmi + Okto

When integrating Okto with Wagmi in a Vite project, you'll need to add Node.js polyfills to resolve browser buffer issues. Update your vite.config.ts file with this configuration:

vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { nodePolyfills } from "vite-plugin-node-polyfills";
 
// https://vite.dev/config/
export default defineConfig({
  plugins: [react(), nodePolyfills()],
  server: {
    port: 3000, // will always start the service on port 3000
  },
});

Don't forget to install the required package:

npm i -D vite-plugin-node-polyfills

Without this package, your app will fail to build or run properly.

Configure Okto

Warning:Essential Setup Required
Show

Set up your Okto Developer Dashboard by making sure you have :

If you need help, reach out to us on our troubleshooting form and we will contact you.

Before getting started, ensure you have the following:

Configure Wagmi

Create a configuration file to set up wagmi with the Okto connector. You can choose between two authentication methods:

This method provides a streamlined Google sign-in experience.

wagmi.config.ts
import { okto } from '@okto_web3/wagmi-adapter';
import { cookieStorage, createConfig, createStorage, http } from 'wagmi';
import { baseSepolia } from 'wagmi/chains';
 
export function getConfig() {
  return createConfig({
    chains: [baseSepolia],
    connectors: [
      okto({
        environment: 'sandbox',
        clientPrivateKey: '0xprivatekey',
        clientSWA: '0xswa',
        googleClientId: 'xxx',
      }),
    ],
    storage: createStorage({
      storage: cookieStorage,
    }),
    ssr: true,
    transports: {
      [baseSepolia.id]: http(),
    },
  });
}
 
declare module 'wagmi' {
  interface Register {
    config: ReturnType<typeof getConfig>;
  }
}

📝 Login Types Explained

  • Google OAuth (default): Uses Google OAuth for authentication, providing a simple sign-in experience with Google accounts.
  • Okto Onboarding Modal (loginType: 'generic'): Opens a full onboarding modal with multiple authentication options (Google, email, phone, etc.) Choose the method that best fits your user experience needs!

Okto Configuration Parameters

ParameterDescriptionTypeRequired
environmentEnvironment to use for the SDK'sandbox' | 'production'Yes
clientPrivateKeyYour client private keystringYes
clientSWAYour client SWAstringYes
googleClientIdYour Google client IDstringNo
loginTypeLogin method type'generic'No

Set Up Providers

Update your app's root component to include the necessary providers:

layout.tsx
"use client";
 
import { headers } om 'next/headers';
import { useState } from 'react';fr
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { ReactNode } fm 'reacrot';
import Script from 'next/script';
import { WagmiProvider, cookieToInitialState } from 'wagmi';
import { getConfig } from '../wagmi';
 
export default async function Layout(props: { children: ReactNode }) {
  const initialState = cookieToInitialState(
    getConfig(),
    (await headers()).get('cookie'),
  );
 
  const [config] = useState(() => getConfig());
  const [queryClient] = useState(() => new QueryClient());
 
  return (
    <html lang="en">
      <head>
        <Script src="https://accounts.google.com/gsi/client" async defer /> // Not needed if using Onboarding Modal
      </head>
      <body>
        <WagmiProvider config={config} initialState={initialState}>
          <QueryClientProvider client={queryClient}>
            {props.children}
          </QueryClientProvider>
        </WagmiProvider>
      </body>
    </html>
  );
}
main.tsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import { WagmiProvider } from "wagmi";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { config } from "./wagmi.config.ts";
 
(window as any).Buffer = Buffer;
 
const queryClient = new QueryClient();
 
createRoot(document.getElementById("root")!).render(
<StrictMode>
  <WagmiProvider config={config}>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  </WagmiProvider>
</StrictMode>
);

Note

For Vite project, add this script tag to your index.html file in the project root directory. The script must be placed inside the <head> tag.

<script src="https://accounts.google.com/gsi/client" async defer></script>

This is necessary for Google OAuth to work properly with wagmi. If using Onboarding Modal, this script is not required.

Usage with wagmi Hooks

Once configured, you can use wagmi hooks to offer Okto social login to your users:

import { useAccount, useConnect, useDisconnect } from 'wagmi';
 
function WalletConnection() {
  const { address, isConnected } = useAccount();
  const { connect, connectors } = useConnect();
  const { disconnect } = useDisconnect();
 
  if (isConnected) {
    return (
      <div>
        Connected to {address}
        <button onClick={() => disconnect()}>Disconnect</button>
      </div>
    );
  }
 
  return (
    <div>
      {connectors.map((connector) => (
        <button
          key={connector.id}
          onClick={() => connect({ connector })}
        >
          Connect with {connector.name}
        </button>
      ))}
    </div>
  );
}

Important Notes & Troubleshooting

Chain Switching

When using traditional wallets like MetaMask with Wagmi, users can change networks directly in their wallet interface, and your application code automatically picks up the current selected chain. However, Okto users don't have a separate wallet UI to change networks manually.

This means your application code must handle network switching programmatically when using Okto. If your dApp requires a specific chain (like Base Sepolia for transactions), you need to implement chain switching logic.

🔗 Network Switching: Traditional Wallets vs Okto

  • Traditional Wallets (MetaMask, etc.): User changes network in wallet → Code automatically detects the change
  • Okto: No external wallet UI → Your app must programmatically switch networks when needed

Implementation Example Here's how to implement automatic chain switching when a user tries to perform an action requiring a specific network:

import { useChainId, useSwitchChain } from 'wagmi';
 
const chainId = useChainId();
const { switchChain } = useSwitchChain();
 
const handleTransaction = async () => {
  // Check if user is on the required chain (Base Sepolia = 84532)
  if (chainId !== 84532) {
    try {
      console.log("Current chainId:", chainId);
      await switchChain({ chainId: 84532 }); // Switch to Base Sepolia
    } catch (error) {
      alert("Network switch to Base Sepolia failed or was rejected.");
      return;
    }
  }
  
  // Proceed with transaction now that we're on the correct network
  // ... your transaction logic here
};

This pattern ensures your dApp works seamlessly with Okto by automatically switching to the required network before executing transactions.