Tronwallet Adapter

Overview

Tronwallet Adapter is a set of packages that contain wallet adapters and components for Tron DApps. With out-of-box components and unified methods, developers can easily interact with multiple kinds of wallets, select/connect/disconnect wallets and sign message or transaction.

Adapters

Wallet adapters help you access to TRON wallets with consistent API.

There are many wallets supporting TRON network such as TronLink, Ledger and so on. Different wallets and different versions of one wallet may have different interface to use. The aim of Adapters relavant pacakges is to shield these differences and offer consistent interface for DApp developers. DApps don't need to change their code frequently if they have accessed to the tron wallet dapters code.

For example, if you want to connect to different wallets, you have to use different methods:

// TronLink
window.tronLink.request({ method: 'tron_requestAccounts' });

// Ledger
const transport = await TransportWebHID.create();
const app = new Trx(transport);

// WalletConnect
const wallet = new WalletConnectWallet({
 network: this._config.network,
 options: this._config.options
});

With the adapter, you can use consistent APIs for different wallets:

// TronLink
const tronlinkAdapter = new TronLinkAdapter();
await tronlinkAdapter.connect();
await tronlinkAdapter.signMessage(message);

// Ledger
const ledgerAdapter = new LedgerAdapter();
await ledgerAdapter.connect();
await ledgerAdapter.signMessage(message);

// WalletConnect
const walletconnectAdapter = new WalletConnectAdapter();
await walletconnectAdapter.connect();
await walletconnectAdapter.signMessage(message);

React Hooks

Adapter wallet hooks export a useWallet() hook which manages the global state of wallet, such as current selected wallet and the connection state, address, and so on. It also provides some methods to interact with wallet.

When your dapp supports multiple wallets, with the help of useWallet() hook you can easily:

  • select which wallet to use
  • connect to the selected wallet
  • disconnect to the selected wallet
  • call signMessage or signTransaction of the selected wallet

Examples:

function Comp() {
 const { wallet, address, connected, select, connect, disconnect, signMessage, signTransaction } = useWallet();
 return (
   <div>
     <button onClick={() => select('TronLink')}>Select Wallet</button>
     <button onClick={connect}>Connect</button>
     <button onClick={disconnect}>Disconnect</button>
     <button onClick={() => signMessage('Hello World')}>Sign Message</button>
   </div>
 );
}

React UI Components

useWallet() only contains logic to manage wallet state. Besides, we provide a set of out-of-box components to help you interact with wallets:

  • WalletSelectButton: Show wallets dialog to select a wallet.
  • WalletConnectButton: Connect to the selected wallet.
  • WalletDisconnectButton: Disconnect to the selected wallet.
  • WalletActionButton: A Button with multiple actions include select/connect/disconnect.

You can find react demos here.

Here is the demo image:
demo.png

Wallet Adapters

@tronweb3/tronwallet-adapters provides multiple wallet adapters to help developers connect to Tron wallet like TronLink with consistent API.

Supported Wallets

As @tronweb3/tronwallet-adapters exports adapter of each wallet, you can use this package, or use the individual wallet adapter you want.

Installation

npm install @tronweb3/tronwallet-abstract-adapter @tronweb3/tronwallet-adapters
# or pnpm install @tronweb3/tronwallet-abstract-adapter @tronweb3/tronwallet-adapters
# or yarn add @tronweb3/tronwallet-abstract-adapter @tronweb3/tronwallet-adapters

Usage

React

You can use @tronweb3/tronwallet-adapters in your component. Use useMemo to memorize the adapter to improve your web performance.

import { TronLinkAdapter } from '@tronweb3/tronwallet-adapters';

function App() {
 const [readyState, setReadyState] = useState(WalletReadyState.NotFound);
 const [account, setAccount] = useState('');
 const [netwok, setNetwork] = useState({});
 const [signedMessage, setSignedMessage] = useState('');

 const adapter = useMemo(() => new TronLinkAdapter(), []);
 useEffect(() => {
   setReadyState(adapter.state);
   setAccount(adapter.address!);

   adapter.on('connect', () => {
     setAccount(adapter.address!);
   });

   adapter.on('readyStateChanged', state => {
     setReadyState(state);
   });

   adapter.on('accountsChanged', data => {
     setAccount(data);
   });

   adapter.on('chainChanged', data => {
     setNetwork(data);
   });

   adapter.on('disconnect', () => {
     // when disconnect from wallet
   });
   return () => {
     // remove all listeners when components is destroyed
     adapter.removeAllListeners();
   };
 }, []);

 async function sign() {
   const res = await adapter!.signMessage('helloworld');
   setSignedMessage(res);
 }

 return (
   <div className="App">
     <div>readyState: {readyState}</div>
     <div>current address: {account}</div>
     <div>current network: {JSON.stringify(netwok)}</div>
     <button disabled={adapter.connected} onClick={() => adapter.connect()}>
       Connect to TronLink
     </button>
     <button onClick={sign}>sign message</button>
     <br />
     SignedMessage: {signedMessage}
   </div>
 );
}

Vue

In Vue, as the created/mounted hook just can be executed once, you can init the adapter in mounted or created hook.

// vue2.x
export default {
   created() {
       this.adapter = new TronLinkAdapter();
       this.adapter.on('connect', () => {
           // here you can do something
       });
   },
   beforeDestroy() {
       this.adapter.removeAllListeners();
   }
}

// vue3
export default {
   setup() {
       onMounted(function() {
           const adapter = new TronLinkAdapter();
           adapter.on('connect', () => {
               // here you can do something
           });
       });
       onBeforeUnmount(function() {
           // remove all listeners when components is destroyed
           adapter.removeAllListeners();
       });
       return {};
   }
}

API Reference

Adapter

The Adapter class defines the common interface for all adapters of specified wallets.

Constructor

  • constructor(config): adapter constructor method, an optional config is valid. For detailed config type, refer to the following adapter section.

Properties

  • name: The name of the adapter.
  • url: The website of the adapter's wallet.
  • icon: The icon of the adapter's wallet.
  • readyState: The wallet's state, which includes three value:
  • Loading: When adapter is checking if the wallet is available or not.
  • NotFound: The wallet is not detected in current browser.
  • Found: The wallet is detected in current browser.
  • address: The address of current account when the adapter is connected.
  • connecting: Whether the adapter is trying to connect to the wallet.
  • connected: Whether the adapter is connected to the wallet.

Methods

  • connect(): Promise<void>: connect to the wallet.
  • disconnect(): Promise<void>: disconnect to the wallet.
  • signMessage(message, privateKey?): Promise<string>: sign a string, return the signature result. An optional privateKey can be provided.
  • signTransaction(transaction, privateKey?): sign a transaction, return the signature result of the transaction. An optional privateKey can be provided.
  • multiSign(transaction, privateKey: string | null, permissionId?): sign a multi-sign transaction.
  • If privateKey is not null, will use the privateKey to sign rather than TronLink.
  • If permissionId is not provided, will use 0(OwnerPerssion) as default.
  • Please refer to here for more about Multi-Sign,
  • switchChain(chainId: string): Promise<void>;: request wallet to switch chain by chainId.

Events

Adapter extends the EventEmitter class in eventemitter3 package. So you can listen to the events by adapter.on('connect', function() {}).

Events are as follows:

  • connect(address): Emit when adapter is connected to the wallet. The parameter is the address of current account.
  • disconnect(): Emit when adapter is disconnected to the wallet.
  • readyStateChanged(state: WalletReadyState): Emit when wallet's readyState is changed. The parameter is the state of wallet.
enum WalletReadyState {
  /**
  * Adapter will start to check if wallet exists after adapter instance is created.
  */
  Loading = 'Loading',
  /**
  * When checking ends and wallet is not found, readyState will be NotFound.
  */
  NotFound = 'NotFound',
  /**
  * When checking ends and wallet is found, readyState will be Found.
  */
  Found = 'Found'
}
  • accountsChanged(address: string, preAddress: string): Emit when users change the current selected account in wallet. The parameter is the address of new account.
  • chainChanged(chainInfo: ChainInfo): Emit when users change the current selected chain in wallet. The parameter is the new network config:
interface ChainInfo {
  chainId: string;
}
  • error(WalletError): Emit when there are some errors when call the adapter's method. The [WalletError Types] is defined as follows.

WalletError

WalletError is a superclass which defines the error when using adapter.
All error types are extended from this class.
Developers can check the error type according to the error instance.

try {
 // do something here
} catch (error: WalletError) {
 if (error instanceof WalletNotFoundError) {
   console.log('Wallet is not found');
 }
}

All errors are as follows:

  • WalletNotFoundError: Occurs when wallet is not installed.
  • WalletNotSelectedError: Occurs when connect but there is no selected wallet.
  • WalletDisconnectedError: Occurs when wallet is disconnected. Used by some wallets which won't connect automatically when call signMessage() or signTransaction().
  • WalletConnectionError: Occurs when try to connect a wallet.
  • WalletDisconnectionError: Occurs when try to disconnect a wallet.
  • WalletSignMessageError: Occurs when call signMessage().
  • WalletSignTransactionError: Occurs when call signTransaction().
  • WalletSwitchChainError: Occurs when call switchChain(). Only supported by TronLink.
  • WalletGetNetworkError: Occurs when call network() to get network information.

Following exmaple shows how to get original error info with WalletError:

const adapter = new TronLinkAdapter();
try {
   await adapter.connect();
} catch (e: any) {
   const originalError = e.error;
}

TronLinkAdapter

  • Constructor(config: TronLinkAdapterConfig)
interface TronLinkAdapterConfig {
  /**
  * Set if open Wallet's website url when wallet is not installed.
  * Default is true.
  */
  openUrlWhenWalletNotFound?: boolean;
  /**
  * Timeout in millisecond for checking if TronLink wallet exists.
  * Default is 30 * 1000ms
  */
  checkTimeout?: number;
  /**
  * Set if open TronLink app using DeepLink on mobile device.
  * Default is true.
  */
  openTronLinkAppOnMobile?: boolean;
  /**
  * The icon of your dapp. Used when open TronLink app in mobile device browsers.
  * Default is current website icon.
  */
  dappIcon?: string;
  /**
  * The name of your dapp. Used when open TronLink app in mobile device browsers.
  * Default is `document.title`.
  */
  dappName?: string;
}
  • network() method is supported to get current network information. The type of returned value is Network as follows:

    export enum NetworkType {
        Mainnet = 'Mainnet',
        Shasta = 'Shasta',
        Nile = 'Nile',
        /**
         * When use custom node
         */
        Unknown = 'Unknown',
    }
    
    export type Network = {
        networkType: NetworkType;
        chainId: string;
        fullNode: string;
        solidityNode: string;
        eventServer: string;
    };
    
  • Don't support disconnect by DApp. As TronLinkAdapter doesn't support disconnect by DApp website, call adapter.disconnect() won't disconnect from TronLink extension really.

  • Auto open TronLink app in mobile browser. If developers call connect() method in mobile browser, it will open DApp in TronLink app to get tronlink wallet.

Others adapters
Other adapters Constructor config api can be found in their source code README.

Adapter React Hooks

@tronweb3/tronwallet-adapter-react-hooks provides a useWallet() hook which will make it easy to "Connect Wallet" and listen to the state change for developers.

Installation

npm install @tronweb3/tronwallet-adapter-react-hooks @tronweb3/tronwallet-abstract-adapter @tronweb3/tronwallet-adapters
# or pnpm install @tronweb3/tronwallet-adapter-react-hooks @tronweb3/tronwallet-abstract-adapter @tronweb3/tronwallet-adapters
# or yarn add @tronweb3/tronwallet-adapter-react-hooks @tronweb3/tronwallet-abstract-adapter @tronweb3/tronwallet-adapters

Usage

@tronweb3/tronwallet-adapter-react-hooks uses Context of React to maintain a shared data. So developers need to wrap App content within the WalletProvider.

You can provide a onError callback to handle various errors such as WalletConnectionError, WalletNotFoundError.

import { useWallet, WalletProvider } from '@tronweb3/tronwallet-adapter-react-hooks';
import { WalletDisconnectedError, WalletError, WalletNotFoundError } from '@tronweb3/tronwallet-abstract-adapter';
import toast, { Toaster } from 'react-hot-toast';

function App() {
    // use `react-hot-toast` npm package to notify user what happened here
    function onError(e: WalletError) {
        if (e instanceof WalletNotFoundError) {
            toast.error(e.message);
        } else if (e instanceof WalletDisconnectedError) {
            toast.error(e.message);
        } else toast.error(e.message);
    }
    return (
        <WalletProvider onError={onError}>
            <ConnectComponent></ConnectComponent>
            <Profile></Profile>
        </WalletProvider>
    );
}
function ConnectComponent() {
    const { connect, disconnect, select, connected } = useWallet();
    return (<div>
      <button type="button" onClick={() => select('TronLink Adapter' as any)}> Select TronLink</button>
      <button type="button" disabled={connected} onClick={connect}>Connect</button><br>
      <button type="button" disabled={!connected} onClick={disconnect}>Disconnect</button>
    </div>);
}
function Profile() {
    const { address, connected, wallet } = useWallet();
    return (<div>
        <p> <span>Connection Status:</span> {connected ? 'Connected' : 'Disconnected'}</p>
        <p> <span>Your selected Wallet:</span> {wallet?.adapter.name} </p>
        <p> <span>Your Address:</span> {address} </p>
    </div>);
}

WalletProvider

WalletProvider and useWallet work together like Context.Provider and useContext(). There is a WalletProviderContext underlying which maintains some state and can be obtained with useWallet. So developers need to wrap application components with WalletProvider.

import { useWallet, WalletProvider } from '@tronweb3/tronwallet-adapter-react-hooks';
function App() {
    return <WalletProvider>/* here is application components */</WalletProvider>;
}

Props

adapters:

  • Required: false
  • Type: Adapter[]
  • Default: [ new TronLinkAdapter() ]

Used to specify what wallet adapters are supported. All wallet adapters can be imported from @tronweb3/tronwallet-adapters package or their standalone package.

  • Example
    import { useWallet, WalletProvider } from '@tronweb3/tronwallet-adapter-react-hooks';
    import { TronLinkAdapter } from '@tronweb3/tronwallet-adapters';
    function App() {
        const adapters = useMemo(() => [new TronLinkAdapter()]);
        return <WalletProvider adapters={adapters}>/* here is application components */</WalletProvider>;
    }
    

onError

  • Required: false
  • Type: (error: WalletError): void
  • Default: function(error) { console.error(error); }

Used to handle errors occured when use wallet. Developers can use the callback to tell users what happened according to the error type. All error types can be found here.

  • Example
    functon onError(e) {
    if (e instanceof WalletNotFoundError) {
            console.error(e.message);
        } else if (e instanceof WalletDisconnectedError) {
            console.error(e.message);
        } else console.error(e.message);
    }
    

autoConnect

  • Required: false
  • Type: boolean
  • Default: true

Whether connect to the specified wallet automatically when loading the page and selecting a wallet.

disableAutoConnectOnLoad

  • Required: false
  • Type: boolean
  • Default: false

When autoConnect enabled, whether automatically connect to current selected wallet when loading the page.
If you don't want to connect the wallet when page is first loaded, set disableAutoConnectOnLoad: true.

localStorageKey

  • Required: false
  • Type: string
  • Default: tronAdapterName

Specified the key used to cache wallet name in localStorage. When user select a wallet, applications will cache the wallet name to localStorage.

Event handlers

You can provide event handlers for listen adapter events, such as connect,disconnect,accountsChanged. Available event handlers and their types are as follows:

  • readyStateChanged: (readyState: 'Found' | 'NotFound') => void: Called when current adapter emits readyStateChanged event.
  • onConnect: (address: string) => void: Called when current adapter emits connect event.
  • onDisconnect: () => void: Called when current adapter emits disconnect event.
  • onAccountsChanged: (newAddress: string; preAddress?: string) => void: Called when current adapter emits accountsChanged event.
  • onChainChanged: (chainData: unknow) => void: Called when current adapter emits chainChanged event.

An event handler named onAdapterChanged is also avaliable to get noticed when selected adapter is changed.

  • onAdapterChanged: (adapter: Adapter | null) => void: Called when current adapter is changed.

Here is an example:

import { useWallet, WalletProvider } from '@tronweb3/tronwallet-adapter-react-hooks';
import { TronLinkAdapter } from '@tronweb3/tronwallet-adapters';
function App() {
    const adapters = useMemo(() => [new TronLinkAdapter()]);
    const onAccountsChanged = useCallback((curAddr, preAddr) => {
        console.log('new address is: ', curAddr, ' previous address is: ', preAddr);
    }, []);
    return (
        <WalletProvider adapters={adapters} onAccountsChanged={onAccountsChanged}>
            /* here is application components */
        </WalletProvider>
    );
}

useWallet()

useWallet is a react hook providing a set of properties and methods which can be used to select and connect wallet, get wallet state and so on.

useWallet() must be used in the descendant components of WalletProvider!

ReturnedValue

autoConnect

  • Type: boolean
    Synchronous with autoConnect property passed to WalletProvider.

disableAutoConnectOnLoad

  • Type: boolean
    Synchronous with disableAutoConnectOnLoad property passed to WalletProvider.

wallet

  • Type: Wallet | null
    The wallet current selected. If no wallet is selected, the value is null.

Wallet is defined as follow:

interface Wallet {
    adapter: Adapter; // wallet adapter
    state: AdapterState;
}
enum AdapterState {
    NotFound = 'NotFound',
    Disconnect = 'Disconnected',
    Connected = 'Connected',
}

address

  • Type: string | null
    Address of current selected wallet. If no wallet is selected, the value is null.

wallets

  • Type: Wallet[]
    Wallet list based on current used adapters when initial WalletProvider.

connecting

  • Type: boolean
    Indicate if is connecting to the wallet.

connected

  • Type: boolean
    Indicate if is connected with the wallet.

disconnecting

  • Type: boolean
    Indicate if is connecting to the wallet.

Methods

select

  • Type: (walletAdapterName: AdapterName) => void
    Select a wallet by walletAdapterName. Valid adapters can be found here

connect

  • Type: () => Promise<void>
    Connect to current selected wallet.

disconnect

  • Type: () => Promise<void>
    Disconnect from current selected wallet.

signTransaction

  • Type: (transaction: Transaction) => Promise<SignedTransaction>
    Sign a unsigned transaction. This method is the same as TronWeb API.

signMessage

  • Type: (message: string) => Promise<string>
    Sign a message.

Example

import { useWallet } from '@tronweb3/tronwallet-adapter-react-hooks';
import { AdapterName } from '@tronweb3/tronwallet-abstract-adapter';

function Content() {
    const { connect, disconnect, select, connected } = useWallet();
    return (
        <div>
            <button type="button" onClick={() => select('TronLink Adapter')}>
                Select TronLink
            </button>
            <button type="button" disabled={connected} onClick={connect}>
                Connect
            </button>
            <button type="button" disabled={!connected} onClick={disconnect}>
                Disconnect
            </button>
        </div>
    );
}

Adapter React UI Components

@tronweb3/tronwallet-adapter-react-ui provides a set of out-of-the-box components to make it easy to select, change, connect and disconnect wallet.

This package relies on @tronweb3/tronwallet-adapter-react-hooks for functionality. So developers must wrap App content within the WalletProvider.

Installation

npm install @tronweb3/tronwallet-adapter-react-ui @tronweb3/tronwallet-adapter-react-hooks @tronweb3/tronwallet-abstract-adapter @tronweb3/tronwallet-adapters
# or pnpm install @tronweb3/tronwallet-adapter-react-ui @tronweb3/tronwallet-adapter-react-hooks @tronweb3/tronwallet-abstract-adapter @tronweb3/tronwallet-adapters
# or yarn add @tronweb3/tronwallet-adapter-react-ui @tronweb3/tronwallet-adapter-react-hooks @tronweb3/tronwallet-abstract-adapter @tronweb3/tronwallet-adapters

Usage

@tronweb3/tronwallet-adapter-react-ui provide a Select Wallet Modal by Context.Provider. Developers must wrap App content within the WalletProvider and WalletModalProvider.

import { useWallet, WalletProvider } from '@tronweb3/tronwallet-adapter-react-hooks';
import { WalletModalProvider, WalletActionButton } from '@tronweb3/tronwallet-adapter-react-ui';
import '@tronweb3/tronwallet-adapter-react-ui/style.css';
import { WalletDisconnectedError, WalletError, WalletNotFoundError } from '@tronweb3/tronwallet-abstract-adapter';
import toast, { Toaster } from 'react-hot-toast';

function App() {
 // here use `react-hot-toast` npm package to notify user what happened
 function onError(e: WalletError) {
   if (e instanceof WalletNotFoundError) {
     toast.error(e.message);
   } else if (e instanceof WalletDisconnectedError) {
     toast.error(e.message);
   } else toast.error(e.message);
 }
 return (
   <WalletProvider onError={onError}>
     <WalletModalProvider>
       <ConnectComponent></ConnectComponent>
       <Profile></Profile>
     </WalletModalProvider>
   </WalletProvider>
 );
}
function ConnectComponent() {
 const { connect, disconnect, select, connected } = useWallet();
 return <WalletActionButton></WalletActionButton>;
}
function Profile() {
 const { address, connected, wallet } = useWallet();
 return (
   <div>
     <p>
       <span>Connection Status:</span> {connected ? 'Connected' : 'Disconnected'}
     </p>
     <p>
       <span>Your selected Wallet:</span> {wallet?.adapter.name}
     </p>
     <p>
       <span>Your Address:</span> {address}
     </p>
   </div>
 );
}

API Reference

WalletModalProvider and useWalletModal

WalletModalProvider provide a Select Wallet Modal by Context.Provider. The modal can be controled by useWalletModal.

function App() {
 const { visible, setVisible } = useWalletModal();
 function toggle() {
   setVisible(visible => !visible);
 }
 return (
   <div>
     <button onClick={toggle}>{visible ? 'Close Modal' : 'Open Modal'}</button>
   </div>
 );
}

WalletConnectButton

Button to connect to the selected wallet. The button is disabled when:

  • no wallet is selected
  • is connecting to wallet
  • is connected
  • disabled by props

Props

type ButtonProps = PropsWithChildren<{
 className?: string,
 disabled?: boolean,
 onClick?: (e: MouseEvent<HTMLButtonElement>) => void,
 style?: CSSProperties,
 tabIndex?: number,
 icon?: string
}>;

WalletDisconnectButton

Button to connect to the selected wallet. The button is disabled when:

  • no wallet is selected
  • is connecting to wallet
  • disabled by props

Props

Same as WalletConnectButton.

WalletSelectButton

Button to open Select Wallet Modal.

Props

Same as WalletConnectButton.

WalletActionButton

Button with multiple functions including:

  • Select wallet
  • Connect to wallet
  • Disconnect from wallet
  • Show current selected wallet and address
  • Copy address

It's recommended to use this component to connect wallet easily.
Here is the demo:
example

Props

Same as WalletConnectButton.

Vue Hooks

@tronweb3/tronwallet-adapter-vue-hooks provides a useWallet() hook which will make it easy to "Connect Wallet" and listen to the state change for developers.

Installation

npm install @tronweb3/tronwallet-adapter-vue-hooks @tronweb3/tronwallet-abstract-adapter @tronweb3/tronwallet-adapters
# or pnpm install @tronweb3/tronwallet-adapter-vue-hooks @tronweb3/tronwallet-abstract-adapter @tronweb3/tronwallet-adapters
# or yarn install @tronweb3/tronwallet-adapter-vue-hooks @tronweb3/tronwallet-abstract-adapter @tronweb3/tronwallet-adapters

Usage

@tronweb3/tronwallet-adapter-vue-hooks uses Provide / Inject in Vue to maintain a shared data. So developers need to wrap App content within the WalletProvider.

You can provide a error event listener to handle various errors such as WalletConnectionError, WalletNotFoundError.

Here is a Demo project;

<script setup>
    import { defineComponent, h } from 'vue';
    import { WalletProvider, useWallet } from '@tronweb3/tronwallet-adapter-vue-hooks';
    import { TronLinkAdapter } from '@tronweb3/tronwallet-adapters';
    const tronLink = new TronLinkAdapter();

    const adapters = [tronLink];

    function onConnect(address) {
        console.log('[wallet hooks] onConnect: ', address);
    }
    function onDisconnect() {
        console.log('[wallet hooks] onDisconnect');
    }

    const VueComponent = defineComponent({
        setup() {
            // Here you can use `useWallet` API
            const { wallet, connect, signMessage, signTransaction } = useWallet();
            return () =>
                h('div', [
                    h('div', { style: 'color: #222;' }, `Current Adapter: ${(wallet && wallet.adapter.name) || ''}`),
                ]);
        },
    });
</script>

<template>
    <WalletProvider :adapters="adapters" @connect="onConnect" @disconnect="onDisconnect">
        <VueComponent />
    </WalletProvider>
</template>

WalletProvider

WalletProvider and useWallet work together. WalletProvider use provide() in Vue to provide a shared state. useWallet use inject() to get the shared state. Developers need to wrap application components with WalletProvider.

<html>
    <WalletProvider>/* here is application components */</WalletProvider>
</html>
<script setup>
    import { useWallet, WalletProvider } from '@tronweb3/tronwallet-adapter-vue-hooks';
</script>

Props

adapters:

  • Required: false
  • Type: Adapter[]
  • Default: [ new TronLinkAdapter() ]

Used to specify what wallet adapters are supported. All wallet adapters can be imported from @tronweb3/tronwallet-adapters package or their standalone package.

  • Example
    <template>
        <WalletProvider :adapters="adapters">/* here is application components */</WalletProvider>
    </template>
    <script setup>
        import { useWallet, WalletProvider } from '@tronweb3/tronwallet-adapter-vue-hooks';
        import { TronLinkAdapter } from '@tronweb3/tronwallet-adapters';
        const adapters = [new TronLinkAdapter()];
    </script>
    

autoConnect

  • Required: false
  • Type: boolean
  • Default: true

Whether connect to the specified wallet automatically after a wallet is selected.

disableAutoConnectOnLoad

  • Required: false
  • Type: boolean
  • Default: false

Whether automatically connect to current selected wallet after the page is loaded when autoConnect enabled.
If you don't want to connect the wallet when page is first loaded, set disableAutoConnectOnLoad: true.

localStorageKey

  • Required: false
  • Type: string
  • Default: tronAdapterName

Specified the key used to cache wallet name in localStorage. When user select a wallet, applications will cache the wallet name to localStorage.

Events

You can provide event handlers for listen adapter events, such as connect,disconnect,accountsChanged. Available events and their types are as follows:

  • readyStateChanged: (readyState: 'Found' | 'NotFound') => void: Emits when current adapter emits readyStateChanged event.
  • connect: (address: string) => void: Emits when current adapter emits connect event.
  • disconnect: () => void: Emits when current adapter emits disconnect event.
  • accountsChanged: (newAddress: string; preAddress?: string) => void: Emits when current adapter emits accountsChanged event.
  • chainChanged: (chainData: unknow) => void: Emits when current adapter emits chainChanged event.
  • error: (error) => void: Emits when occurs error in methods calls.

An event named adapterChanged is also avaliable to get noticed when selected adapter is changed.

  • adapterChanged: (adapter: Adapter | undefined) => void: Called when current adapter is changed.

Here is an example:

```html
<template>
    <WalletProvider :adapters="adapters" @accountsChanged="onAccountsChanged">/* here is application components */</WalletProvider>
</template>
<script setup>
    import { useWallet, WalletProvider } from '@tronweb3/tronwallet-adapter-vue-hooks';
    import { TronLinkAdapter } from '@tronweb3/tronwallet-adapters';
    const adapters = [new TronLinkAdapter()];

    function onAccountsChanged(curAddress, preAddress) {}
</script>
```

useWallet()

useWallet is a react hook providing a set of properties and methods which can be used to select and connect wallet, get wallet state and so on.

useWallet() must be used in the descendant components of WalletProvider!

ReturnedValue

autoConnect

  • Type: ComputedRef<boolean>
    Synchronous with autoConnect property passed to WalletProvider.

disableAutoConnectOnLoad

  • Type: ComputedRef<boolean>
    Synchronous with disableAutoConnectOnLoad property passed to WalletProvider.

wallet

  • Type: ComputedRef<Wallet | null>
    The wallet current selected. If no wallet is selected, the value is null.

Wallet is defined as follow:

interface Wallet {
    adapter: Adapter; // wallet adapter
    state: AdapterState;
}
enum AdapterState {
    NotFound = 'NotFound',
    Disconnect = 'Disconnected',
    Connected = 'Connected',
}

address

  • Type: ComputedRef<string | null>
    Address of current selected wallet. If no wallet is selected, the value is null.

wallets

  • Type: Ref<Wallet[]>
    Wallet list based on current used adapters when initial WalletProvider.

connecting

  • Type: Ref<boolean>
    Indicate if is connecting to the wallet.

connected

  • Type: Ref<boolean>
    Indicate if is connected with the wallet.

disconnecting

  • Type: Ref<boolean>
    Indicate if is connecting to the wallet.

Methods

select

  • Type: (walletAdapterName: AdapterName) => void
    Select a wallet by walletAdapterName. Valid adapters can be found here

connect

  • Type: () => Promise<void>
    Connect to current selected wallet.

disconnect

  • Type: () => Promise<void>
    Disconnect from current selected wallet.

signTransaction

  • Type: (transaction: Transaction) => Promise<SignedTransaction>
    Sign a unsigned transaction. This method is the same as TronWeb API.

signMessage

  • Type: (message: string) => Promise<string>
    Sign a message.

Example

<template>
    <div>
        <button type="button" @click="() => select('TronLink Adapter')">Select TronLink</button>
        <button type="button" :disabled="connected" @click="connect">Connect</button>
        <button type="button" :disabled="!connected" @click="disconnect">Disconnect</button>
    </div>
</template>
<script setup>
    import { useWallet } from '@tronweb3/tronwallet-adapter-vue-hooks';
    import { AdapterName } from '@tronweb3/tronwallet-abstract-adapter';

    const { connect, disconnect, select, connected } = useWallet();
</script>

Adapter Vue UI Components

@tronweb3/tronwallet-adapter-vue-ui provides a set of out-of-the-box components to make it easy to select, change, connect and disconnect wallet.

@tronweb3/tronwallet-adapter-vue-ui depends on @tronweb3/tronwallet-adapter-vue-hooks to work. So developers must wrap App content within the WalletProvider.

Installation

npm install @tronweb3/tronwallet-adapter-vue-ui @tronweb3/tronwallet-adapter-vue-hooks @tronweb3/tronwallet-abstract-adapter @tronweb3/tronwallet-adapters

# or pnpm install @tronweb3/tronwallet-adapter-vue-ui @tronweb3/tronwallet-adapter-vue-hooks @tronweb3/tronwallet-abstract-adapter @tronweb3/tronwallet-adapters

# or yarn install @tronweb3/tronwallet-adapter-vue-ui @tronweb3/tronwallet-adapter-vue-hooks @tronweb3/tronwallet-abstract-adapter @tronweb3/tronwallet-adapters

Usage

@tronweb3/tronwallet-adapter-vue-ui provide a Select Wallet Modal by provide() in Vue. So developers must wrap App content within the WalletProvider and WalletModalProvider.

Note: A stylesheet must be imported to make components work fine.

Here is a Demo project;

<template>
    <WalletProvider @error="onError">
        <WalletModalProvider>
            <WalletActionButton></WalletActionButton>
            <Profile></Profile>
        </WalletModalProvider>
    </WalletProvider>
</template>
<script setup>
    import { h, defineComponent } from 'vue';
    import { useWallet, WalletProvider } from '@tronweb3/tronwallet-adapter-vue-hooks';
    import { WalletModalProvider, WalletActionButton } from '@tronweb3/tronwallet-adapter-vue-ui';
    // This is necessary to keep style normal.
    import '@tronweb3/tronwallet-adapter-vue-ui/style.css';
    import { WalletDisconnectedError, WalletError, WalletNotFoundError } from '@tronweb3/tronwallet-abstract-adapter';

    function onError(e: WalletError) {
        if (e instanceof WalletNotFoundError) {
            console.error(e.message);
        } else if (e instanceof WalletDisconnectedError) {
            console.error(e.message);
        } else console.error(e.message);
    }

    const ConnectComponent = defineComponent({
        setup() {
            return () => h(WalletActionButton);
        },
    });

    const Profile = defineComponent({
        setup() {
            const { wallet } = useWallet();
            return () => h('div', `Current adapter: ${wallet?.adapter.name}`);
        },
    });
</script>

WalletModalProvider and useWalletModal

WalletModalProvider provide a Select Wallet Modal by provide() in Vue. The modal can be controled by useWalletModal.

<template>
    <div>
        <button @click="toggle">{{visible ? 'Close Modal' : 'Open Modal'}}</button>
    </div>
</template>
<script setup>
    const { visible, setVisible } = useWalletModal();
    function toggle() {
        setVisible((visible) => !visible);
    }
</script>

WalletConnectButton

Button to connect to the selected wallet. The button is disabled when:

  • no wallet is selected
  • is connecting to wallet
  • is connected
  • disabled by props

Props

type ButtonProps = PropsWithChildren<{
    className?: string,
    disabled?: boolean,
    onClick?: (e: MouseEvent<HTMLButtonElement>) => void,
    style?: CSSProperties,
    tabIndex?: number,
    icon?: string,
}>;

WalletDisconnectButton

Button to connect to the selected wallet. The button is disabled when:

  • no wallet is selected
  • is connecting to wallet
  • disabled by props

Props

Same as WalletConnectButton.

WalletSelectButton

Button to open Select Wallet Modal.

Props

Same as WalletConnectButton.

WalletActionButton

Button with multiple functions including:

  • Select wallet
  • Connect to wallet
  • Disconnect from wallet
  • Show current selected wallet and address
  • Copy address

It's recommended to use this component to connect wallet easily.
example

Props

Same as WalletConnectButton.