bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 54쪽 중 25쪽
oat(formatEther(result)).toFixed(3);
setBalance(formatted);
} catch (err) {
console.error('Failed to fetch balance:', err);
}
};
const sendSTT = async () => {
if (!walletAddress) return;
console.log(walletAddress);
const txn = {
to: '0xb6e4fa6ff2873480590c68D9Aa991e5BB14Dbf03',
value: 1000000000000000,
chainId: 50312,
};
try {
const tx = await sendTransaction(txn, { address: walletAddress });
console.log('TX Sent:', tx);
if (walletAddress) fetchBalance(walletAddress);
} catch (err) {
console.error('TXN Failed:', err);
}
};
return (
<div className='grid min-h-screen items-center justify-items-center p-8 sm:p-20'>
<main className='flex flex-col gap-6 row-start-2 items-center'>
{!ready ? (
<p>Loading...</p>
) : !authenticated ? (
<>
<button
onClick={startCrossAppLogin}
className='bg-purple-600 text-white px-4 py-2 rounded'
>
Login with Global Wallet
</button>
{loginError && <p className='text-red-500 text-sm'>{loginError}</p>}
</>
) : hydrated ? (
<div className='space-y-4 text-center'>
{walletAddress ? (
<p>Connected as: {walletAddress}</p>
) : (
<p className='text-gray-600'>No wallet address found.</p>
)}
<p>Balance: {balance ? `${balance} STT` : 'Loading...'} </p>
<button
onClick={sendSTT}
className='bg-blue-600 text-white px-4 py-2 rounded'
>
Send 0.001 STT
</button>
<button
onClick={logout}
className='bg-red-600 text-white px-4 py-2 rounded'
>
Logout
</button>
</div>
) : (
<p>🔄 Logging in... Please wait</p>
)}
</main>
</div>
);
}
```
</details>
By using Privy Global Wallet on the Somnia Testnet, developers can offer a seamless onboarding and wallet experience. This setup is ideal for onboarding Web2 users into Web3 with embedded wallets, abstracting away traditional wallet complexities.
<br>
# Authenticating with RainbowKit
In this guide, we'll integrate [RainbowKit](https://www.rainbowkit.com/docs/introduction) with the Somnia Network in a Next.js application. This will enable users to connect their wallets seamlessly, facilitating interactions with the Somnia blockchain.
## Prerequisites
Before we begin, ensure you have the following:
1. This guide is not an introduction to JavaScript Programming; you are expected to understand JavaScript.
2. To complete this guide, you will need MetaMask installed and the Somnia DevNet added to the list of Networks. If you have yet to install MetaMask, please follow this guide to [Connect Your Wallet guide](/get-started/connect-your-wallet-to-mainnet).
3. Familiarity with React and Next.js is assumed.
## Create the Next.js Project
Open your terminal and run the following commands to set up a new Next.js project:
```bash
npx create-next-app@latest somnia-rainbowkit
cd somnia-rainbowkit
```
Install the required Dependencies, which are **`wagmi`**, **`viem`**, @tanstack/react-query, and rainbowkit. Run the following command:
```bash
npm install wagmi viem @tanstack/react-query rainbowkit
```
### Set Up Providers in Next.js
We'll set up several providers to manage the application's state and facilitate interactions with the blockchain.
\
Create a **`components`** directory in the app folder. Inside the components directory, create a file named **`ClientProvider.tsx`** with the following content:
```typescript
'use client';
import { WagmiProvider } from "wagmi";
import {
RainbowKitProvider,
getDefaultConfig,
} from "@rainbow-me/rainbowkit";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { somniaTestnet } from "viem/chains";
const queryClient = new QueryClient();
const config = getDefaultConfig({
appName: "Somnia Example App",
projectId: "Get_WalletConnect_ID",
chains: [somniaTestnet],
ssr: true,
});
export default function ClientProvider({ children }) {
return (
<WagmiConfig config={config}>
<QueryClientProvider client={queryClient}>
<RainbowkitProvider>{children}</RainbowkitProvider>
</QueryClientProvider>
</WagmiConfig>
);
}
```
> Every Rainbowkit dApp relies on **WalletConnect** and needs to obtain a **`projectId`** from WalletConnect Cloud. Get one [here](https://cloud.walletconnect.com/).
In the app directory, locate the **`layout.tsx`** file and update it as follows:
```typescript
import ClientProvider from './components/ClientProvider';
export default function RootLayout({ children }) {
return (
<html lang="en">
<head>
<title>Somnia DApp</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<ClientProvider>{children}</ClientProvider>
</body>
</html>
);
}
```
### Build the Home Page
We'll create a simple home page that allows users to connect their wallets and displays their address upon connection.
In the app directory, locate the **`page.tsx`** file and update it as follows:
```typescript
'use client';
import { useAccount } from 'wagmi';
import { ConnectButton } from "@rainbow-me/rainbowkit";
export default function Home() {
const { address, isConnected } = useAccount();
return (
<div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
<main className="flex flex-col gap-8 row-start-2 items-center sm:items-start">
<ConnectButton />
{isConnected && (
<p className="mt-4 text-lg text-blue-600">Connected as: {address}</p>
)}
</main>
</div>
);
}
```
### Run the Application
Start the Development Server by running the following command:
```bash
npm run dev
```
Open your browser and navigate to <http://localhost:3000>. You should see the RainbowKit button, allowing users to connect their wallets to the Somnia network.
## Conclusion
You've successfully integrated RainbowKit with the Somnia Network in a Next.js application. This setup provides a foundation for building decentralized applications on Somnia, enabling seamless wallet connections and interactions with the Somnia Network.
For further exploration, consider adding features such as interacting with smart contracts, displaying user balances, or implementing transaction functionalities.
If you encounter any issues or need assistance, join the[ Somnia Developer Discord](https://discord.gg/somnia).
<br>
# OnRamps
OnRamps make it easy for users to move from the traditional financial system into the Somnia ecosystem by purchasing tokens directly with their local currency.
This section covers how to integrate **Banxa**, Somnia’s trusted onramping service, to enable seamless and secure fiat-to-crypto transactions within your dApps.
You’ll learn how to:
* Embed Banxa’s checkout flow in your application
* Support multiple payment methods (credit/debit card, bank transfer, etc.)
* Customize the onramp experience to match your app’s branding
* Streamline user onboarding with a direct path from fiat to onchain activity
> Banxa provides developers and users with a regulated, global, and developer-friendly solution for accessing the Somnia network — making your application more inclusive and easier to adopt.
# Buy SOMI Using Banxa Checkout
You can easily buy SOMI tokens using Banxa, a trusted fiat to crypto gateway partner.\
This guide walks you through purchasing SOMI directly from the[ Banxa Checkout Portal](https://checkout.banxa.com/).
***
Banxa lets you buy cryptocurrency with local payment methods, including credit/debit cards, bank transfers, and mobile wallets.\
In this guide, you’ll learn how to:
* Access the Banxa checkout page
* Select SOMI as the token to purchase
* Complete payment securely
* Receive SOMI in your wallet
***
## Prerequisites
Before you start, ensure you have:
* Your wallet address handy, this is where SOMI will be sent.
* A valid payment method supported in your region (Visa, Mastercard, bank transfer, etc.).
***
## Step 1 — Visit the Banxa Checkout Page
Go to[ https://checkout.banxa.com/](https://checkout.banxa.com/).\
You’ll see a simple interface to select your fiat currency and cryptocurrency.
***
<figure><img src="https://2122549367-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FkYErT9t3BJtpPfejLO6I%2Fuploads%2F4GN5jwQT79DWFamE30Pp%2Fimage.png?alt=media&token=cdcdd31d-2c9e-485f-8ae4-50bacf20599f" alt="" width="375"><figcaption></figcaption></figure>
## Step 2 — Choose Your Purchase Options
* In the “You Pay” field, enter how much fiat (e.g. USD, EUR, NGN) you want to spend.
* In the “You Get” field, select SOMI as the token.
* Select the network as Somnia Network.
Banxa will automatically show the conversion rate, fees, and delivery estimate.
***
## Step 3 — Enter Your Wallet Address
Copy your wallet address from your Somnia-compatible wallet (e.g. MetaMask) and paste it into the “Wallet Address” field.
{% hint style="danger" %}
***Triple check the address before proceeding. Funds sent to the wrong address cannot be recovered.***
{% endhint %}
***
## Step 4 — Complete KYC Verification
Banxa complies with international regulations and may ask you to verify your identity.\
Typical verification steps include:
* Uploading a government-issued ID
* Taking a selfie
* Confirming your billing address
This process only needs to be done once per account.
<div align="center"><img src="https://2122549367-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FkYErT9t3BJtpPfejLO6I%2Fuploads%2FDlOUu0Y1ZUpGRRDcbS5f%2FBanxa-2.png?alt=media&token=8cc99731-c962-4ffa-b8ed-4d2e101c42ff" alt=""></div>
***
## Step 5 — Select a Payment Method
Choose one of the available payment options for your country:
* Credit/Debit Card
* Bank Transfer
* Apple Pay / Google Pay (where supported)
Follow the on-screen instructions to complete the payment.
***
## Step 6 — Receive SOMI in Your Wallet
Once payment is confirmed:
* Banxa will process the transaction.
* SOMI tokens will be sent directly to your wallet on the Somnia Network.
* You’ll receive a confirmation email once the transfer is complete.
This may take a few minutes, depending on network congestion and payment method.
***
## Need Help?
If your transaction is delayed or you need assistance, you can contact:
* Banxa Support:[ support.banxa.com](https://support.banxa.com/)
* Somnia Community:[ Discord → #support](https://discord.gg/somnia)
***
## Disclaimers
* Banxa is a third party provider. Always ensure you are using the official[ checkout.banxa.com](https://checkout.banxa.com/) link.
* Transaction fees, limits, and verification steps vary by country and payment method.
* SOMI purchases are non reversible once processed.
<br>
# Cross-chain Swaps and Bridging
Most users don't start their journey on Somnia, their assets live on Ethereum, Arbitrum, Base, Solana, and dozens of other chains. To grow your dApp, you need a smooth way to move that liquidity **into, out of, and across** the Somnia ecosystem.
There are two ways to bring assets across, depending on who is doing the work:
* **For end users (no code):** Somnia's official bridge partners, [**Relay**](https://relay.link/bridge) and [**Stargate Finance**](https://stargate.finance/), let anyone bridge assets through their own interfaces. If you just need users to move funds and don't want to build any UI, point them to the [Bridging Info](/get-started/bridging-info) guide.
* **For developers (this section):** embed swaps and bridging **directly inside your dApp** with the [**LI.FI**](https://li.fi/) **SDK**, so users never have to leave your app.
***
## Why LI.FI for in-app bridging
LI.FI is the routing and execution layer for cross-chain liquidity. A single integration aggregates dozens of bridges and DEX aggregators across 50+ chains **(including Somnia's official partners Relay and Stargate)** normalises token standards, picks the optimal route, and monitors execution for you.
In other words, integrating LI.FI doesn't replace Relay or Stargate, it routes *through* them (and many others) and chooses the best option per transfer. A live USDC transfer from Arbitrum to Somnia, for example, is currently routed via Stargate under the hood.
LI.FI is **infrastructure.** It does the routing and execution, while *you* own the user experience. (The same way [Jumper Exchange](https://jumper.exchange/) is LI.FI's own front-end, your dApp becomes its own bridge/swap interface.)
You'll learn how to:
* [Add cross-chain and same-chain swaps directly inside your Somnia dApp with the **LI.FI SDK**](/developer/building-dapps/cross-chain-swaps-and-bridging/integrating-the-li.fi-sdk)
* Let users **bridge assets to and from Somnia** in your own UI
* Request **routes and quotes**, execute them, and **track transaction status** in-app
* Query supported **chains, tokens, bridges, and exchanges** programmatically
***
## Choosing an integration path
LI.FI offers several integration surfaces. This section focuses on the **SDK**, which gives you full programmatic control over the route lifecycle.
| Path | Best for | Effort |
| --------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | ------ |
| **SDK** (`@lifi/sdk`) | Custom swap/bridge flows where you build the UI and control every step | Medium |
| Widget (`@lifi/widget`) | Dropping a ready-made, themeable swap/bridge UI into a React app | Low |
| REST API (`li.quest/v1`) | Backend services, bots, and AI agents that construct requests directly | Medium |
| Bridge UIs ([Relay](https://relay.link/bridge) / [Stargate](https://stargate.finance/)) | End users moving funds manually — no integration needed | None |
> Whichever path you choose, LI.FI's official documentation is the source of truth for the latest implementation details: [https://docs.li.fi](https://docs.li.fi/).
{% hint style="info" %}
**Somnia at a glance** — when configuring LI.FI for Somnia, use Chain ID **`5031`**, native currency **SOMI** (18 decimals), RPC `https://api.infra.mainnet.somnia.network/`. Always confirm live route and token support with the LI.FI API before going to production (see the SDK guide).
{% endhint %}
# Integrating the LI.FI SDK
The [**LI.FI**](https://li.fi/) **SDK** lets you add cross-chain and same-chain swaps and bridging directly inside your Somnia dApp. Instead of redirecting users to an external bridge, you request a route, execute it, and track its status. All from your own interface.
Under the hood, LI.FI aggregates dozens of bridges and DEX aggregators across 50+ chains, normalises token standards, and picks the optimal route. Your dApp only talks to one SDK.
In this guide, you'll learn how to:
* Install and configure the LI.FI SDK for Somnia
* Request a quote to **bridge assets into Somnia**
* Execute the route and **track its status** in your app
* Query supported **chains, tokens, and tools** to keep your UI accurate
{% hint style="info" %}
The LI.FI SDK is a JavaScript/TypeScript toolkit that runs in both front-end and back-end environments. This guide shows the front-end (browser wallet) flow. For the full API surface and the latest details, always refer to the official docs: <https://docs.li.fi/sdk/overview>.
{% endhint %}
## Prerequisites
Before you start, ensure you have:
* A working JavaScript/TypeScript dApp (React or Next.js recommended). This guide assumes familiarity with both.
* Wallet connection already set up. If not, see [Wallet Integration and Auth](/developer/building-dapps/wallet-integration-and-auth).
* [Node.js](https://nodejs.org/) 18+ and a package manager (npm, pnpm, or yarn).
* The Somnia network details on hand:
| Property | Value |
| --------------- | ------------------------------------------- |
| Chain ID | `5031` |
| Native currency | SOMI (18 decimals) |
| RPC URL | `https://api.infra.mainnet.somnia.network/` |
| Explorer | `https://explorer.somnia.network` |
## Step 1: Install the SDK
The SDK uses [Viem](https://viem.sh/) under the hood, so install it alongside.
```bash
npm install @lifi/sdk viem
```
{% hint style="info" %}
This guide was written and verified against `@lifi/sdk` v3.16.x and `viem` v2.x. API surfaces evolve — if a signature differs in your version, the [official SDK docs](https://docs.li.fi/sdk/overview) are the source of truth.
{% endhint %}
## Step 2: Configure the SDK
Call `createConfig` once when your app boots. The `integrator` string identifies your app to LI.FI (and is used for fee monetisation later).
Because Somnia may not ship in Viem's default chain list, define it explicitly with `defineChain` so the SDK's wallet provider can switch to it.
{% code title="lib/lifi.ts" %}
```typescript
import { createConfig, EVM, ChainId } from '@lifi/sdk';
import { createWalletClient, custom, defineChain } from 'viem';
import { mainnet, arbitrum, optimism, base } from 'viem/chains';
import { switchChain } from 'viem/actions';
// Somnia may be newer than the ChainId enum in your installed SDK version,
// so cast the numeric id where the SDK's TypeScript types expect a ChainId.
const SOMNIA = 5031 as ChainId;
// Define Somnia Mainnet for Viem
export const somnia = defineChain({
id: 5031,
name: 'Somnia',
nativeCurrency: { name: 'Somnia', symbol: 'SOMI', decimals: 18 },
rpcUrls: {
default: { http: ['https://api.infra.mainnet.somnia.network/'] },
},
blockExplorers: {
default: { name: 'Somnia Explorer', url: 'https://explorer.somnia.network' },
},
});
// Chains your dApp will let users move assets between
const chains = [mainnet, arbitrum, optimism, base, somnia];
// A Viem wallet client backed by the user's injected wallet (e.g. MetaMask)
const walletClient = createWalletClient({
chain: mainnet,
transport: custom(window.ethereum!),
});
createConfig({
integrator: 'YourSomniaDApp', // required; max 23 chars (letters, numbers, . - _)
rpcUrls: {
[SOMNIA]: ['https://api.infra.mainnet.somnia.network/'], // let the SDK use Somnia's RPC
},
providers: [
EVM({
getWalletClient: async () => walletClient,
switchChain: async (chainId) => {
await switchChain(walletClient, { id: chainId });
return walletClient;
},
}),
],
});
```
{% endcode %}
{% hint style="success" %}
The SDK automatically fetches chain, bridge, and token metadata from LI.FI at runtime — you don't have to hard-code bridge addresses. The `defineChain` block is only needed so the wallet can **switch networks** during execution, and `rpcUrls` lets the SDK use your preferred Somnia endpoint. For production, pass an authenticated RPC URL rather than a public one.
{% endhint %}
{% hint style="warning" %}
**TypeScript note:** the SDK's types use a `ChainId` enum for parameters like `rpcUrls` keys and `getTokens({ chains })`. If your installed SDK version predates Somnia's addition to that enum, the raw number `5031` will fail to type-check — cast it with `5031 as ChainId` (shown above). The runtime value is unaffected; this is purely a type-level workaround. `getQuote`'s `fromChain` / `toChain` accept a plain `number` and need no cast.
{% endhint %}
## Step 3: Request a quote
A **quote** is a single, ready-to-execute route with the optimal pricing LI.FI could find. The example below bridges **USDC on Arbitrum → USDC.e on Somnia** (routed via Stargate at the time of writing).
Amounts are always passed as strings in the token's **smallest unit** (USDC has 6 decimals, so `10` USDC = `"10000000"`). A chain's native token is represented by the zero address.
{% code title="Bridge USDC (Arbitrum) → USDC.e (Somnia)" %}
```typescript
import { getQuote } from '@lifi/sdk';
const quote = await getQuote({
fromChain: 42161, // Arbitrum
toChain: 5031, // Somnia
fromToken: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831', // USDC on Arbitrum
toToken: '0x28BEc7E30E6faee657a03e19Bf1128AaD7632A00', // USDC.e (bridged USDC) on Somnia
fromAmount: '10000000', // 10 USDC (6 decimals)
fromAddress: userWalletAddress, // the connected wallet
});
console.log(quote.estimate.toAmount); // estimated USDC.e received (6 decimals)
```
{% endcode %}
### Tokens routable to S프로젝트로 돌아가기