TRON Wallet Adapter
TronWallet Adapter helps dApps interact with TRON wallets easily.
Quick Start
Install
npm install @tronweb3/tronwallet-abstract-adapter @tronweb3/tronwallet-adapterspnpm install @tronweb3/tronwallet-abstract-adapter @tronweb3/tronwallet-adaptersyarn add @tronweb3/tronwallet-abstract-adapter @tronweb3/tronwallet-adapters- @tronweb3/tronwallet-abstract-adapter defines the common types used by all adapters such as
WalletReadyState,WalletError. - @tronweb3/tronwallet-adapters contains all adapters including
TronLinkAdapter,TokenPocketAdapterand so on.
Usage
// import Adapter class
import { TronLinkAdapter } from '@tronweb3/tronwallet-adapters';
// Create the adapter instance for TronLink
const tronLinkAdapter = new TronLinkAdapter();
// Connect to the wallet
await tronLinkAdapter.connect();
// Get the wallet address
const address = tronLinkAdapter.address;
console.log('The address is: ', address);
// Sign a message
const message = 'Hello, Tron!';
const signature = await tronLinkAdapter.signMessage(message);Detecting wallet
With wallet adapters you can check whether the wallet exists or not easily.
Browser extension wallets inject TRON provider into a global variable. After initialization adapter will check it for a while. dApps can check wallet state by adapter.readyState and monitor the wallet state by listening for readyStateChanged event.
import { TronLinkAdapter } from '@tronweb3/tronwallet-adapters';
import { WalletReadyState } from '@tronweb3/tronwallet-abstract-adapter';
const tronLinkAdapter = new TronLinkAdapter({ checkTimeout: 3000 });
if (tronLinkAdapter.readyState === WalletReadyState.Found) {
console.log('TronLink is ready');
} else {
tronLinkAdapter.on('readyStateChanged', (state) => {
console.log(state === WalletReadyState.Found ? 'TronLink is ready' : 'TronLink is not found');
});
}adapter.readyState is in type of WalletReadyState:
Loading: Adapter is checking the wallet. And the detection duration can be configured bycheckTimeoutparameter of constructor method.Found: The wallet is found and can be connected.NotFound: The wallet is not found after the detection duration.
Connect wallet
dApps can call adapter.connect() without checking wallet exists or not. Adapter will detect the wallet first and connect it if the wallet is found. If the wallet is not found, this method will throw an error.
import { TronLinkAdapter } from '@tronweb3/tronwallet-adapters';
import { WalletNotFoundError } from '@tronweb3/tronwallet-abstract-adapter';
const tronLinkAdapter = new TronLinkAdapter();
try {
await tronLinkAdapter.connect();
} catch (error: any) {
if (error instanceof WalletNotFoundError) {
console.log('Please install TronLink wallet first');
} else {
console.error(error);
}
}Connect wallet automatically
Some wallet keep the connection with the same website. This means dApps can access the wallet address and sign transaction even though the page is reloaded.
In this case dApps can listen to the connect event to monitor the connection status.
import { TronLinkAdapter } from '@tronweb3/tronwallet-adapters';
const tronLinkAdapter = new TronLinkAdapter();
// Check the connection status first
if (tronLinkAdapter.connected) {
console.log('Connected to wallet', tronLinkAdapter.address);
}
// Add event listener
tronLinkAdapter.on('connect', (address) => {
// Here you can get the connected wallet address and display it to the user.
console.log('Connected to wallet', address);
});Security Check
Adapters can run an optional security check when connecting. You host a risk-list service, and the adapter fetches it during connect(); if the connecting wallet has configured risk entries, they are passed to your onRiskDetected callback so you can warn users.
const adapter = new ExampleWalletAdapter({
securityOptions: {
enabled: true, // off by default
configUrls: ['https://your-domain.com/wallet-risks.json'],
onRiskDetected: async ({ risks }) => {
// show your own UI; throw to block the connection
console.warn(risks);
},
},
});It is disabled by default and never blocks a connection on its own. See Security Check for the full guide.
Interact with wallet
Once the connection with wallet is established, dApps can use wallet to sign messages or sign transaction.
Before the signing, we should initialize the wallet adapter and TronWeb instance.
import { TronLinkAdapter } from '@tronweb3/tronwallet-adapters';
import { TronWeb } from 'tronweb';
// Initialize TronWeb
const tronWeb = new TronWeb({
fullHost: 'https://api.nileex.io',
privateKey: '',
});
// Initialize TronLinkAdapter and connect to wallet
const tronLinkAdapter = new TronLinkAdapter();
await tronLinkAdapter.connect();Sign message
We use signMessage(message: string) method to sign a message and use TronWeb to verify the signature:
const message = 'Hello world';
const signature = await tronLinkAdapter.signMessage(message);
const recoveredAddress = await tronWeb.trx.verifyMessageV2(message, signature);
console.log(`The signature is ${recoveredAddress === adapter.address ? 'valid' : 'invalid'}`);Sign transaction
To sign a transaction, you should create a tranasction with TronWeb. The following code shows how to sign a transaction that transfers USDT on Nile testnet to another address.
TIP
TIP: You can get USDT on Nile testnet from Nile faucet.
// USDT contract address
const contractAddress = 'TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf';
// Use `transfer()` method to transfer TRC20 token
const functionSelector = 'transfer(address,uint256)';
// Replace the address you want to transfer
const parameter = [
{ type: 'address', value: 'The address you want to transfer' },
{ type: 'uint256', value: 100 },
];
// Create a transfer transaction
const tx = await tronWeb.transactionBuilder.triggerSmartContract(
tronLinkAdapter.address,
functionSelector,
{},
parameter
);
// Use `signTransaction()` method to sign the transaction
const signedTx = await adapter.signTransaction(tx.transaction);
// Send the transaction to the network
const result = await tronWeb.trx.sendRawTransaction(signedTx);Listen to adapter events
Except the readyStateChanged introduced in the previous section, TronWallet Adapter also provides the following events:
| Event Name | Description |
|---|---|
connect | Emit when the connection is established |
accountsChanged | Emit when the current connected address changes |
disconnect | Emit when the wallet is disconnected |
chainChanged | Emit when the current chain changes |
Connect event
When adapter creates a connection with wallet, it emits a connect event.
const tronLinkAdapter = new TronLinkAdapter();
tronLinkAdapter.on('connect', (address: string) => {
console.log('The connected address is:', address);
}); accountsChanged event
accountsChanged event is emitted when the current connected account changes. You can listen to this event to update the address displayed to user.
TIP
TIP: Some wallets may not support this event.
const tronLinkAdapter = new TronLinkAdapter();
tronLinkAdapter.on('accountsChanged', (curAddress: string, preAddress?: string) => {
console.log('The current address is:', curAddress);
}); disconnect event
When you cancel the connection from extension wallet, the disconnect event will be emitted.
TIP
TIP: Some wallets may not support this event.
chainChanged event
Some extension wallets like TronLink support TRON testnet. When users switch the selected network, the chainChanged event will be triggered.
const tronLinkAdapter = new TronLinkAdapter();
tronLinkAdapter.on('chainChanged', (chainData) => {
console.log('The current network changed:', chainData);
}); TIP
TIP: Currently only TronLink supports this event.
WalletConnect
TronWallet Adapter supports WalletConnect, allowing users to connect with mobile wallets by scanning QR codes.
Basic Usage
import { WalletConnectAdapter } from '@tronweb3/tronwallet-adapter-walletconnect';
const adapter = new WalletConnectAdapter({
network: 'Nile',
options: {
projectId: 'your-project-id',
metadata: {
name: 'Your DApp Name',
description: 'Your DApp Description',
url: 'https://your-dapp.com',
icons: ['https://your-dapp.com/icon.png'],
},
},
});
await adapter.connect();Custom QR Code
You can use onUri callback to render your own QR code instead of the default modal:
await adapter.connect({
onUri: (uri) => {
// Display your custom QR code with the URI
console.log('WalletConnect URI:', uri);
// Use any QR code library to generate and display the QR code
},
});TRON DApp Quickstart
If you are looking to build a fully functional TRON DApp web application, please refer to our TRON dApp Quickstart project - a complete starter kit to help you build and launch your TRON DApp with ease.
