本页目录
快速开始
先连接 provider,并使用同一钱包对应的 TronWeb 实例。将省略的地址和合约方法替换为有效值。准备交易前,检查所选网络。
了解如何检测、连接和与 TRON 进行交互。
OneKey 提供兼容 TronLink 的 provider 和 TronWeb 集成。功能可用性取决于钱包版本和所选网络。
Provider 检测
// OneKey injects both the provider and TronWeb instances
const provider = window.$onekey?.tron
// TronWeb is available globally after connection
let tronWeb = provider?.tronWeb
if (!provider) {
throw new Error('OneKey TRON provider not detected')
}
// Check if it's TronLink compatible
console.log('isTronLink:', provider.isTronLink) // true请求账户
// Request connection
const result = await provider.request({
method: 'tron_requestAccounts'
})
if (result.code === 200) {
tronWeb = provider.tronWeb
if (!tronWeb) throw new Error('OneKey TronWeb is not ready')
console.log('Connected!')
const address = tronWeb.defaultAddress.base58
console.log('Address:', address)
} else {
console.log('Connection rejected:', result.message)
}检查连接状态
// Check if TronWeb is ready
if (provider.ready && tronWeb && tronWeb.defaultAddress.base58) {
console.log('Connected:', tronWeb.defaultAddress.base58)
} else {
console.log('Not connected')
}使用 TronWeb
连接后使用 provider.tronWeb,确保请求仍发送给 OneKey:
获取余额
const balance = await tronWeb.trx.getBalance(tronWeb.defaultAddress.base58)
console.log('Balance:', tronWeb.fromSun(balance), 'TRX')发送 TRX
const tx = await tronWeb.trx.sendTransaction(
'TRecipientAddress...',
tronWeb.toSun(10) // 10 TRX
)
console.log('Transaction:', tx.txid)发送 TRC20 代币
const contractAddress = 'TTokenContractAddress...'
const contract = await tronWeb.contract().at(contractAddress)
// Get decimals
const decimals = await contract.decimals().call()
// Transfer tokens
const amount = (100n * 10n ** BigInt(decimals.toString())).toString() // 100 tokens, exact integer
const tx = await contract.transfer(
'TRecipientAddress...',
amount
).send()
console.log('Transaction:', tx)事件处理
监听账户变更
provider.on('accountsChanged', (accounts) => {
if (accounts[0]) {
console.log('Account changed:', accounts[0])
} else {
console.log('Disconnected')
}
})监听网络变更
provider.on('chainChanged', (chainId) => {
console.log('Network changed:', chainId)
// Recommend page reload for network changes
})Window 事件(TronLink 兼容)
// Listen for TronLink initialization
window.addEventListener('tronLink#initialized', () => {
console.log('TronLink initialized')
})
// Listen for messages
window.addEventListener('message', (event) => {
if (event.source === window && event.data?.isTronLink && event.data?.message) {
const { action, data } = event.data.message
console.log('TronLink event:', action, data)
}
})从 TronLink 迁移
OneKey 与 TronLink 兼容。更新您的检测逻辑:
// Before (TronLink only)
const tronWeb = window.tronWeb
// After (OneKey with TronLink fallback)
const provider = window.$onekey?.tron || window.tronLink
const tronWeb = window.tronWeb // Compatibility global; verify which wallet owns it最后更新于