@tronweb3/walletconnect-tron helps dApps connect to the TRON network via WalletConnect.
You can install @tronweb3/walletconnect-tron with npm, yarn, or pnpm:
npm i @tronweb3/walletconnect-tronyarn add @tronweb3/walletconnect-tronpnpm add @tronweb3/walletconnect-tron| Argument | Description | Type |
|---|---|---|
| network | The chain (Mainnet, Shasta, Nile) | string |
| options | WalletConnect client options | object |
| themeMode | Theme mode (dark | light) |
string |
| themeVariables | Theming variables (--w3m-*) |
object |
interface WalletConnectAdapterConfig {
network: WalletConnectChainID;
options: SignClientTypes.Options;
/**
* Theme mode configuration flag. By default, `themeMode` follows the user's system setting.
* @type `dark` | `light`
* @see https://docs.reown.com/appkit/react/core/theming
*/
themeMode?: 'dark' | 'light';
/**
* Theme variable configuration object.
* @default undefined
* @see https://docs.reown.com/appkit/react/core/theming#themevariables
*/
themeVariables?: ThemeVariables;
}import { WalletConnectWallet, WalletConnectChainID } from '@tronweb3/walletconnect-tron';
const wallet = new WalletConnectWallet({
network: WalletConnectChainID.Mainnet,
options: {
relayUrl: 'wss://relay.walletconnect.com',
projectId: '....',
metadata: {
name: 'Your dApp name',
description: 'Your dApp description',
url: 'Your dApp url',
icons: ['Your dApp icon']
}
},
// Theming (optional)
themeMode: 'dark',
themeVariables: {
'--w3m-z-index': 1000
// More variables: https://docs.reown.com/appkit/react/core/theming#themevariables
}
});Use wallet.connect() to establish a connection. If the dApp has previously connected, it will reconnect automatically; otherwise, a WalletConnect QR code will be displayed.
Returns an object containing the wallet address when connected (e.g., { address: string }).
const { address } = await wallet.connect();If you want to use your own UI to display the QR code, you can provide an onUri callback to receive the WalletConnect URI. When onUri is provided, the AppKit modal will be automatically skipped.
| Parameter | Description | Type |
|---|---|---|
| onUri | Callback to receive the WalletConnect URI string | Function |
const { address } = await wallet.connect({
onUri: (uri) => {
console.log('WalletConnect URI:', uri);
// Display the QR code using your own UI
// For example, using the qrcode library:
// import QRCode from 'qrcode';
// QRCode.toCanvas(document.getElementById('canvas'), uri);
}
});- Implement custom QR code styling and branding
- Display QR codes in mobile apps or custom web interfaces
- Integrate with existing UI frameworks or design systems
- Add custom loading states or error handling around QR code display
Use wallet.disconnect() to disconnect the wallet.
try {
await wallet.disconnect();
} catch (error) {
console.log('disconnect:' + error);
}Signs the provided transaction object.
| Argument | Description | Type |
|---|---|---|
| transaction | TRON transaction | object |
Returns a signed transaction object.
- TRX transfer (native TRX)
import { TronWeb } from 'tronweb';
const tronWeb = new TronWeb({ fullHost: 'https://nile.trongrid.io' }); // Nile Testnet
const from = '<yourAddress>';
const to = '<recipientAddress>';
const amountSun = 1_000_000; // 1 TRX
// build
const tx = await tronWeb.transactionBuilder.sendTrx(to, amountSun, from);
// sign
const signedTransaction = await wallet.signTransaction(tx);
// optional: broadcast
// const receipt = await tronWeb.trx.sendRawTransaction(signedTransaction)- Contract call (USDT approve)
import { TronWeb } from 'tronweb';
const tronWeb = new TronWeb({ fullHost: 'https://nile.trongrid.io' }); // Nile Testnet
const from = '<yourAddress>';
const usdt = '<usdtContract>';
const spender = '<spenderAddress>';
const amount = 100n * 1_000_000n; // 100 USDT, 6 decimals
// triggerSmartContract returns { transaction }
const { transaction } = await tronWeb.transactionBuilder.triggerSmartContract(
usdt,
'approve(address,uint256)',
{ feeLimit: 200000000 },
[
{ type: 'address', value: spender },
{ type: 'uint256', value: amount.toString() }
],
from
);
const signedTransaction = await wallet.signTransaction(transaction);
// optional: broadcast
// const receipt = await tronWeb.trx.sendRawTransaction(signedTransaction)- For
triggerSmartContract, pass thetransactionfield from its response, not the whole response object. sendTrxreturns the transaction object directly; pass it towallet.signTransaction.- Some wallets auto-broadcast, others do not. If not, call
tronWeb.trx.sendRawTransaction(signedTransaction)yourself.
Signs a string message.
| Argument | Description | Type |
|---|---|---|
| message | The message to sign | string |
try {
const signature = await wallet.signMessage('hello world');
} catch (error) {
console.log('signMessage:' + error);
}Checks the connection status.
Returns { address: string }. If not connected, returns { address: '' }.
const { address } = await wallet.checkConnectStatus();The wallet supports event listeners to monitor connection state and account changes.
Note: The on() method returns a function that can be called to unsubscribe from the event. This is why the returned value is typically named unsubscribe.
Triggered when the connected account address changes (e.g., user switches accounts in the wallet).
| Parameter | Description | Type |
|---|---|---|
| accounts | Array of account addresses | string[] |
The first address in the array is the primary account address.
// on() returns a function that can be called to unsubscribe
const unsubscribe = wallet.on('accountsChanged', accounts => {
const primaryAddress = accounts[0];
console.log('Primary address:', primaryAddress);
console.log('All addresses:', accounts);
});
// Call the returned function to unsubscribe when done
unsubscribe();Triggered when the wallet connection is disconnected (either by user action or network issues).
// on() returns a function that can be called to unsubscribe
const unsubscribe = wallet.on('disconnect', () => {
console.log('Wallet disconnected');
// Clean up your app state
});
// Call the returned function to unsubscribe when done
unsubscribe();Recommended: use the unsubscribe function returned by on(). To remove a specific listener with off(), pass the same function reference:
// Preferred
const fn = accounts => {
/* ... */
};
const unsubscribe = wallet.on('accountsChanged', fn);
unsubscribe();
// Or remove by function reference
wallet.off('accountsChanged', fn);
// Cleanup
wallet.removeAllListeners('accountsChanged');
// wallet.removeAllListeners();The SDK exposes AppKit control methods for advanced use cases. These methods allow you to control the AppKit modal and subscribe to its state changes.
Note: AppKit is initialized during the first connect() call. Most methods require AppKit to be initialized first.
Programmatically close the AppKit modal.
// Close the modal programmatically
await wallet.closeModal();- Auto-close modal after a timeout
- Close modal based on custom business logic
- Integrate with your own UI flow
Dynamically change the AppKit theme mode after initialization.
| Parameter | Description | Type |
|---|---|---|
| mode | Theme mode to set | 'light' | 'dark' |
// Switch to light theme
wallet.setThemeMode('light');
// Switch to dark theme
wallet.setThemeMode('dark');Note: This method can be called after connect() to dynamically change the theme. The initial theme is set via the themeMode config option when creating the wallet instance.
Subscribe to AppKit modal state changes (e.g., modal open/close events).
| Parameter | Description | Type |
|---|---|---|
| callback | Function called on state changes | Function |
Returns an unsubscribe function that can be called to stop receiving updates.
// Subscribe to modal state changes
const unsubscribe = wallet.subscribeModalState(state => {
console.log('Modal open:', state.open);
console.log('Selected network:', state.selectedNetworkId);
if (state.open) {
console.log('Modal opened');
} else {
console.log('Modal closed');
}
});
// Later: unsubscribe when done
unsubscribe();Note: This method can be called before connect(). The subscription will become active after AppKit is initialized.
Subscribe to all AppKit events for analytics and tracking purposes.
| Parameter | Description | Type |
|---|---|---|
| callback | Function called on each event | Function |
Returns an unsubscribe function that can be called to stop receiving events.
// Subscribe to all AppKit events
const unsubscribe = wallet.subscribeEvents(event => {
const { data } = event;
if (data) {
console.log('Event type:', data.event);
console.log('Event data:', data.properties);
// Track specific events
if (data.event === 'MODAL_OPEN') {
console.log('User opened wallet selection modal');
} else if (data.event === 'MODAL_CLOSE') {
console.log('User closed wallet selection modal');
} else if (data.event === 'CONNECT_SUCCESS') {
console.log('User successfully connected wallet');
}
}
});
// Later: unsubscribe when done
unsubscribe();MODAL_OPEN- Modal openedMODAL_CLOSE- Modal closedSELECT_WALLET- User selected a walletCONNECT_SUCCESS- Connection successfulCONNECT_ERROR- Connection failed
Note: This method can be called before connect(). The subscription will become active after AppKit is initialized.
The connection uses the WalletConnect relay service specified by relayUrl. Network errors may occur occasionally, so dApp developers should handle network errors, connection errors, and timeout errors appropriately.
Refer to the WalletConnect Error Definitions for all error messages and codes.
MIT