bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 57쪽
ng a custom connect button instead of the standard one provided by Reown AppKit.
### Create a `Header` component with custom `ConnectButton`
<img alt="header" />
Create a file named `Header.tsx` in `src/components/layout` folder and import the newly created `ConnectButton` component into it.
```tsx title="src/components/layout/Header.tsx" theme={null}
"use client";
import { ConnectButton } from "../wallet/ConnectButton";
import { ExternalLink } from "lucide-react";
export function Header() {
return (
<header className="sticky top-0 z-50 w-full border-b border-border bg-card/80 backdrop-blur supports-[backdrop-filter]:bg-card/60">
<div className="flex h-16 items-center justify-between">
<div className="flex items-center gap-3">
<h1 className="text-xl font-bold text-foreground">
Portfolio App
</h1>
</div>
<div className="flex items-center gap-6">
<ConnectButton />
</div>
</div>
</header>
);
}
```
Import the `Header` component in `layout.tsx`
```tsx title="src/app/layout.tsx" theme={null}
import { Header } from "@/components/layout/Header";
// rest of the code
<ContextProvider>
<Header />
<main className="flex-1 pb-6">{children}</main>
</ContextProvider>
// rest of the code
```
You should now be able to see a custom Connect Wallet button!
## Step 4: Fetching connected wallet token balances
### Creating a `/api/wallet/balances` route
Create a file named `route.ts` in the folder `src/app/api/wallet/balances/`
We are using the "Get Native & ERC20 Token Balances by Wallet" Moralis API endpoint to get the token balances. You can find the endpoint docs [here](https://docs.moralis.com/web3-data-api/evm/reference/wallet-api/get-wallet-token-balances-price?address=0xcB1C1FdE09f811B294172696404e88E658659905\&chain=0x8f\&token_addresses=\[]\&limit=25).
It takes in an address and a chain id and returns a list of ERC20 tokens (including Logo, Name, Symbol) and native balance of the address.
```ts title="src/app/api/wallet/balances/route.ts" theme={null}
import { NextRequest, NextResponse } from "next/server";
const MORALIS_API_BASE = "https://deep-index.moralis.io/api/v2.2";
export async function GET(request: NextRequest) {
try {
const { searchParams } = request.nextUrl;
const address = searchParams.get("address");
const chain = "0x8f"; // 0x8f = 143 (Monad chain ID in hex)
if (!address) {
return NextResponse.json(
{ error: "Address is required" },
{ status: 400 }
);
}
// Fetch ERC20 token balances with price data from Moralis
const data = await moralisRequest({
endpoint: `/wallets/${address}/tokens`,
params: {
chain,
},
});
return NextResponse.json(data);
} catch (error) {
console.error("Error fetching token balances:", error);
const errorMessage = error instanceof Error ? error.message : "Failed to fetch token balances";
return NextResponse.json(
{
error: errorMessage,
},
{ status: 500 }
);
}
}
async function moralisRequest({
endpoint,
params,
}) {
const apiKey = process.env.MORALIS_API_KEY;
if (!apiKey) {
throw new Error("MORALIS_API_KEY is not set");
}
const url = new URL(`${MORALIS_API_BASE}${endpoint}`);
if (params) {
Object.entries(params).forEach(([key, value]) => {
url.searchParams.append(key, String(value));
});
}
const response = await fetch(url.toString(), {
method: "GET",
headers: {
"X-API-Key": apiKey,
"Content-Type": "application/json",
},
next: {
revalidate: 30, // Cache for 30 seconds
},
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
const errorMessage = errorData.message || `Moralis API error: ${response.status}`;
console.error("Moralis API Error:", {
status: response.status,
url: url.toString(),
error: errorData,
});
throw new Error(errorMessage);
}
return response.json();
}
```
### Create a react hook called `useTokenBalances`
This react hook calls the `/api/wallet/balances/` endpoint that you created and gets the token balances data, formats it into a proper list and makes it available to consume in the frontend.
```ts title="src/hooks/useTokenBalances.ts" theme={null}
"use client";
import { useQuery } from "@tanstack/react-query";
async function fetchTokenBalances(
address: string,
) {
const response = await fetch(
`/api/wallet/balances?address=${address}`
);
if (!response.ok) {
const error = await response.json().catch(() => ({}));
throw new Error(error.error || "Failed to fetch token balances");
}
const data = await response.json();
// Check if data exists
if (!data) {
return [];
}
// Handle both response formats: direct array or object with result property
const tokens = Array.isArray(data) ? data : data.result;
if (!tokens || !Array.isArray(tokens)) {
return [];
}
// Transform Moralis data to our Token type
return tokens.map((token) => {
const balanceFormatted = parseFloat(
formatTokenBalance(token.balance, token.decimals)
);
// Calculate USD value if we have price but not value
const usdValue = token.usd_value !== undefined
? token.usd_value
: token.usd_price !== undefined
? token.usd_price * balanceFormatted
: undefined;
return {
address: token.token_address,
name: token.name,
symbol: token.symbol,
logo: token.logo || token.thumbnail,
decimals: token.decimals,
balance: token.balance,
balanceFormatted,
usdPrice: token.usd_price,
usdValue,
isNative: token.native_token || false,
isSpam: token.possible_spam,
verified: token.verified_contract,
};
});
}
export function useTokenBalances(address?: string, enabled: boolean = true) {
return useQuery({
queryKey: ["tokenBalances", address],
queryFn: () => fetchTokenBalances(address!),
enabled: enabled && !!address,
staleTime: 30000, // 30 seconds
});
}
function formatTokenBalance(
balance: string | number,
decimals: number = 18
): string {
const balanceNum = typeof balance === "string" ? parseFloat(balance) : balance;
const divisor = Math.pow(10, decimals);
const formattedBalance = balanceNum / divisor;
// Show more decimals for small amounts
if (formattedBalance < 0.01) {
return formattedBalance.toFixed(6);
} else if (formattedBalance < 1) {
return formattedBalance.toFixed(4);
} else {
return formattedBalance.toFixed(2);
}
}
```
We will later use this hook in the UI components
## Step 5: Creating the UI
### Create a `TokenRow` component
<img alt="token-row" />
`TokenRow` component will display token details like name, symbol, logo, usd price, amount of tokens in connected wallet and the usd value.
Create a file named `TokenRow.tsx` in the folder `src/components/portfolio/tokens/`
```tsx title="src/components/portfolio/tokens/TokenRow.tsx" theme={null}
import Image from "next/image";
export function TokenRow({ token }) {
return (
<div className="grid grid-cols-12 gap-4 px-6 py-4 hover:bg-muted/30 transition-colors">
{/* Token Info */}
<div className="col-span-4 flex items-center gap-3">
{token.logo ? (
<Image
src={token.logo}
alt={token.name}
width={40}
height={40}
className="rounded-full"
onError={(e) => {
e.currentTarget.style.display = "none";
}}
/>
) : (
<div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary font-bold border border-primary/20">
{token.symbol.charAt(0)}
</div>
)}
<div className="min-w-0">
<div className="flex items-center gap-2">
<p className="font-semibold truncate">{token.symbol}</p>
</div>
<p className="text-sm text-muted-foreground truncate">
{token.name}
</p>
</div>
</div>
{/* Price */}
<div className="col-span-2 flex items-center justify-end">
{token.usdPrice !== undefined && token.usdPrice > 0 ? (
<p className="text-sm font-medium">
${formatCurrency(token.usdPrice, 4)}
</p>
) : (
<p className="text-sm text-muted-foreground">-</p>
)}
</div>
{/* Amount */}
<div className="col-span-3 flex items-center justify-end">
<p className="font-medium">{formatCurrency(token.balanceFormatted, 2)}</p>
</div>
{/* USD Value */}
<div className="col-span-3 flex items-center justify-end">
{token.usdValue !== undefined && token.usdValue > 0 ? (
<p className="font-semibold text-primary">
{formatUSD(token.usdValue)}
</p>
) : (
<p className="text-sm text-muted-foreground">-</p>
)}
</div>
</div>
);
}
// Helper function to format values in the UI
function formatUSD(value: number): string {
if (value === 0) return "$0.00";
if (value < 0.01) return "< $0.01";
if (value < 1) return `$${value.toFixed(4)}`;
if (value < 1000) return `$${value.toFixed(2)}`;
if (value < 1000000) return `$${(value / 1000).toFixed(2)}K`;
return `$${(value / 1000000).toFixed(2)}M`;
}
function formatCurrency(value: number, decimals: number = 2): string {
return value.toLocaleString("en-US", {
minimumFractionDigits: decimals,
maximumFractionDigits: decimals,
});
}
```
### Create a `TokenList` component
<img alt="token-list" />
Create a `TokenList.tsx` file in `src/components/portfolio` folder and import the newly created `TokenRow.tsx` component in it.
```tsx title="src/components/portfolio/TokenList.tsx" theme={null}
import { TokenRow } from "./tokens/TokenRow";
export function TokenList({
tokens,
isLoading,
error,
showLowValueTokens = false,
}) {
if (isLoading) {
return (
// Loading state
);
}
if (error) {
return (
// Error state
);
}
if (tokens.length === 0) {
return (
// Empty state
);
}
return (
<div className="divide-y divide-border">
{tokens.map((token) => (
<TokenRow key={token.address} token={token} />
))}
</div>
);
}
```
### Create a `PortfolioDashboard` component
<img alt="dashboard" />
The `PortfolioDashboard` component will display the `TokenList` and can be further modified to have more components presenting information that you would like your user to see.
```tsx title="src/components/portfolio/PortfolioDashboard.tsx" theme={null}
"use client";
import { useState, useEffect } from "react";
import { useAccount } from "wagmi";
import { useTokenBalances } from "@/hooks/useTokenBalances";
import { TokenList } from "./TokenList";
export function PortfolioDashboard() {
const { address, isConnected } = useAccount();
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
const {
data: tokens = [],
isLoading,
error,
refetch,
isFetching,
} = useTokenBalances(address, isConnected);
// Prevent hydration mismatch - don't render until mounted
if (!mounted) {
return null;
}
// Not connected state
if (!isConnected) {
return (
// UI for wallet not connected state
);
}
return (
<div className="space-y-8">
<TokenList
tokens={tokens}
isLoading={isLoading}
error={error?.message}
showLowValueTokens={showLowValueTokens}
/>
</div>
);
}
```
<Tip>
Check out the other [Moralis API endpoints](https://docs.moralis.com/web3-data-api/evm/api-reference) and create visual components for the same!
</Tip>
## Conclusion
In this guide you learned how to use Moralis API to get wallet token balances and presenting them in a UI.
It is highly recommended you check out the other API endpoints and add more features to this project you created!
You can find a complete portfolio dashboard project [here](https://github.com/monad-developers/portfolio-dashboard-example) for inspiration.
## Useful links
* [Live portfolio app](https://portfolio-dashboard-example.vercel.app)
* [Moralis API reference](https://docs.moralis.com/web3-data-api/evm/api-reference)
* [Portfolio dashboard project](https://github.com/monad-developers/portfolio-dashboard-example)
* [Reown AppKit Docs](https://docs.reown.com/appkit/next/core/installation)
# How to connect a wallet to your app with Reown AppKit
Source: https://docs.monad.xyz/guides/reown
This guide shows you how to use [Reown AppKit](https://reown.com/appkit) to enable wallet connections and interact with the Monad network. AppKit provides seamless wallet connections, including email/social logins, smart accounts, one-click authentication, and wallet notifications.
For this tutorial, we'll be using Next.js, though you can use any other framework compatible
with AppKit.
<Note>
AppKit is available on eight frameworks, including React, Next.js, Vue, JavaScript, React
Native, Flutter, Android, iOS, and Unity.
</Note>
**What you'll learn:**
* Set up a new project using AppKit CLI
* Configure the project for Monad Testnet
* Connect wallets to your application
**Time to complete:** \~5 minutes
## Prerequisites
* Node.js installed on your system
## Step 1: Create a New Project
Run the AppKit CLI to create a new project configured with Reown AppKit:
```bash theme={null}
npx @reown/appkit-cli
```
When prompted, provide:
1. **Project Name**: Choose a name (e.g., `my-monad-appkit-app`)
2. **Framework**: Select `Next.js` (or your preferred framework)
3. **Blockchain Library**: Choose whether you want to install Wagmi, Ethers, Solana,
or Multichain (EVM + Solana). In this case, you need to either pick `Wagmi` or `Ethers` since
Monad is an EVM compatible blockchain. We will be choosing `Wagmi` for the sake of this
tutorial.
The CLI will create a minimal AppKit example with your selected configuration.
## Step 2: Set Up the Project
Navigate to your project directory and install dependencies:
```bash theme={null}
cd my-monad-appkit-app
npm install
```
<Note>
You can also use other package managers such as `yarn`, `bun`, `pnpm`, etc.
</Note>
## Step 3: Get Your Project ID
The example is pre-configured with a `projectId` that will only work on `localhost`. To fully configure your project, you will need to get a `projectId` from the [Reown Dashboard](https://dashboard.reown.com/?utm_source=monad\&utm_medium=docs\&utm_campaign=backlinks), as described below:
1. Go to [dashboard.reown.com](https://dashboard.reown.com/?utm_source=monad\&utm_medium=docs\&utm_campaign=backlinks) and sign in
2. Navigate to your team's Cloud Dashboard
3. Click "+ Project"
<img alt="Create Project" />
4. If prompted to choose a product type, select "AppKit" (otherwise ignore this step)
<img alt="Enter Project Name" />
5. Choose a project name
6. Click "Create"
<img alt="Select Framework" />
7. Copy the generated Project ID from the bottom of the page
<img alt="Project ID" />
## Step 4: Configure Environment Variables
Create a `.env` file in your project root:
```js title=".env" theme={null}
NEXT_PUBLIC_PROJECT_ID="YOUR_PROJECT_ID_HERE"
```
Replace `YOUR_PROJECT_ID_HERE` with the Project ID you copied in the previous step.
<Warning>
Environment variables starting with `NEXT_PUBLIC_` are exposed to the client. Only include non-sensitive configuration data.
</Warning>
## Step 5: Configure for Monad Testnet
Update `/src/config/index.ts` to use Monad Testnet:
```ts lines title="/src/config/index.ts" theme={null}
import { mainnet, monadTestnet } from '@reown/appkit/networks'
export const networks = [monadTestnet] as [AppKitNetwork, ...AppKitNetwork[]]
```
This configures your app to use Monad Testnet instead of the default networks.
## Step 6: Run Your Application
Start the development server:
```bash theme={null}
npm run dev
```
Your app will be available at `http://localhost:3000`.
<Note>
If you are using alternative package managers, you can try either of these commands - `yarn dev`, `pnpm dev`, or `bun dev`.
</Note>
## Conclusion
You have now learned how to create a simple app using AppKit CLI that allows users to connect their wallet and interact with Monad Testnet.
**Reown AppKit** is a powerful solution for developers looking to integrate wallet connections and other Web3 functionalities into their apps on any EVM chain. In just a few simple steps, you can provide your users with seamless wallet access, one-click authentication, social logins, and notifications—streamlining their experience while enabling advanced features like on-ramp functionality and smart accounts.
## What's Next?
* Explore the [Reown blog](https://reown.com/blog)
* Check out the complete example: [Reown AppKit EVM](https://github.com/rohit-710/reown-appkit-evm)
# How to build a basic dApp with Scaffold-ETH
Source: https://docs.monad.xyz/guides/scaffold-eth
In this guide, you will learn how to use Scaffold-ETH 2 to quickly build a new dapp project.
## Requirements
Before you begin, you need to install the following tools:
* Node (>= v18.18)
* Yarn (v1 or v2+)
* Git
### Get funds on Monad Testnet
You will need funds on Monad Testnet in order to deploy smart contracts, you can get funds from the [Monad Faucet](https://testnet.monad.xyz).
## Working with Scaffold-ETH
Scaffold-ETH can have two different solidity development frameworks: Foundry and Hardhat.
In this guide you can choose between Foundry and Hardhat.
<Tabs>
<Tab title="Foundry">
### Clone the scaffold-monad-foundry repo
```sh theme={null}
git clone https://github.com/monad-developers/scaffold-monad-foundry.git
```
### Open the project directory and install dependencies
```sh theme={null}
cd scaffold-monad-foundry && yarn install
```
### Start your local blockchain node
```sh theme={null}
yarn chain
```
### Deploy your smart contract to your local blockchain node
```sh theme={null}
yarn deploy
```
This command deploys `YourContract.sol` to your local blockchain node. The contract is located in `packages/foundry/contracts` and can be modified to suit your needs.
The `yarn deploy` command uses the deploy script located in `packages/foundry/deploy` to deploy the contract to the network. You can also customize the deploy script.
### Start your NextJS app
```sh theme={null}
yarn start
```
Visit your app on: `http://localhost:3000`.
You can interact with your smart contract using the Debug Contracts page. You can tweak the app config in `packages/nextjs/scaffold.config.ts`.
### Deploy your smart contract to Monad Testnet
```sh theme={null}
yarn deploy --network monadTestnet
```
This command deploys `YourContract.sol` to Monad Testnet. The contract is located in `packages/foundry/contracts` and can be modified to suit your needs.
### Verify your smart contract on Monad Testnet
```sh theme={null}
yarn verify --network monadTestnet
```
This command verifies `YourContract.sol` on Monad Testnet.
</Tab>
<Tab title="Hardhat">
### Clone the scaffold-monad-hardhat repo
```sh theme={null}
git clone https://github.com/monad-developers/scaffold-monad-hardhat.git
```
### Open the project directory and install dependencies
```sh theme={null}
cd scaffold-monad-hardhat && yarn install
```
### Start your local blockchain node
```sh theme={null}
yarn chain
```
### Deploy your smart contract to your local blockchain node
```sh theme={null}
yarn deploy
```
This command deploys `YourContract.sol` to your local blockchain node. The contract is located in `packages/hardhat/contracts` and can be modified to suit your needs.
The `yarn deploy` command uses the deploy script located in `packages/hardhat/deploy` to deploy the contract to the network. You can also customize the deploy script.
### Start your NextJS app
```sh theme={null}
yarn start
```
Visit your app on: `http://localhost:3000`.
You can interact with your smart contract using the Debug Contracts page. You can tweak the app config in `packages/nextjs/scaffold.config.ts`.
### Generate a deployer account
```sh theme={null}
yarn generate
```
This command will create a new deployer account. **Remember the password you create** as you'll need it for deployments.
### Deploy your smart contract to Monad Testnet
```sh theme={null}
yarn deploy --network monadTestnet
```
This command deploys `YourContract.sol` to Monad Testnet. The contract is located in `packages/hardhat/contracts` and can be modified to suit your needs.
### Verify your smart contract on Monad Testnet
```sh theme={null}
yarn verify --network monadTestnet
```
This command verifies `YourContract.sol` on Monad Testnet.
</Tab>
</Tabs>
## Next steps
* Explore the Debug Contr프로젝트로 돌아가기