Rainbow Kit:Web 3.0 世界的魔法鑰匙!
🌈 一鍵開啟加密貨幣之門
你是否曾經在加密貨幣世界的門口徘徊,卻因為「連接錢包」這一步被勸退?別擔心,Rainbow Kit 來拯救你了!這個工具就像是 Web3 界的 VIP 通行證,讓你用 最潮的方式 進入區塊鏈的神秘宇宙。🚀
🤔 什麼是 Rainbow Kit?
簡單來說,Rainbow Kit 就是 一個讓你的 DApp 可以輕鬆支援錢包連接的工具,它基於 wagmi(一個超讚的以太坊 React Hook 庫)打造,讓你用最少的代碼,實現最流暢的錢包體驗。
它就像一位貼心的管家,幫你處理各種加密錢包的連接邏輯,支援 MetaMask、WalletConnect、Coinbase Wallet 等等,無痛上手,連小白都能輕鬆駕馭!
🛠️ 開始你的 Rainbow 之旅
要開始使用 Rainbow Kit,當然要先安裝它:
pnpm add @rainbow-me/rainbowkit wagmi viem
然後,在你的 React 專案中配置它,就像召喚一個區塊鏈精靈:
'use client'
import type { ReactNode } from 'react'
import { ALCHEMY_API_KEY, WALLET_CONNECT_PROJECT_ID } from '@/configs/ethereum'
import { useLocale } from '@/hooks'
import { darkTheme, getDefaultConfig, lightTheme, RainbowKitProvider } from '@rainbow-me/rainbowkit'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useTheme } from 'next-themes'
import { http, WagmiProvider } from 'wagmi'
import { mainnet, sepolia } from 'wagmi/chains'
import '@rainbow-me/rainbowkit/styles.css'
interface Props {
children: ReactNode
}
const Web3Provider = (props: Props) => {
// ** Props
const { children } = props
// ** Hooks
const { t, currentLocale } = useLocale()
const { resolvedTheme } = useTheme()
// ** Vars
const wagmiConfig = getDefaultConfig({
appName: t('website.title'),
projectId: WALLET_CONNECT_PROJECT_ID,
chains: [mainnet, sepolia],
transports: {
[mainnet.id]: http(`https://eth-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}`),
[sepolia.id]: http(`https://eth-sepolia.g.alchemy.com/v2/${ALCHEMY_API_KEY}`),
},
ssr: true,
})
const queryClient = new QueryClient()
const rainbowLocale = currentLocale === 'en' ? 'en-US' : 'zh-TW'
const rainbowTheme = resolvedTheme === 'dark' ? darkTheme() : lightTheme()
return (
<WagmiProvider config={wagmiConfig}>
<QueryClientProvider client={queryClient}>
<RainbowKitProvider locale={rainbowLocale} theme={rainbowTheme}>
{children}
</RainbowKitProvider>
</QueryClientProvider>
</WagmiProvider>
)
}
export default Web3Provider
現在,你的 DApp 已經準備好迎接世界各地的錢包玩家啦! 🎉
🏆 一鍵連接,暢遊 Web3
當然,沒有連接按鈕,怎麼讓使用者體驗「秒進 Web3」的快感呢? 加上這行代碼,讓你的 DApp 一秒變成 Web3 大門:
import { ConnectButton } from "@rainbow-me/rainbowkit";
export default function HomePage() {
return (
<div>
<h1>歡迎來到 Web3 世界!</h1>
<ConnectButton />
</div>
);
}
按下按鈕,哇!你的錢包已經連上去啦! 就像 Tinder 配對成功一樣,只是這次連的是區塊鏈,而不是心碎 💔😂
🎨 客製化你的 Web3 體驗
Rainbow Kit 不僅好用,還超美!你可以自由 更改主題、按鈕樣式、動畫效果,讓你的 DApp 成為 Web3 界的「顏值擔當」。
比如說,你可以這樣自定義主題:
import { darkTheme } from "@rainbow-me/rainbowkit";
<RainbowKitProvider theme={darkTheme()}>
讓你的 DApp 瞬間變身成暗黑系潮流大師!🖤
也能依照你的 UI 框架變換樣式,例如使用:Tailwind CSS + Shadcn/ui:
...
<ConnectButton.Custom>
{({ account, chain, openAccountModal, openChainModal, openConnectModal, authenticationStatus, mounted }) => {
// Note: If your app doesn't use authentication, you
// can remove all 'authenticationStatus' checks
const ready = mounted && authenticationStatus !== 'loading'
const connected
= ready && account && chain && (!authenticationStatus || authenticationStatus === 'authenticated')
return (
<div
{...(!ready && {
'aria-hidden': true,
style: {
opacity: 0,
pointerEvents: 'none',
userSelect: 'none',
},
})}
>
{(() => {
if (!connected) {
return (
<MotionButton
onClick={openConnectModal}
variant="outline"
className="h-8 rounded-md text-sm font-medium shadow border-none"
animate={{ backgroundPosition: ['0% 50%', '100% 50%', '0% 50%'] }}
transition={{ duration: 2, repeat: Infinity, ease: 'linear' }}
style={{
backgroundSize: '200% 100%',
backgroundImage: 'linear-gradient(to right, #3b82f6, #8b5cf6, #ec4899)',
}}
>
<Wallet className="h-4 w-4 text-white sm:mr-2" />
<span className="text-white hidden sm:inline">{t('web3.connectWallet')}</span>
</MotionButton>
)
}
if (chain.unsupported) {
return (
<Button onClick={openChainModal} variant="destructive" className="h-8">
{t('web3.wrongNetwork')}
</Button>
)
}
return (
<DropdownMenu>
<DropdownMenuTrigger asChild className="flex items-center">
<button className="relative p-0 border-0 bg-transparent">
<Avatar className="h-8 w-8 cursor-pointer border border-1 border-foreground">
<AvatarImage src={`https://effigy.im/a/${account.address}.svg`} alt="Wallet Avatar" />
<AvatarFallback>{account.displayName.substring(0, 2).toUpperCase()}</AvatarFallback>
</Avatar>
<span className="absolute bottom-0.25 right-0.25 block h-2 w-2 rounded-full bg-green-500 ring-2 ring-foreground"></span>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
{chain && (
<DropdownMenuLabel className="flex justify-between items-center gap-3">
<p className="text-xs font-medium text-muted-foreground">{t('web3.myWallet')}</p>
<div className="flex items-center">
{chain.hasIcon && (
<div
className="mr-1.5 h-2 w-2 overflow-hidden rounded-full"
style={{
background: chain.iconBackground,
}}
>
{chain.iconUrl && (
<img alt={chain.name ?? 'Chain icon'} src={chain.iconUrl} className="h-full w-full" />
)}
</div>
)}
<p className="text-xs font-medium">{chain.name}</p>
</div>
</DropdownMenuLabel>
)}
<DropdownMenuItem className="flex items-center gap-3 cursor-pointer" onClick={openAccountModal}>
<div className="flex flex-grow items-center gap-2">
<Avatar className="h-7 w-7 border border-1 border-foreground">
<AvatarImage src={`https://effigy.im/a/${account.address}.svg`} alt="Wallet Avatar" />
<AvatarFallback>{account.displayName.substring(0, 2).toUpperCase()}</AvatarFallback>
</Avatar>
<div className="flex flex-col items-start text-left">
<p className="text-xs font-medium">{account.displayName}</p>
<p className="text-xs text-muted-foreground">{account.displayBalance}</p>
</div>
</div>
<Wallet className="mr-2 h-4 w-4" />
</DropdownMenuItem>
<DropdownMenuItem onClick={openChainModal} className="cursor-pointer">
<RefreshCw className="mr-2 h-4 w-4" />
<span>{t('web3.switchNetwork')}</span>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={handleDisconnectWallet} className="cursor-pointer focus:text-red-600">
<LogOut className="mr-2 h-4 w-4" />
<span>{t('web3.disconnectWallet')}</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
})()}
</div>
)
}}
</ConnectButton.Custom>
...
⛽ 與鏈上資訊交互,查詢當前 Gas 費用
Web3 世界裡,手續費(Gas Fee)就像計程車跳表,價格隨時變動。如果你不想在錯誤的時間按下交易按鈕,被高額 Gas 費榨乾錢包,那就來 查詢當前 Gas 費 吧!
幸好,wagmi
讓這件事變得超簡單:
import { useEstimateFeesPerGas } from "wagmi";
export default function GasFeeChecker() {
const { data, isLoading } = useEstimateFeesPerGas();
if (isLoading) return <p>正在計算你的通行費...🛣️</p>;
return (
<div>
<h2>當前以太坊 Gas 費</h2>
<p>基礎費用: {data?.formatted?.gasPrice} Gwei</p>
<p>最快速度費用: {data?.formatted?.maxFeePerGas} Gwei</p>
</div>
);
}
現在,你可以在 DApp 介面上即時顯示 Gas 費用,再也不怕衝動交易,付出天價手續費! 💸
🔥 結論
透過 Rainbow Kit,你不需要手寫一堆麻煩的錢包連接邏輯,一行代碼搞定 Web3 錢包連線,讓你專注於打造更厲害的 DApp!
🌈 現在就用 Rainbow Kit,把你的 Web3 旅程點亮吧!🚀