Skip to Content
dApp 接入Aptos Wallet Adapter

Aptos Wallet Adapter

Aptos 官方 React 钱包连接库。兼容的 OneKey 版本通过 Aptos Wallet Standard 注册。

适配器会发现注册了 Aptos Wallet Standard 功能的钱包。提供连接入口前,请确认 wallets 中包含 OneKey,并测试实际发布时使用的钱包和适配器版本。


安装

npm install @aptos-labs/wallet-adapter-react @aptos-labs/ts-sdk

基础设置

使用 AptosWalletAdapterProvider 包裹你的应用:

App.tsx
import { AptosWalletAdapterProvider } from '@aptos-labs/wallet-adapter-react' function App() { return ( <AptosWalletAdapterProvider autoConnect={true}> <YourApp /> </AptosWalletAdapterProvider> ) }

钱包连接

连接按钮

ConnectButton.tsx
import { useWallet } from '@aptos-labs/wallet-adapter-react' function ConnectButton() { const { connect, disconnect, account, connected, wallets } = useWallet() if (connected && account) { return ( <div> <p>Connected: {account.address.toString().slice(0, 6)}...{account.address.toString().slice(-4)}</p> <button onClick={disconnect}>Disconnect</button> </div> ) } return ( <div> {wallets?.map((wallet) => ( <button key={wallet.name} onClick={() => connect(wallet.name)} > <img src={wallet.icon} alt={wallet.name} width={24} /> {wallet.name} </button> ))} </div> ) }

钱包选择弹窗

此最小示例展示自定义钱包列表。生产应用需要补充弹窗焦点管理和键盘操作,或使用支持无障碍访问的对话框组件:

WalletModal.tsx
import { useWallet } from '@aptos-labs/wallet-adapter-react' import { useState } from 'react' function WalletModal() { const { wallets, connect } = useWallet() const [isOpen, setIsOpen] = useState(false) const [error, setError] = useState('') return ( <> <button onClick={() => setIsOpen(true)}>Connect Wallet</button> {isOpen && ( <div className="modal"> <h2>Select Wallet</h2> {error && <p role="alert">{error}</p>} {wallets?.map((wallet) => ( <button key={wallet.name} onClick={async () => { try { await connect(wallet.name) setIsOpen(false) } catch (error) { setError(error instanceof Error ? error.message : 'Connection failed') } }} > <img src={wallet.icon} alt={wallet.name} width={24} /> {wallet.name} </button> ))} <button onClick={() => setIsOpen(false)}>Close</button> </div> )} </> ) }

交易

签名并提交交易

替换省略的收款地址,并在界面中处理用户拒绝或请求失败。客户端和钱包必须使用同一网络。

import { useWallet } from '@aptos-labs/wallet-adapter-react' import { Aptos, AptosConfig, Network } from '@aptos-labs/ts-sdk' function TransferAPT() { const { account, network, signAndSubmitTransaction } = useWallet() const config = new AptosConfig({ network: Network.MAINNET }) const aptos = new Aptos(config) const handleTransfer = async () => { if (!account) return if (network?.name !== Network.MAINNET) throw new Error('Select Aptos mainnet first') const response = await signAndSubmitTransaction({ sender: account.address, data: { function: '0x1::aptos_account::transfer', functionArguments: [ '0x1234...', // recipient address 100000000, // amount in octas (1 APT = 100000000) ], }, }) // Wait for transaction const result = await aptos.waitForTransaction({ transactionHash: response.hash, }) console.log('Transaction confirmed:', result) } return <button onClick={handleTransfer}>Transfer APT</button> }

签名消息

用于身份验证时,将示例 nonce 替换为服务器签发的一次性挑战,并在服务器验证签名响应。

import { useWallet } from '@aptos-labs/wallet-adapter-react' function SignMessage() { const { signMessage, account } = useWallet() const handleSign = async () => { const response = await signMessage({ message: 'Welcome to My dApp!', nonce: crypto.randomUUID(), }) console.log('Signature:', response.signature) console.log('Full message:', response.fullMessage) } return <button disabled={!account} onClick={handleSign}>Sign Message</button> }

网络配置

在 Provider 中配置网络:

import { AptosWalletAdapterProvider } from '@aptos-labs/wallet-adapter-react' import { Network } from '@aptos-labs/ts-sdk' function App() { return ( <AptosWalletAdapterProvider autoConnect={true} dappConfig={{ network: Network.MAINNET, // Optional: specify additional networks aptosApiKeys: { [Network.MAINNET]: 'YOUR_API_KEY', [Network.TESTNET]: 'YOUR_TESTNET_KEY', }, }} > <YourApp /> </AptosWalletAdapterProvider> ) }

Hooks 参考

Hook 或返回成员说明
useWallet()钱包连接与交易的主 hook
account当前已连接账户
connected连接状态
wallets可用钱包列表
connect(walletName)连接指定钱包
disconnect()断开当前钱包
signAndSubmitTransaction(payload)签名并提交交易
signMessage(request)签署消息
network当前网络信息

相关资源

最后更新于