DEV Community

Cover image for INTEGRATION OF DAPPS WITH MODE: WALLET AND SMART CONTRACTS | PART 1: CONNECTING THE WALLET
wispy for Mode

Posted on

INTEGRATION OF DAPPS WITH MODE: WALLET AND SMART CONTRACTS | PART 1: CONNECTING THE WALLET

This tutorial is also available in video format. If you prefer to follow along visually, you can watch it here. Let's get started!

Welcome to the first part of our series, "Integrating DApps with Mode: Wallet and Smart Contracts"! In this introductory tutorial, we'll dive into connecting wallets to a Next.js application, with a special focus on integrating the Mode blockchain.

Throughout this guide, you will learn how to:

  1. Set up a basic Next.js project to create the foundation for your decentralized application
  2. Install and configure reown to enable wallet connections and smart wallet support
  3. Add Mode network to the wallet options (and any EVM chain)

The wallet integration you'll learn in this tutorial is a fundamental step in developing decentralized applications (DApps). By enabling users to connect their wallets to your application, you'll establish the necessary foundation to interact with the Mode. While we're focusing specifically on this connection, mastering this component is essential for any DApp you plan to build in the future.

Once you complete this part, you'll be ready to move on to Part 2 of the series, where we'll explore how to connect a smart contract to the front end we create here, further expanding your application's capabilities. Ready to take this important first step in developing your DApp with Mode? Let's get started!

Installing Next.js

1 Open your terminal and run the following command to install Next.js:

`npx create-next-app@13.4.19`
Enter fullscreen mode Exit fullscreen mode

2 During the installation, configure your project with the following options:

  • Project name: mode-chain

  • TypeScript: yes (optional)

    • Selecting yes enables TypeScript for static typing, helping to catch errors early and improve code quality. Choosing no configures your project to use JavaScript.
  • ESLint: yes (optional)

    • If you choose yes, ESLint will be integrated to help detect errors and maintain code quality. Selecting no means that no linting rules will be applied by default.
  • Tailwind CSS: no (optional)

    • Choosing no means Tailwind CSS will not be installed, so you won’t have access to its utility classes for rapid styling. You can always integrate Tailwind CSS later if you decide you want to use it for custom styling.
  • src/ directory: yes (optional)

    • Selecting yes creates a src/ folder to organize your source code. If you choose no, your code will reside in the project's root directory.
  • App Router: yes (optional)

    • If you select yes, a router will be set up to manage navigation in your application. Choosing no means you'll need to implement navigation manually later on.
  • Import alias: yes (optional)

    • By choosing yes, you can use import aliases, which helps in organizing your code and improving readability. If you select no, you'll have to use standard relative paths for imports.

3 Once the installation is complete, navigate to the project directory with:

`cd mode-chain`
Enter fullscreen mode Exit fullscreen mode

4 To view the initial front-end, run:

`npm run dev`
Enter fullscreen mode Exit fullscreen mode

You should see an output similar to this in your terminal:

Image description

5 Open your browser and go to http://localhost:3000. You can also directly open the link by Ctrl + left-click on the URL that appears in the terminal.
This is what your application looks like before integrating reown:

Image description

Cloud Configuration

Project ID and reown (formerly known as WalletConnect) Setup

  1. Visit https://cloud.reown.com/sign-in and create an account (I recommend creating an account instead of connecting a wallet, as this can lead to several issues).
  2. Create a new project by clicking "Create New Project."
  3. You will see two options:
    • Name: Enter your project name (for example, "mode-chain").
    • Link Home page URL: You can leave this field blank if you prefer.
  4. Click on "Continue." Then, two new options will appear: AppKit and WalletKit. Select AppKit and choose React.
  5. After creating the project, you will be directed to the “QuickStart” section. Here you will find:

    1. Install package: In my case, I’ll select npm and wagmi. The reown installation command will be:

      npm i @reown/appkit @reown/appkit-adapter-wagmi wagmi viem @tanstack/react-query

    2. Get started: This section will provide you with code for:

      • wagmi configuration (including your Project ID automatically)
      • Context Provider
      • Layout

      These code snippets are crucial for the implementation and will be used in the following sections of the tutorial.

The Project ID is a unique identifier that allows you to use reown services in your application.

Installing reown

After setting up your project in reown Cloud, follow these steps to install reown in your Next.js project:

  • In the "QuickStart" section of your project on reown Cloud, specifically under Install package, you will see the installation options. For this tutorial, we will use npm and wagmi.
  • Open a terminal in your project directory and run the following command:

    npm i @reown/appkit @reown/appkit-adapter-wagmi wagmi viem @tanstack/react-query

    This command installs all the necessary dependencies for reown and wagmi.

Note: If you prefer to use a different setup (e.g., yarn instead of npm, or ethers instead of wagmi), you can find specific instructions in the official reown documentation.

reown implementation

Wagmi Config

The Wagmi configuration is essential for integrating reown and the desired chains, including Mode Chain. Follow these steps:

  1. Create a new folder called config at the root of your project.
  2. Inside the config folder, create a file named index.tsx.
  3. Copy the following code and paste it into config/index.tsx:

This is what your application looks like before integrating reown:

// config/index.tsx

import { cookieStorage, createStorage, http } from '@wagmi/core'
import { WagmiAdapter } from '@reown/appkit-adapter-wagmi'
import { mainnet, sepolia, mode, modeTestnet } from '@reown/appkit/networks'

// Get projectId from https://cloud.reown.com
export const projectId = 'YOUR_PROJECT_ID'

if (!projectId) {
    throw new Error('Project ID is not defined')
}

export const networks = [mainnet, sepolia, mode, modeTestnet]

//Set up the Wagmi Adapter (Config)
export const wagmiAdapter = new WagmiAdapter({
    storage: createStorage({
        storage: cookieStorage
    }),
    ssr: true,
    projectId,
    networks
})

export const config = wagmiAdapter.wagmiConfig
Enter fullscreen mode Exit fullscreen mode

Main Features:

  • Replace YOUR_PROJECT_ID with the project ID you obtained from reown Cloud.
  • In the line import { mainnet, sepolia, mode, modeTestnet } from '@reown/appkit/networks':
    • mainnet and sepolia are Ethereum chains included by default (mainnet and Sepolia testnet).
    • We added mode (Mode mainnet) and modeTestnet (Mode testnet) to integrate Mode chains.
  • Session storage: CookieStorage is used to save session data, allowing users to continue where they left off when they return to the application.
  • WagmiAdapter: This adapter simplifies the connection setup with Wagmi using the Reown project. The ssr: true option is also defined to ensure the configuration works on the server side.

Context Provider

The Context Provider is necessary to initialize Web3Modal and wrap our application. Follow these steps:

  1. Create a new folder called context at the root of your project.
  2. Inside the context folder, create a file named index.tsx.
  3. Copy the following code and paste it into context/index.tsx:
// context/index.tsx
'use client'

import { wagmiAdapter, projectId } from '../config'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { createAppKit } from '@reown/appkit/react'
import { mainnet, sepolia, mode, modeTestnet } from '@reown/appkit/networks'
import React, { type ReactNode } from 'react'
import { cookieToInitialState, WagmiProvider, type Config } from 'wagmi'

// Set up queryClient
const queryClient = new QueryClient()

if (!projectId) {
    throw new Error('Project ID is not defined')
}

// Set up metadata
const metadata = {
    name: 'mode-chain',
    description: 'AppKit Example',
    url: 'https://reown.com/appkit', // origin must match your domain & subdomain
    icons: ['https://assets.reown.com/reown-profile-pic.png']
}

// Create the modal
const modal = createAppKit({
    adapters: [wagmiAdapter],
    projectId,
    networks: [mainnet, sepolia, mode, modeTestnet],
    defaultNetwork: mainnet,
    metadata: metadata,
    features: {
        analytics: true, // Optional - defaults to your Cloud configuration
    }
})

function ContextProvider({ children, cookies }: { children: ReactNode; cookies: string | null }) {
    const initialState = cookieToInitialState(wagmiAdapter.wagmiConfig as Config, cookies)

    return (
        <WagmiProvider config={wagmiAdapter.wagmiConfig as Config} initialState={initialState}>
            <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
        </WagmiProvider>
    )
}

export default ContextProvider
Enter fullscreen mode Exit fullscreen mode

Main Features:

  • Connection Modal: createAppKit creates the modal that will allow users to connect their wallets to the application. It is configured with the wagmiAdapter, projectId, and the supported networks (Ethereum and Mode).
  • Cookies: The cookieToInitialState function retrieves the cookies stored in the browser to initialize the application with the user's previous state, ensuring continuity of their session.
  • Clients and Providers: QueryClientProvider and WagmiProvider are responsible for providing the necessary context so that the entire application can interact with Web3 and the configured networks.

Layout

The Layout is crucial for integrating Web3ModalProvider throughout your Next.js application. Follow these steps:

  1. Open the app/layout.tsx file in your project.
  2. Replace the existing content with the following code:
// app/layout.tsx
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";

import { headers } from "next/headers"; // added
import ContextProvider from '../../context'

export const metadata: Metadata = {
  title: "AppKit Example App",
  description: "Powered by WalletConnect"
};

export default async function RootLayout({
  children
}: Readonly<{
  children: React.ReactNode
}>) {
  const headerList = await headers();
  const cookies = headerList.get('cookie')

  return (
    <html lang="en">
      <body>
        <ContextProvider cookies={cookies}>{children}</ContextProvider>
      </body>
    </html>
  )
}
Enter fullscreen mode Exit fullscreen mode

Main Features:

  • Headers and Cookies: The use of headers() in Next.js allows for retrieving cookies passed from the server, which is necessary for initializing the user's session state in the application.
  • Global Wrappers: Wraps the entire application within the ContextProvider, enabling Web3 functionalities (such as wallet connections) to be available across all pages of the application.

Trigger the Modal

To allow users to connect their wallets, we need to add a button that triggers the reown modal. Follow these steps:

  1. Reown provides a web component <w3m-button /> that you can use directly in your application.
  2. This component does not require importing, as it is a global HTML element.
  3. To add the connection button, simply insert <w3m-button /> into any component of your application where you want it to appear.

Example usage:

export default function HomePage() {
  return (
    <div>
      <h1>Welcome to my DApp!</h1>
      <w3m-button />
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

After adding the connection button to your DApp, you should see a button with the text "Connect Wallet," similar to this:

Image description

When we connect the wallet, we can observe that we have access to both the Mode mainnet and the Mode testnet:

Image description

Note: If you prefer more control over the design or behavior of the button, you can create your own component using the AppKit hooks. Check the official documentation for more details.

Get ready for the next level!

In Part 2 of this series, we'll take your DApp to the next level by connecting a smart contract to the front end we just created. This will allow you to interact with the Mode blockchain more comprehensively, unlocking the full potential of your decentralized application.

Useful links:

Thank you for following this tutorial! If you have any questions or feedback, feel free to share them. See you in Part 2!

Top comments (0)