本页目录
Aptos
使用 OneKey 的 Petra 兼容 Provider 集成 Aptos 区块链。通过 window.$onekey.aptos 访问。
OneKey 提供 Petra 兼容方法和 Aptos Wallet Standard 适配器。两者的方法签名不同,请使用对应集成方式的接口。
快速链接
Provider 检测
// Detect OneKey Aptos provider
const provider = window.$onekey?.aptos
if (!provider) {
throw new Error('OneKey Aptos provider not detected')
}
// Check provider info
console.log('Provider:', provider.isOneKey ? 'OneKey' : 'Unknown')快速开始
连接钱包
// Connect and get account info
const response = await provider.connect()
console.log({
address: response.address, // Account address
publicKey: response.publicKey, // Public key
})检查连接状态
const isConnected = await provider.isConnected()
console.log('Connected:', isConnected)断开连接
await provider.disconnect()账户管理
获取当前账户
const account = await provider.account()
console.log({
address: account.address,
publicKey: account.publicKey,
})获取网络信息
const network = await provider.getNetwork()
console.log({
name: network.name, // 'mainnet', 'testnet', 'devnet'
chainId: network.chainId, // Network chain ID
url: network.url, // RPC URL
})监听账户变化
provider.onAccountChange((newAccount) => {
if (newAccount) {
console.log('Account changed:', newAccount)
} else {
console.log('Wallet disconnected')
}
})监听网络变化
provider.onNetworkChange((network) => {
console.log('Network changed:', network)
})交易
签名并提交交易
// Simple APT transfer
const payload = {
type: 'entry_function_payload',
function: '0x1::aptos_account::transfer',
type_arguments: [],
arguments: [
'0x1234...', // Recipient address
'100000000', // Amount in Octas (1 APT = 100000000 Octas)
],
}
const response = await provider.signAndSubmitTransaction(payload)
console.log('Transaction hash:', response.hash)签名交易(不提交)
const payload = {
type: 'entry_function_payload',
function: '0x1::coin::transfer',
type_arguments: ['0x1::aptos_coin::AptosCoin'],
arguments: ['0x1234...', '100000000'],
}
const signedTxn = await provider.signTransaction(payload)
// Submit later using Aptos SDK
// const pendingTxn = await client.submitTransaction(signedTxn)签名交易 V2 (BCS 序列化)
用于 BCS 序列化交易的高级用例:
const rawTransaction = '<BCS_SERIALIZED_TRANSACTION>'; // Use the encoding expected by your wallet version
const signedTxn = await provider.signTransactionV2({ transaction: rawTransaction, transactionType: 'simple' })交易选项
const payload = {
type: 'entry_function_payload',
function: '0x1::aptos_account::transfer',
type_arguments: [],
arguments: ['0x1234...', '100000000'],
}
// The legacy direct method takes only a payload.
const response = await provider.signAndSubmitTransaction(payload)
// For gas options, use signAndSubmitTransactionV2 with the matching Wallet Standard input.消息签名
签名消息
签名任意消息用于身份验证:
const message = 'Welcome to MyApp!\n\nClick to sign in.\n\nNonce: abc123'
const response = await provider.signMessage({
message,
nonce: 12345, // Example only; obtain a single-use challenge from your server
})
console.log({
signature: response.signature, // Hex-encoded signature
fullMessage: response.fullMessage, // Full signed message
prefix: response.prefix, // Message prefix used
})验证消息(链下)
import nacl from 'tweetnacl'
const { signature, fullMessage } = await provider.signMessage({
message: 'Hello Aptos',
nonce: 12345,
})
const account = await provider.account()
const pubKeyBytes = Buffer.from(account.publicKey.slice(2), 'hex')
const signatureBytes = Buffer.from(signature.slice(2), 'hex')
const messageBytes = Buffer.from(fullMessage)
const isValid = nacl.sign.detached.verify(messageBytes, signatureBytes, pubKeyBytes)
console.log('Signature valid:', isValid)智能合约交互
调用 View 函数
// View functions don't require signing
const result = await client.view({
function: '0x1::coin::balance',
type_arguments: ['0x1::aptos_coin::AptosCoin'],
arguments: [accountAddress],
})
console.log('Balance:', result[0])调用 Entry 函数
// Mint NFT example
const payload = {
type: 'entry_function_payload',
function: '0x3::token::create_collection_script',
type_arguments: [],
arguments: [
'My Collection', // Collection name
'Description', // Description
'https://example.com', // URI
'1000', // Maximum supply
[false, false, false], // Mutability config
],
}
const response = await provider.signAndSubmitTransaction(payload)API 参考
方法
| 方法 | 说明 |
|---|---|
connect() | 连接钱包并获取账户 |
disconnect() | 断开钱包连接 |
isConnected() | 检查连接状态 |
account() | 获取当前账户信息 |
network() | 获取当前网络名称 |
signMessage(request) | 签署消息 |
signAndSubmitTransaction(payload) | 签名并提交交易 |
signTransaction(payload) | 仅签名,不提交交易 |
signTransactionV2(params) | 签署经 BCS 序列化的交易 |
onAccountChange(callback) | 监听账户变化 |
onNetworkChange(callback) | 监听网络变化 |
类型
interface AptosAccount {
address: string // Hex address with 0x prefix
publicKey: string // Ed25519 public key
}
interface AptosNetwork {
name: string // Network name
chainId: number // Chain ID
url: string // RPC URL
}
interface SignMessageRequest {
message: string // Message to sign
nonce: number // Required by the direct provider API
address?: boolean // Include address in message
application?: boolean // Include app info
chainId?: boolean // Include chain ID
}
interface SignMessageResponse {
signature: string // Hex signature
fullMessage: string // Complete signed message
prefix: string // APTOS prefix
address?: string // Signer address
application?: string // Application info
chainId?: number // Chain ID
nonce: number // Nonce used
}
interface TransactionPayload {
type: 'entry_function_payload' | 'script_payload' | 'module_bundle_payload'
function: string // Module::function format
type_arguments: string[]
arguments: any[]
}支持的网络
| 网络 | 说明 |
|---|---|
| Mainnet | 生产网络 |
| Testnet | 测试环境 |
| Devnet | 开发环境 |
错误处理
try {
await provider.connect()
} catch (error) {
switch (error.code) {
case 4001:
console.log('User rejected the request')
break
case 4100:
console.log('The account or method is not authorized')
break
case 4200:
console.log('Unsupported method')
break
default:
console.error('Error:', error.message)
}
}常见错误码
| 错误码 | 说明 |
|---|---|
| 4001 | 用户拒绝请求 |
| 4100 | 未授权 |
| 4200 | 不支持的方法 |
| 4201 | 不支持的网络 |
| -32603 | 内部错误 |
使用 Aptos Wallet Adapter
对于 React 应用,使用官方的 Aptos Wallet Adapter:
npm install @aptos-labs/wallet-adapter-reactimport { AptosWalletAdapterProvider } from '@aptos-labs/wallet-adapter-react'
function App() {
return (
<AptosWalletAdapterProvider>
<YourApp />
</AptosWalletAdapterProvider>
)
}使用兼容 Wallet Standard 的适配器版本,并确认自动发现的钱包列表中包含 OneKey。
从 Petra 迁移
OneKey 的 Aptos provider 兼容 Petra。更新你的 provider 检测代码:
// Before (Petra only)
const provider = window.petra
// After (OneKey with Petra fallback)
const provider = window.$onekey?.aptos || window.petra最后更新于