Wagmi
连接钱包
连接或断开用户的钱包。该函数根据当前连接状态自动处理连接和断开连接。
参数
interface ConnectParams {
connector: Connector; // 钱包连接器,如 injected/metamask/walletConnect 等
}
interface DisconnectParams {
// 断开连接无需参数
}
返回值
interface ConnectResult {
account: string; // 已连接的钱包地址
chainId: number; // 当前链 ID
connector: Connector; // 使用的钱包连接器
}
interface DisconnectResult {
// 断开连接确认
}
@wagmi/actions
纯 JS 调用方式,适用于非 React 场景或直接调用:
// 完整可运行组件代码:
import { useState, useEffect } from 'react'
import { connect, disconnect, getAccount } from 'wagmi/actions'
import { injected } from 'wagmi/connectors'
import { Button } from 'antd'
import ReactJsonView from 'react-json-view'
import { http, createConfig } from 'wagmi'
import { mainnet, sepolia } from 'wagmi/chains'
const config = createConfig({
chains: [mainnet, sepolia],
transports: {
[mainnet.id]: http(),
[sepolia.id]: http(),
},
})
export function Connect() {
const [res, setRes] = useState({})
const [isConnected, setIsConnected] = useState(false)
const [address, setAddress] = useState('')
const [error, setError] = useState('')
const [isLoading, setIsLoading] = useState(false)
useEffect(() => {
const acc = getAccount(config)
setIsConnected(acc.isConnected)
setAddress(acc.address || '')
}, [res])
async function handleConnect() {
setError('')
setIsLoading(true)
try {
const result = await connect(config, { connector: injected() })
setRes(result)
} catch(e) {
setError(e?.message || String(e))
setRes({})
} finally {
setIsLoading(false)
}
}
async function handleDisconnect() {
setError('')
setIsLoading(true)
try {
const result = await disconnect(config)
setRes(result)
} catch(e) {
setError(e?.message || String(e))
setRes({})
} finally {
setIsLoading(false)
}
}
const handleClick = () => {
if (isConnected) {
handleDisconnect()
} else {
handleConnect()
}
}
return (
<div>
<div style={{ marginBottom: 8 }}>
当前状态: {isConnected ? '已连接' : '未连接'}
</div>
<Button
type={isConnected ? 'default' : 'primary'}
style={{ margin: '12px 0' }}
loading={isLoading}
onClick={handleClick}
>
{isLoading ? (isConnected ? '断开连接中...' : '连接中...') : isConnected ? '断开连接' : '连接钱包'}
</Button>
{isConnected && address && (
<div style={{ fontSize: 14, color: '#555', wordBreak: 'break-all', background: '#f7f7f7', borderRadius: 6, padding: 10, textAlign: 'center', marginBottom: 12 }}>
<div style={{ marginBottom: 4 }}>地址:</div>
<div style={{ fontFamily: 'monospace', fontSize: 15 }}>{address}</div>
</div>
)}
<ReactJsonView src={res} theme='monokai' />
{error && <div style={{ color: 'red' }}>{error}</div>}
</div>
)
}
Connect Wallet
Current Status: Disconnected
签名消息
签名个人消息
为个人身份验证签名任意消息,通常用于登录、身份验证等场景。
参数
interface SignPersonalMessageParams {
message: string; // 要签名的消息内容
}
返回值
interface SignPersonalMessageResult {
signature: string; // 签名结果
}
@wagmi/actions
纯 JS 调用方式,适用于非 React 场景或直接调用:
// 完整可运行组件代码:
import { useState } from 'react'
import { signMessage, getAccount } from 'wagmi/actions'
import { Button, Input } from 'antd'
import ReactJsonView from 'react-json-view'
import { http, createConfig } from 'wagmi'
import { mainnet, sepolia } from 'wagmi/chains'
const config = createConfig({
chains: [mainnet, sepolia],
transports: {
[mainnet.id]: http(),
[sepolia.id]: http(),
},
})
export function SignPersonalMessage() {
const [res, setRes] = useState({})
const [message, setMessage] = useState('hello bitget wallet')
const [isConnected, setIsConnected] = useState(false)
const [error, setError] = useState('')
// 可选:在签名前检查连接状态
React.useEffect(() => {
const acc = getAccount(config)
setIsConnected(acc.isConnected)
}, [res])
async function run() {
setError('')
try {
const result = await signMessage(config, { message })
setRes({ signature: result })
} catch(e) {
setError(e?.message || String(e))
setRes({})
}
}
return (
<div>
<div style={{ marginBottom: 8 }}>
当前状态: {isConnected ? '已连接' : '未连接'}
</div>
<Input style={{ width: 300, marginRight: 8 }} value={message} onChange={e => setMessage(e.target.value)} />
<Button style={{ margin: '12px 0' }} onClick={run}>签名个人消息</Button>
<ReactJsonView src={res} theme='monokai' />
{error && <div style={{ color: 'red' }}>{error}</div>}
</div>
)
}
Sign Personal Message
签名类型化数据
签名结构化数据(EIP-712),适用于合约交互、链上授权等高级场景。
参数
interface SignTypedDataParams {
domain: object; // EIP-712 域信息
types: object; // EIP-712 类型定义
primaryType: string; // 主要类型
message: object; // 要签名的数据
}
返回值
interface SignTypedDataResult {
signature: string; // 签名结果
}
@wagmi/actions
Pure JS calling approach, suitable for non-React scenarios or direct calls:
// Complete runnable component code:
import { useState } from 'react'
import { signTypedData, getAccount } from 'wagmi/actions'
import { Button } from 'antd'
import ReactJsonView from 'react-json-view'
import { http, createConfig } from 'wagmi'
import { mainnet, sepolia } from 'wagmi/chains'
const config = createConfig({
chains: [mainnet, sepolia],
transports: {
[mainnet.id]: http(),
[sepolia.id]: http(),
},
})
export function SignTypedData() {
const [res, setRes] = useState({})
const [isConnected, setIsConnected] = useState(false)
const [error, setError] = useState('')
// 可选:在签名前检查连接状态
React.useEffect(() => {
const acc = getAccount(config)
setIsConnected(acc.isConnected)
}, [res])
const domain = {
name: 'MyDApp',
version: '1',
chainId: 1,
verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC',
}
const types = {
Person: [
{ name: 'name', type: 'string' },
{ name: 'wallet', type: 'address' },
],
Mail: [
{ name: 'from', type: 'Person' },
{ name: 'to', type: 'Person' },
{ name: 'contents', type: 'string' },
],
}
const message = {
from: {
name: 'Alice',
wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826',
},
to: {
name: 'Bob',
wallet: '0xAaaAaAaaAaAaAaaAaAaAaaAaAaAaAaAaAaAaAaAa',
},
contents: 'Hello Bob!',
}
async function run() {
setError('')
try {
const result = await signTypedData(config, {
domain,
types,
primaryType: 'Mail',
message,
})
setRes({ signature: result })
} catch(e) {
setError(e?.message || String(e))
setRes({})
}
}
return (
<div>
<div style={{ marginBottom: 8 }}>
当前状态: {isConnected ? '已连接' : '未连接'}
</div>
<Button style={{ margin: '12px 0' }} onClick={run}>签名类型化数据</Button>
<ReactJsonView src={res} theme='monokai' />
{error && <div style={{ color: 'red' }}>{error}</div>}
</div>
)
}
Sign Typed Data
验证消息
验证消息签名的有效性,判断签名是否由指定地址生成。
参数
interface VerifyMessageParams {
address: string; // 钱包地址
message: string; // 原始消息
signature: string; // 签名
}
返回值
interface VerifyMessageResult {
valid: boolean; // 签名是否有效
}
@wagmi/actions
Pure JS calling approach, suitable for non-React scenarios or direct calls:
import { useState } from 'react'
import { verifyMessage } from 'wagmi/actions'
import { Button, Input } from 'antd'
import ReactJsonView from 'react-json-view'
import { http, createConfig } from 'wagmi'
import { mainnet, sepolia } from 'wagmi/chains'
const config = createConfig({
chains: [mainnet, sepolia],
transports: {
[mainnet.id]: http(),
[sepolia.id]: http(),
},
})
export function VerifyMessage() {
const [res, setRes] = useState({})
const [address, setAddress] = useState('')
const [message, setMessage] = useState('hello bitget wallet')
const [signature, setSignature] = useState('')
const [error, setError] = useState('')
async function run() {
setError('')
try {
const result = await verifyMessage(config, { address, message, signature })
setRes({ valid: result })
} catch (e) {
setError(e?.message || String(e))
setRes({})
}
}
return (
<div>
<Input style={{ width: 200, marginRight: 8 }} placeholder="address" value={address} onChange={e => setAddress(e.target.value)} />
<Input style={{ width: 200, marginRight: 8 }} placeholder="message" value={message} onChange={e => setMessage(e.target.value)} />
<Input style={{ width: 300, marginRight: 8 }} placeholder="signature" value={signature} onChange={e => setSignature(e.target.value)} />
<Button style={{ margin: '12px 0' }} onClick={run}>验证消息</Button>
<ReactJsonView src={res} theme='monokai' />
{error && <div style={{ color: 'red' }}>{error}</div>}
</div>
)
}
Verify Message
验证类型化数据
验证结构化数据(EIP-712)签名的有效性。
参数
interface VerifyTypedDataParams {
address: string; // 钱包地址
domain: object; // EIP-712 域信息
types: object; // EIP-712 类型定义
primaryType: string;// 主要类型
message: object; // 原始数据
signature: string; // 签名
}
返回值
interface VerifyTypedDataResult {
valid: boolean; // 签名是否有效
}
@wagmi/actions
Pure JS calling approach, suitable for non-React scenarios or direct calls:
import { useState } from 'react'
import { verifyTypedData } from 'wagmi/actions'
import { Button, Input } from 'antd'
import ReactJsonView from 'react-json-view'
import { http, createConfig } from 'wagmi'
import { mainnet, sepolia } from 'wagmi/chains'
const config = createConfig({
chains: [mainnet, sepolia],
transports: {
[mainnet.id]: http(),
[sepolia.id]: http(),
},
})
export function VerifyTypedData() {
const [res, setRes] = useState({})
const [address, setAddress] = useState('')
const [signature, setSignature] = useState('')
const [error, setError] = useState('')
const domain = {
name: 'MyDApp',
version: '1',
chainId: 1,
verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC',
}
const types = {
Person: [
{ name: 'name', type: 'string' },
{ name: 'wallet', type: 'address' },
],
Mail: [
{ name: 'from', type: 'Person' },
{ name: 'to', type: 'Person' },
{ name: 'contents', type: 'string' },
],
}
const message = {
from: {
name: 'Alice',
wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826',
},
to: {
name: 'Bob',
wallet: '0xAaaAaAaaAaAaAaaAaAaAaaAaAaAaAaAaAaAaAaAa',
},
contents: 'Hello Bob!',
}
async function run() {
setError('')
try {
const result = await verifyTypedData(config, {
address,
domain,
types,
primaryType: 'Mail',
message,
signature,
})
setRes({ valid: result })
} catch (e) {
setError(e?.message || String(e))
setRes({})
}
}
return (
<div>
<Input style={{ width: 200, marginRight: 8 }} placeholder="address" value={address} onChange={e => setAddress(e.target.value)} />
<Input style={{ width: 300, marginRight: 8 }} placeholder="signature" value={signature} onChange={e => setSignature(e.target.value)} />
<Button style={{ margin: '12px 0' }} onClick={run}>验证类型化数据</Button>
<ReactJsonView src={res} theme='monokai' />
{error && <div style={{ color: 'red' }}>{error}</div>}
</div>
)
}
Verify Typed Data
交易
发送交易
发起链上转账或合约调用交易。
参数
interface SendTransactionParams {
to: string; // 目标地址
value: bigint; // 转账金额(以 wei 为单位)
data?: string; // 可选,合约调用数据
}
返回值
interface SendTransactionResult {
hash: string; // 交易哈希
// 其他链上交易相关字段
}
@wagmi/actions
import { useState } from 'react'
import { Button, Input } from 'antd'
import ReactJsonView from 'react-json-view'
import { sendTransaction } from 'wagmi/actions'
import { http, createConfig } from 'wagmi'
import { mainnet, sepolia } from 'wagmi/chains'
const config = createConfig({
chains: [mainnet, sepolia],
transports: {
[mainnet.id]: http(),
[sepolia.id]: http(),
},
})
export function SendTransaction() {
const [res, setRes] = useState({})
const [to, setTo] = useState('0xAaaAaAaaAaAaAaaAaAaAaaAaAaAaAaAaAaAaAaAa')
const [value, setValue] = useState('0.01')
const [data, setData] = useState('')
const [error, setError] = useState('')
async function run() {
setError('')
try {
const result = await sendTransaction(config, {
to,
value: BigInt(Math.floor(Number(value) * 1e18)),
data: data || undefined,
})
setRes(result)
} catch (e) {
setError(e?.message || String(e))
setRes({})
}
}
return (
<div>
<Input style={{ width: 300, marginRight: 8 }} placeholder="to" value={to} onChange={e => setTo(e.target.value)} />
<Input style={{ width: 120, marginRight: 8 }} placeholder="value(ETH)" value={value} onChange={e => setValue(e.target.value)} />
<Input style={{ width: 300, marginRight: 8 }} placeholder="data (hex)" value={data} onChange={e => setData(e.target.value)} />
<Button style={{ margin: '12px 0' }} onClick={run}>发送交易</Button>
<ReactJsonView src={res} theme='monokai' />
{error && <div style={{ color: 'red' }}>{error}</div>}
</div>
)
}
API 参考
Last updated on