本页目录
TRON
使用 OneKey 的 TronLink 兼容 Provider 集成 TRON 区块链。通过 window.$onekey.tron 或 window.tronWeb 访问。
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)交易
签名交易
签名交易但不广播:
// Build transaction
const tx = await tronWeb.transactionBuilder.sendTrx(
'TRecipientAddress...',
tronWeb.toSun(10),
tronWeb.defaultAddress.base58
)
// Sign via provider
const signedTx = await provider.sign(tx)
console.log('Signed transaction:', signedTx)
// Broadcast manually
const result = await tronWeb.trx.sendRawTransaction(signedTx)智能合约交互
// Call contract method
const contract = await tronWeb.contract().at(contractAddress)
// Read (view function)
const result = await contract.someViewFunction().call()
// Write (requires signing)
const tx = await contract.someWriteFunction(param1, param2).send({
feeLimit: 100_000_000, // 100 TRX
callValue: 0,
})触发智能合约
const tx = await tronWeb.transactionBuilder.triggerSmartContract(
contractAddress,
'transfer(address,uint256)',
{ feeLimit: 100_000_000 },
[
{ type: 'address', value: recipientAddress },
{ type: 'uint256', value: amount }
],
tronWeb.defaultAddress.base58
)
const signedTx = await provider.sign(tx.transaction)
const result = await tronWeb.trx.sendRawTransaction(signedTx)消息签名
签名消息 V1(十六进制)
签名十六进制编码的消息:
const message = tronWeb.toHex('Hello TRON!')
const signature = await provider.signMessage(message)
console.log('Signature:', signature)签名消息 V2(UTF-8)
直接签名 UTF-8 消息:
const message = 'Hello TRON!'
const signature = await provider.signMessageV2(message)
console.log('Signature:', signature)验证签名
const message = 'Hello TRON!'
const signature = await provider.signMessageV2(message)
// Verify using TronWeb
const address = await tronWeb.trx.verifyMessageV2(message, signature)
console.log('Signer:', address)事件处理
监听账户变化
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)
}
})API 参考
Provider 方法
| 方法 | 说明 |
|---|---|
request({ method, params }) | 通用 JSON-RPC 请求 |
sign(transaction) | 签名交易 |
signMessage(hexMessage) | 签名十六进制消息(V1) |
signMessageV2(message) | 签名 UTF-8 消息(V2) |
Request 方法
| 方法 | 说明 |
|---|---|
tron_requestAccounts | 请求连接 |
tron_getProviderState | 获取 provider 状态 |
tron_signTransaction | 签名交易 |
signMessageV1 | 签名消息 V1 |
signMessageV2 | 签名消息 V2 |
响应码
调用 tron_requestAccounts 后,应检查成功返回的响应中的 code。当前 provider 在已有待处理请求时返回 4001,在没有返回账户或请求失败时返回 4000。这些代码的含义与 Ethereum JSON-RPC 错误码不同。
| 错误码 | 说明 |
|---|---|
| 200 | 成功 |
| 4000 | 用户拒绝 |
| 4001 | 请求排队中 |
事件
| 事件 | 说明 |
|---|---|
accountsChanged | 账户已变更 |
chainChanged | 网络已变更 |
connect | 已连接 |
disconnect | 已断开连接 |
使用 SunWeb
用于 DappChain(侧链)操作:
const sunWeb = window.sunWeb
// Main chain to side chain
await sunWeb.depositTrx(
amount,
depositFee,
feeLimit
)
// Side chain to main chain
await sunWeb.withdrawTrx(
amount,
withdrawFee,
feeLimit
)错误处理
try {
const result = await provider.request({
method: 'tron_requestAccounts'
})
if (result.code === 4001) {
console.log('A connection request is already pending')
} else if (result.code !== 200) {
console.log('Connection was not approved:', result.message)
}
} catch (error) {
console.error('Request failed:', error)
}从 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最后更新于