bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 37쪽 중 14쪽
n 2.0.0. The configured `ConnectKitProvider` component wraps the app’s content, ensuring this setup is accessible throughout the application.
## Integrate Particle Connect in Your App 
After configuration, wrap your application with the `ParticleConnectKit` component to provide access to the Particle Connect SDK across the app. Update the `layout.tsx` file in the `src` directory as follows:
```javascript
import { ParticleConnectkit } from "@/components/Connectkit";
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "Particle Connectkit App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={inter.className}>
<ParticleConnectkit>{children}</ParticleConnectkit>
</body>
</html>
);
}
```
## Building the Application 
With your project set up, dependencies installed, and Particle Connect configured, you can start building in the `page.tsx` file.
In `page.tsx`, you’ll define the core features: login flow, data visualization, transaction handling, and the UI.
### Connecting the Wallet 
With `layout.tsx` set up, the next step is to add a main **Connect Wallet** button for user login. Import `ConnectButton` from `@particle-network/connectkit` and add it to the interface. Once the user logs in, the `ConnectButton` transforms into an embedded wallet widget.
```javascript
"use client";
import { ConnectButton, useAccount } from "@particle-network/connectkit";
const HomePage = () => {
const { address, isConnected, chainId } = useAccount();
return (
<div className="flex justify-center items-center h-screen">
<div className="text-center">
<ConnectButton />
{isConnected && (
<>
<h2>Address: {address}</h2>
<h2>Chain ID: {chainId}</h2>
</>
)}
</div>
</div>
);
};
export default HomePage;
```
### Sending Transactions with an EIP-1193 Provider 
Particle Connect offers built-in AA features, but pairing it with the Particle AA SDK lets you leverage EIP-1193 providers like `ethers`. This setup is particularly useful if you’re already accustomed to these providers or if you’re integrating Particle Connect into an existing application.
To set this up, wrap the smart account from Particle Connect within an `ethers` instance to create a `customProvider`. This lets you interact with ethers as usual while the smart account manages transaction signing in the background.
```javascript
import {useSmartAccount } from "@particle-network/connectkit";
import { AAWrapProvider, SendTransactionMode } from "@particle-network/aa";
const smartAccount = useSmartAccount();
// Init custom provider with gasless transaction mode
const customProvider = smartAccount
? new ethers.BrowserProvider(
new AAWrapProvider(
smartAccount,
SendTransactionMode.Gasless
) as Eip1193Provider,
"any"
)
: null;
/**
* Sends a transaction using the ethers.js library.
* This transaction is gasless since the customProvider is initialized as gasless
*/
const executeTxEthers = async () => {
if (!customProvider) return;
const signer = await customProvider.getSigner();
const tx = {
to: recipientAddress,
value: parseEther("0.01").toString(),
};
const txResponse = await signer.sendTransaction(tx);
const txReceipt = await txResponse.wait();
console.log(txReceipt?.hash)
};
```
This transaction is gasless due to two factors:
1. **Gasless Mode:** Setting `SendTransactionMode.Gasless` in `AAWrapProvider` specifies a sponsored transaction.
2. **Funding:** On Testnets like Mantle Sepolia, transactions are automatically sponsored, so no USDT is needed. On mainnets, the Paymaster (configured in the [Particle dashboar](https://dashboard.particle.network/)d) must be funded to cover transaction fees.
This example uses an EIP-1193 provider, though you can also create a userOp directly with Particle Connect. For details, see the [starter repository](https://github.com/Particle-Network/connectkit-aa-usage/blob/2017262daf297624362d51f3d50cccd3b4606ef9/app/page.tsx#L117).
## Full App Example 
With an understanding of each part, you can now use Particle Connect, as shown in the example application below.
This application creates a smart account on Mantle Sepolia through either social or Web3 login and sends a gasless transaction of 0.01 MNT using the `ethers` provider.
```javascript
"use client";
import React, { useEffect, useState } from "react";
// Particle imports
import {
ConnectButton,
useAccount,
usePublicClient,
useSmartAccount,
} from "@particle-network/connectkit";
// Eip1193 and AA Provider
import { AAWrapProvider, SendTransactionMode } from "@particle-network/aa"; // Only needed with Eip1193 provider
import { ethers, type Eip1193Provider } from "ethers";
import { formatEther, parseEther } from "viem";
export default function Home() {
const { isConnected, chain } = useAccount();
const publicClient = usePublicClient();
const smartAccount = useSmartAccount();
const [userAddress, setUserAddress] = useState<string>("");
const [balance, setBalance] = useState<string | null>(null);
const [recipientAddress, setRecipientAddress] = useState<string>("");
const [transactionHash, setTransactionHash] = useState<string | null>(null);
// Init custom provider with gasless transaction mode
const customProvider = smartAccount
? new ethers.BrowserProvider(
new AAWrapProvider(
smartAccount,
SendTransactionMode.Gasless
) as Eip1193Provider,
"any"
)
: null;
/**
* Fetches the balance of a given address.
* @param {string} address - The address to fetch the balance for.
*/
const fetchBalance = async (address: string) => {
try {
const balanceResponse = await publicClient?.getBalance({
address: address as `0x${string}`,
});
if (balanceResponse) {
const balanceInEther = formatEther(balanceResponse).toString();
setBalance(balanceInEther);
} else {
setBalance("0.0");
}
} catch (error) {
console.error("Error fetching balance:", error);
setBalance("0.0");
}
};
/**
* Loads the user's account data, including address and balance.
*/
useEffect(() => {
const loadAccountData = async () => {
if (isConnected && smartAccount) {
try {
const address = await smartAccount.getAddress();
setUserAddress(address);
await fetchBalance(address);
} catch (error) {
console.error("Error loading account data:", error);
}
}
};
loadAccountData();
}, [isConnected, smartAccount]);
/**
* Sends a transaction using the ethers.js library.
* This transaction is gasless since the customProvider is initialized as gasless
*/
const executeTxEthers = async () => {
if (!customProvider) return;
const signer = await customProvider.getSigner();
try {
const tx = {
to: recipientAddress,
value: parseEther("0.01").toString(),
};
const txResponse = await signer.sendTransaction(tx);
const txReceipt = await txResponse.wait();
setTransactionHash(txReceipt?.hash || null);
} catch (error) {
console.error("Failed to send transaction using ethers.js:", error);
}
};
return (
<div className="container min-h-screen flex flex-col justify-center items-center mx-auto gap-4 px-4 md:px-8">
<div className="w-full flex justify-center mt-4">
<ConnectButton label="Click to login" />
</div>
{isConnected && (
<>
<div className="border border-purple-500 p-6 rounded-lg w-full">
<h2 className="text-lg font-semibold mb-2 text-white">
Address: <code>{userAddress || "Loading..."}</code>
</h2>
<h2 className="text-lg font-semibold mb-2 text-white">
Balance: {balance || "Loading..."} {chain?.nativeCurrency.symbol}
</h2>
<input
type="text"
placeholder="Recipient Address"
value={recipientAddress}
onChange={(e) => setRecipientAddress(e.target.value)}
className="mt-4 p-3 w-full rounded border border-gray-700 bg-gray-900 text-white focus:outline-none"
/>
<button
className="bg-purple-600 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded mt-4"
onClick={executeTxEthers}
disabled={!recipientAddress}
>
Send 0.001 {chain?.nativeCurrency.name}
</button>
{transactionHash && (
<p className="text-green-500 mt-4">
Transaction Hash: {transactionHash}
</p>
)}
</div>
</>
)}
</div>
);
}
```
### Particle Connect Hooks 
This example demonstrates a basic usage of Particle Connect. For the complete list of hooks, see the Particle Connect documentation.
# Wallet
Mantle supports multiple wallets for interacting with the network.
## Reown[](https://docs-v2.mantle.xyz/devs/dev-guides/tools/wallet/overview#web3modal) <a href="#web3modal" id="web3modal"></a>
Reown (formerly WalletConnect Inc.) is an onchain UX platform providing toolkits (AppKit and WalletKit) that help builders create intuitive, secure, and seamless Web3 experiences. Check more details [here](/network/for-developers/resources-and-tooling/wallet/reown).
## Multisig Wallet[](https://docs-v2.mantle.xyz/devs/dev-guides/tools/wallet/overview#multisig-wallet) <a href="#multisig-wallet" id="multisig-wallet"></a>
Multisig wallet is a wallet that can be used to sign transactions with multiple signers. This is useful when you cooperate with multiple people in your project and also increase the decentralization of your project. Mantle also supports this important feature. Check more details [here](/network/for-developers/resources-and-tooling/wallet/multisig-wallet).
# Reown
Learn how to use Reown AppKit to enable wallet connections and interact with the Mantle network.
With AppKit, you can provide seamless wallet connections, including email and social logins, on-ramp functionality, smart accounts, one-click authentication, and wallet notifications, all designed to deliver an exceptional user experience.
In this tutorial, you will learn how to:
1. Set up Reown AppKit.
2. Configure a wallet connection modal and enable interactions with the Mantle network.
This guide takes approximately 10 minutes to complete.
Let’s get started!
### Setup <a href="#installation" id="installation"></a>
In this section, you'll learn how to set up the development environment to use AppKit with Mantle.
For this tutorial, we'll be using Next.js, though you can use any other framework compatible with AppKit.
{% hint style="info" %}
*AppKit is available on eight frameworks, including React, Next.js, Vue, JavaScript, React Native, Flutter, Android, iOS, and Unity.*
{% endhint %}
Now, let’s create a Next app. In order to do so, please run the command given below:
```bash
npx create-next-app@latest appkit-example
```
The above command creates a Next app and sets the name of the Next app as “appkit-example”.
#### Install AppKit
Now, we need to install AppKit and other dependencies that we need for our app to function as expected. For this tutorial, we will be using “wagmi” as our preferred Ethereum library. 
```bash
npm install @reown/appkit @reown/appkit-wagmi-adapter wagmi @tanstack/react-query
```
{% hint style="info" %}
Reown also supports wagmi v1, ethers, ethers v5, if you want to use other sdk, please refer to their documentation [here](https://docs.reown.com/appkit/react/core/installation).
{% endhint %}
#### Create a New Project on Reown Cloud
Now, we need to get a project Id from Reown Cloud that we will use to set up AppKit with Wagmi config. Navigate to [cloud.reown.com](https://cloud.reown.com/) and sign in. If you have not created an account yet, please do so before we proceed.
After you have logged in, please navigate to the “**Projects**” section of the Cloud and click on “**Create Project**”.
<figure><img src="https://3885809119-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FQliZlRNwHhmzesDU1Ksq%2Fuploads%2FlpblnqCweJvTvxFsxOln%2Fimage.png?alt=media&token=0fe5b56a-637a-43e8-93ee-4748573fc96f" alt=""><figcaption></figcaption></figure>
Now, enter the name for your project and click on “**Continue**”.
<figure><img src="https://3885809119-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FQliZlRNwHhmzesDU1Ksq%2Fuploads%2FdK49FeaOTWH9Yc3eDe2Y%2Fimage.png?alt=media&token=cacee33b-aab0-44c2-9349-27f2dbadf82e" alt=""><figcaption></figcaption></figure>
Select the product as “**AppKit**” and click on “**Continue**”.
<figure><img src="https://3885809119-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FQliZlRNwHhmzesDU1Ksq%2Fuploads%2Fq4bQrVFie52QBuDt3mWg%2Fimage.png?alt=media&token=90cad039-afdc-4b71-ad8d-98abe4319f6d" alt=""><figcaption></figcaption></figure>
Select the framework as “**Next.js**” and click on “**Create**”. Reown Cloud will now create a new project for you which will also generate a project Id.
<figure><img src="https://3885809119-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FQliZlRNwHhmzesDU1Ksq%2Fuploads%2FLmycWqby2Wdqf3OlxvrK%2Fimage.png?alt=media&token=6e18dd44-0e39-415f-86e4-00bd06647b92" alt=""><figcaption></figcaption></figure>
You will notice that your project was successfully created. On the top left corner, you will be able to find your Project Id. Please copy that as you will need that later.
<figure><img src="https://3885809119-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FQliZlRNwHhmzesDU1Ksq%2Fuploads%2FMvDCFDdWJ1IKgxoCAHIo%2Fimage.png?alt=media&token=593ff14e-e3de-448c-b4be-29bd9fb5c37c" alt=""><figcaption></figcaption></figure>
You will notice that your project was successfully created. On the top left corner, you will be able to find your Project Id. Please copy that as you will need that later.
### Build the App Using AppKit
Before we build the app, let’s first configure our .env file. On the root level of your code directory, create a new file named .env.
Open that file and create a new variable NEXT\_PUBLIC\_PROJECT\_ID. You will assign the project Id that you copied in the previous step to this environment variable that you just created. This is what it will look like:
```
NEXT_PUBLIC_PROJECT_ID = <YOUR_PROJECT_ID_HERE>
```
{% hint style="info" %}
*Please make sure you follow the best practices when you are working with secret keys and other sensitive information. Environment variables that start with NEXT\_PUBLIC will be exposed by your app which can be misused by bad actors.*
{% endhint %}
#### Configure AppKit
On the root level of your code directory, create a new folder named config and within that folder, create a new code file named config/index.tsx. Now, paste the code snippet shared below inside the code file, i.e., `config/index.tsx.TypeScriptCopy`
```javascript
import { WagmiAdapter } from "@reown/appkit-adapter-wagmi";
import { cookieStorage, createStorage } from "wagmi";
import { mantle, mantleSepoliaTestnet } from '@reown/appkit/networks'
// Get projectId from https://cloud.reown.com
export const projectId = process.env.NEXT_PUBLIC_PROJECT_ID;
export const networks = [mantle, mantleSepoliaTestnet]
if (!projectId) throw new Error("Project ID is not defined");
// Set up the Wagmi Adapter (config)
export const wagmiAdapter = new WagmiAdapter({
storage: createStorage({
storage: cookieStorage
}),
ssr: true,
networks,
projectId
})
export const config = wagmiAdapter.wagmiConfig
```
So what's happening in the above code? Let's understand it step-by-step:
First, we need to import the necessary functions from their respective packages.
**WagmiAdapter -** this is used to create a WAGMI configuration which is then initialized to the wagmiAdapter
**cookieStorage, createStorage -** this provides a storage mechanism using cookies and a function to create custom storage solutions (in this case, using cookies).
#### Create the Modal for your app
Now, we need to create a context provider to wrap our application in and initialize AppKit.
On the root level of your code directory, create a new folder named context and within that folder, create a new code file named context/index.tsx. Now, paste the code snippet shared below inside the code file, i.e., `context/index.tsx`.
```typescript
'use client'
import { wagmiAdapter, projectId } from '@/config'
import { createAppKit } from '@reown/appkit/react'
import { mantle, mantleSepoliaTestnet } from '@reown/appkit/networks'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
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 = { //this is optional
name: "appkit-example-mantle",
description: "AppKit Example - Mantle",
url: "https://mantleapp.com", // origin must match your domain & subdomain
icons: ["https://avatars.githubusercontent.com/u/179229932"]
}
// Create the modal
const modal = createAppKit({
adapters: [wagmiAdapter],
projectId,
networks: [mantle, mantleSepoliaTestnet],
metadata: metadata,
features: {
analytics: true, // Optional - defaults to your Cloud configuration
},
themeMode: 'light'
})
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
```
Let’s understand what is happening in the above code:
First, we import the necessary functions from their respective packages. After this, we need to create the modal component for our app.
* **metadata** - This object contains information about our application that will be used by AppKit. This includes the name of the app, the description, the url and the icons representing our app. **This is optional.**
* `createAppKit` - this is called to initialize the AppKit component, which handles the user interface for connecting to blockchain wallets. The function is configured with various options, such as the app's metadata, theming, and enabling features like analytics and onramp services.
* **networks -** these are the networks that we want our app to support. So import the chains you want your app to support from `@reown/appkit/network` and assign it to this network parameter. Since we want to enable wallet interactions on the Mantle network, we import both Mantle Mainnet and the Sepolia testnet. You can view the complete list of supported chains [here](https://wagmi.sh/core/api/chains).
* **WagmiProvider**: Provides blockchain and wallet connection context to the app.
* **QueryClientProvider**: Provides the React Query context for managing server-state data.
Now, let’s create the layout for our app. In `app/layout.tsx`, remove the existing code and paste the code snippet given below.
```typescript
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
const inter = Inter({ subsets: ["latin"] });
import { headers } from "next/headers"; // added
import ContextProvider from '@/context'
export const metadata: Metadata = {
title: "AppKit Example App",
description: "Powered by Reown"
};
export default function RootLayout({
children
}: Readonly<{
children: React.ReactNode
}>) {
const cookies = headers().get('cookie')
return (
<html lang="en">
<body className={inter.className}>
<ContextProvider cookies={cookies}>{children}</ContextProvider>
</body>
</html>
)
}
```
#### Create the UI for your app
For our app to have the UI with which your users can interact, you need to set a simple UI and configure the modal. Since, we have already set up AppKit, you can use \<w3m-button> which will serve as a “Connect Wallet” button or you can build your own custom button using the [hooks](https://docs.walletcon프로젝트로 돌아가기