Skip to Content
dAppsTron

TRON

Integrieren Sie die TRON-Blockchain mit dem TronLink-kompatiblen Provider von OneKey. Zugriff über window.$onekey.tron oder window.tronWeb.

OneKey stellt einen TronLink-kompatiblen Provider und eine TronWeb-Integration bereit. Die Verfügbarkeit von Funktionen hängt von der Wallet-Version und dem ausgewählten Netzwerk ab.



Provider erkennen

// 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

Schnellstart

Konten anfordern

// 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) }

Verbindungsstatus prüfen

// Check if TronWeb is ready if (provider.ready && tronWeb && tronWeb.defaultAddress.base58) { console.log('Connected:', tronWeb.defaultAddress.base58) } else { console.log('Not connected') }

TronWeb verwenden

Nach dem Verbinden verwenden Sie provider.tronWeb, damit Anfragen OneKey zugeordnet bleiben:

Guthaben abrufen

const balance = await tronWeb.trx.getBalance(tronWeb.defaultAddress.base58) console.log('Balance:', tronWeb.fromSun(balance), 'TRX')

TRX senden

const tx = await tronWeb.trx.sendTransaction( 'TRecipientAddress...', tronWeb.toSun(10) // 10 TRX ) console.log('Transaction:', tx.txid)

TRC20-Token senden

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)

Transaktionen

Transaktion signieren

Eine Transaktion signieren, ohne sie zu übertragen:

// 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)

Smart-Contract-Interaktion

// 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, })

Smart Contract auslösen

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)

Nachrichten signieren

Nachricht signieren V1 (Hex)

Hexkodierte Nachrichten signieren:

const message = tronWeb.toHex('Hello TRON!') const signature = await provider.signMessage(message) console.log('Signature:', signature)

Nachricht signieren V2 (UTF-8)

UTF-8-Nachrichten direkt signieren:

const message = 'Hello TRON!' const signature = await provider.signMessageV2(message) console.log('Signature:', signature)

Signatur prüfen

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)

Ereignisbehandlung

Auf Kontoänderungen reagieren

provider.on('accountsChanged', (accounts) => { if (accounts[0]) { console.log('Account changed:', accounts[0]) } else { console.log('Disconnected') } })

Auf Netzwerkänderungen reagieren

provider.on('chainChanged', (chainId) => { console.log('Network changed:', chainId) // Recommend page reload for network changes })
// 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-Referenz

Provider-Methoden

MethodeBeschreibung
request({ method, params })Allgemeine JSON-RPC-Anfrage
sign(transaction)Eine Transaktion signieren
signMessage(hexMessage)Hex-Nachricht signieren (V1)
signMessageV2(message)UTF-8-Nachricht signieren (V2)

Anfragemethoden

MethodeBeschreibung
tron_requestAccountsVerbindung anfordern
tron_getProviderStateProvider-Status abrufen
tron_signTransactionTransaktion signieren
signMessageV1Nachricht signieren V1
signMessageV2Nachricht signieren V2

Antwortcodes

Prüfen Sie bei tron_requestAccounts das Feld code in der aufgelösten Antwort. Die aktuelle Provider-Implementierung gibt 4001 für eine bereits ausstehende Anfrage und 4000 zurück, wenn keine Konten zurückgegeben werden oder die Anfrage fehlschlägt. Dies sind keine Ethereum-JSON-RPC-Fehlerbedeutungen.

CodeBeschreibung
200Erfolg
4000Vom Nutzer abgelehnt
4001Anfrage in der Warteschlange

Ereignisse

EreignisBeschreibung
accountsChangedKonto geändert
chainChangedNetzwerk geändert
connectVerbunden
disconnectGetrennt

SunWeb verwenden

Für DappChain-Vorgänge (Sidechain):

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 )

Fehlerbehandlung

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) }

OneKey ist TronLink-kompatibel. Aktualisieren Sie Ihre Erkennungslogik:

// 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
Zuletzt aktualisiert am