miniwallet
v0.1.19
Published
React wallet connect button with multi-wallet support via EIP-6963
Downloads
3,006
Maintainers
Readme
MiniWallet
React 钱包连接按钮组件:一键连接浏览器扩展钱包,展示账户、余额,并支持切换网络。
功能
- 连接 / 断开钱包
- 展示地址、余额、当前网络
- 切换网络(Ethereum / Sepolia / Polygon,可自定义)
- 多钱包支持(EIP-6963 发现):MetaMask、OKX、Phantom、Coinbase
- 刷新后自动恢复上次连接(
localStorage+eth_accounts)
安装
pnpm add miniwallet或使用其他包管理工具:
npm install miniwallet
# 或
yarn add miniwallet快速开始
本地 Demo
pnpm install
pnpm dev在项目中使用
用 MiniWalletProvider 包裹应用,再放置 MiniWalletButton:
import { MiniWalletProvider, MiniWalletButton } from "miniwallet"
function App() {
return (
<MiniWalletProvider>
<MiniWalletButton label="Connect Wallet" />
</MiniWalletProvider>
)
}自定义支持的链(可选,不传则使用内置默认链):
<MiniWalletProvider
chains={[
{ id: 1, name: "Ethereum", symbol: "ETH", decimals: 18 },
{ id: 137, name: "Polygon", symbol: "MATIC", decimals: 18 },
]}
>
<MiniWalletButton />
</MiniWalletProvider>使用 Hook
需要自定义 UI 时,可直接使用 useMiniWallet(必须在 MiniWalletProvider 内):
import { useMiniWallet } from "miniwallet"
function CustomWalletUI() {
const {
account,
balance,
isConnected,
selectedChain,
wallet,
chains,
connect,
disconnect,
switchChain,
} = useMiniWallet()
// 自定义渲染...
}API
MiniWalletProvider
| Prop | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| children | ReactNode | — | 子节点 |
| chains | ChainConfig[] | 内置默认链 | 可选网络列表 |
MiniWalletButton
| Prop | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| label | string \| null | "Connect Wallet" | 未连接时按钮文案 |
useMiniWallet() 返回值
| 字段 | 类型 | 说明 |
|------|------|------|
| account | string | 当前账户地址 |
| balance | string | 格式化后的余额 |
| isConnected | boolean | 是否已连接 |
| selectedChain | ChainConfig \| null | 当前网络 |
| wallet | WalletProvider \| undefined | 当前钱包信息 |
| chains | ChainConfig[] | 可用网络列表 |
| connect | (wallet) => Promise<void> | 连接指定钱包 |
| disconnect | () => Promise<void> | 断开连接 |
| switchChain | (chain) => Promise<void> | 切换网络 |
类型
type ChainConfig = {
id: number // 链 ID,如 1、11155111、137
name: string
symbol: string
decimals: number
}
type WalletProvider = {
id: string
name: string
icon: string
}支持的钱包
| 钱包 | EIP-6963 rdns |
|------|----------------|
| MetaMask | io.metamask |
| OKX | com.okex.wallet(旧品牌okex问题,兼容 com.okx.wallet) |
| Phantom | app.phantom |
| Coinbase | com.coinbase.wallet |
需安装对应浏览器扩展;未检测到时会提示「请安装钱包」。
默认网络
| 网络 | id | symbol |
|------|-----|--------|
| Ethereum | 1 | ETH |
| Sepolia | 11155111 | SepoliaETH |
| Polygon | 137 | MATIC |
项目结构
src/
MiniWalletProvider.tsx # Context + 连接 / 切链 / 余额 / 自动恢复
MiniWalletButton.tsx # 连接按钮 UI
useMiniWallet.ts # Hook
constants.ts # 钱包列表、默认链、rdns 映射
types.ts # 类型
utils/formatUnits.ts # wei → 可读余额
icons/ # 钱包与断开图标
dev/ # 本地 Demo(不随包发布)说明
- 钱包发现基于 EIP-6963,避免多扩展抢占
window.ethereum。 - 主动连接使用
eth_requestAccounts;刷新恢复使用eth_accounts(不弹窗)。 - 上次连接的钱包 id 保存在
localStorage的miniwallet:lastWalletId。
