Skip to main content

TRON

UKey Wallet TRON Provider is used to connect TRON accounts, use TronWeb, sign transactions and sign messages in web applications. The page can be accessed via window.$ukey.tron, and once connected, you can also use window.tronWeb.

ℹ️

UKey Wallet TRON Provider is compatible with the TronLink interface and provides TronWeb and SunWeb related instances.



Find Provider

// Note: UKey Wallet injects provider and TronWeb instances
const provider = window.$ukey?.tron;

// TronWeb becomes globally available after connection
const tronWeb = window.tronWeb;

if (!provider) {
throw new Error("UKey Wallet TRON provider not detected");
}

// Check whether it is TronLink-compatible
console.log("isTronLink:", provider.isTronLink); // Reference value: true

Get Going

Ask Access

// Request the connection
const callResult = await provider.request({
method: "tron_requestAccounts",
});

if (callResult.code === 200) {
console.log("Connection is ready!");
const address = tronWeb.defaultAddress.base58;
console.log("Resolved address:", address);
} else {
console.log("Connection request was rejected:", callResult.message);
}

Conn Status

// Check whether TronWeb is ready
if (tronWeb && tronWeb.ready) {
console.log("Connection established:", tronWeb.defaultAddress.base58);
} else {
console.log("Connection has not been established");
}

Using TronWeb

After the connection is successful, you can access the TRON network through the global tronWeb instance:

Get balance

const balance = await tronWeb.trx.getBalance(tronWeb.defaultAddress.base58);
console.log("Current balance:", tronWeb.fromSun(balance), "TRX");

Send TRX

const tx = await tronWeb.trx.sendTransaction(
"TR7x6W5v4U3t2S1r0Q9p8NmLyKjHgFeDcB",
tronWeb.toSun(10), // ten TRX
);

console.log("Built transaction:", tx.txid);

Send TRC20 tokens

const contractAddress = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t";
const contract = await tronWeb.contract().at(contractAddress);

// Retrieve accuracy
const decimals = await contract.decimals().call();

// Transfer fungible tokens
const amount = 100 * 10 ** decimals; // token amount: 100
const tx = await contract.transfer("TR7x6W5v4U3t2S1r0Q9p8NmLyKjHgFeDcB", amount).send();

console.log("Built transaction:", tx);

Transfers

signature transaction

The following example is only responsible for signing, and broadcasting is completed by the application through TronWeb:

// Build transaction
const tx = await tronWeb.transactionBuilder.sendTrx(
"TR7x6W5v4U3t2S1r0Q9p8NmLyKjHgFeDcB",
tronWeb.toSun(10),
tronWeb.defaultAddress.base58,
);

// Sign through the provider
const signedTx = await provider.sign(tx);

console.log("Signed payload:", signedTx);

// Broadcast manually
const callResult = await tronWeb.trx.sendRawTransaction(signedTx);

Smart contract interaction

// Note: Call contract method
const contract = await tronWeb.contract().at(contractAddress);

// Fetch (view function)
const callResult = await contract.someViewFunction().call();

// 写操作需要签名确认
const tx = await contract.someWriteFunction(param1, param2).send({
feeLimit: 100_000_000, // fee cap: 100 TRX
callValue: 0,
});

Trigger smart contract

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 callResult = await tronWeb.trx.sendRawTransaction(signedTx);

Msg Sign

Signed message V1 (hex)

V1 receives the hex-encoded message:

const message = tronWeb.toHex("TRON sample message");
const signature = await provider.signMessage(message);

console.log("Generated signature:", signature);

Signed Message V2 (UTF-8)

V2 can directly sign UTF-8 text, which is more suitable for displaying to users:

const message = "TRON sample message";
const signature = await provider.signMessageV2(message);

console.log("Generated signature:", signature);

Verify signature

const message = "TRON sample message";
const signature = await provider.signMessageV2(message);

// Validate using TronWeb
const address = await tronWeb.trx.verifyMessageV2(message, signature);
console.log("Recovered signer:", address);

Event Flow

Watch Accounts

provider.on("accountsChanged", (accounts) => {
if (accounts[0]) {
console.log("Active account changed:", accounts[0]);
} else {
console.log("Connection closed");
}
});

Watch Network

provider.on("chainChanged", (chainId) => {
console.log("Network switched:", chainId);
// A full page reload is usually the safest response to network changes
});
// Watch for TronLink initialization
window.addEventListener("tronLink#initialized", () => {
console.log("TronLink finished initializing");
});

// Start listening for messages
window.addEventListener("message", (event) => {
if (event.data.isTronLink) {
const { action, data } = event.data.message;
console.log("TronLink callback event:", action, data);
}
});

API Notes

Provider method

MethodDetails
request({ action, params })Generic JSON-RPC requests
sign(transaction)Sign transaction
signMessage(hexMessage)Signed Hexadecimal Message (V1)
signMessageV2(message)Signed UTF-8 messages (V2)

Request method

MethodDetails
tron_requestAccountsRequest connection
tron_getProviderStateGet provider status
tron_signTransactionSign transaction
signMessageV1Signed Message V1
signMessageV2Signed Message V2

response code

CodeDescription
200success
4000User rejected the request
4001Request queued

Events

EventDetails
accountsChangedSelected account changed
chainChangedNetwork updated
connectConnected
disconnectConnection closed

Use SunWeb

SunWeb can be used for DAppChain (side chain) related operations:

const sunWeb = window.sunWeb;

// Move from main chain to side chain
await sunWeb.depositTrx(amount, depositFee, feeLimit);

// Move from side chain to main chain
await sunWeb.withdrawTrx(amount, withdrawFee, feeLimit);

Handle Errors

try {
const callResult = await provider.request({
method: "tron_requestAccounts",
});

if (callResult.code !== 200) {
throw new Error(callResult.message);
}
} catch (error) {
if (error.code === 4001) {
console.log("The user declined the request");
} else {
console.error("Operation error:", error.message);
}
}

UKey Wallet is compatible with the TronLink interface. When migrating, read UKey Wallet first, and then fall back to TronLink if it is not installed:

// 旧写法(仅 TronLink)
const legacyTronWeb = window.tronWeb;

// Updated flow: UKey Wallet first, TronLink as fallback
const provider = window.$ukey?.tron || window.tronLink;
const activeTronWeb = window.tronWeb; // Both inject this object