2.0.2 • Published 12 days ago

@tonconnect/ui v2.0.2

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
12 days ago

TON Connect UI

TonConnect UI is a UI kit for TonConnect SDK. Use it to connect your app to TON wallets via TonConnect protocol.

If you use React for your dapp, take a look at TonConnect UI React kit.

If you want to use TonConnect on the server side, you should use the TonConnect SDK.

You can find more details and the protocol specification in the docs.


Latest API documentation

Getting started

Installation with cdn

Add the script to your HTML file:

<script src="https://unpkg.com/@tonconnect/ui@latest/dist/tonconnect-ui.min.js"></script>

ℹ️ If you don't want auto-update the library, pass concrete version instead of latest, e.g.

<script src="https://unpkg.com/@tonconnect/ui@0.0.9/dist/tonconnect-ui.min.js"></script>

You can find TonConnectUI in global variable TON_CONNECT_UI, e.g.

<script>
    const tonConnectUI = new TON_CONNECT_UI.TonConnectUI({
        manifestUrl: 'https://<YOUR_APP_URL>/tonconnect-manifest.json',
        buttonRootId: '<YOUR_CONNECT_BUTTON_ANCHOR_ID>'
    });
</script>

Installation with npm

npm i @tonconnect/ui

Usage

Create TonConnectUI instance

import TonConnectUI from '@tonconnect/ui'

const tonConnectUI = new TonConnectUI({
    manifestUrl: 'https://<YOUR_APP_URL>/tonconnect-manifest.json',
    buttonRootId: '<YOUR_CONNECT_BUTTON_ANCHOR_ID>'
});

See all available options:

TonConnectUiOptionsWithManifest

TonConnectUiOptionsWithConnector

Change options if needed

tonConnectUI.uiOptions = {
    language: 'ru',
    uiPreferences: {
        theme: THEME.DARK
    }
};

UI element will be rerendered after assignation. You should pass only options that you want to change. Passed options will be merged with current UI options. Note, that you have to pass object to tonConnectUI.uiOptions to keep reactivity.

DON'T do this:

/* WRONG, WILL NOT WORK */ tonConnectUI.uiOptions.language = 'ru'; 

See all available options

Fetch wallets list

const walletsList = await tonConnectUI.getWallets();

/* walletsList is 
{
    name: string;
    imageUrl: string;
    tondns?: string;
    aboutUrl: string;
    universalLink?: string;
    deepLink?: string;
    bridgeUrl?: string;
    jsBridgeKey?: string;
    injected?: boolean; // true if this wallet is injected to the webpage
    embedded?: boolean; // true if the dapp is opened inside this wallet's browser
}[] 
 */

or

const walletsList = await TonConnectUI.getWallets();

Call connect

"TonConnect UI connect button" (which is added at buttonRootId) automatically handles clicks and calls connect. But you are still able to open "connect modal" programmatically, e.g. after click on your custom connect button.

const connectedWallet = await tonConnectUI.connectWallet();

If there is an error while wallet connecting, TonConnectUIError or TonConnectError will be thrown depends on situation.

Get current connected Wallet and WalletInfo

You can use special getters to read current connection state. Note that this getter only represents current value, so they are not reactive. To react and handle wallet changes use onStatusChange mathod.

    const currentWallet = tonConnectUI.wallet;
    const currentWalletInfo = tonConnectUI.walletInfo;
    const currentAccount = tonConnectUI.account;
    const currentIsConnectedStatus = tonConnectUI.connected;

Subscribe to the connection status changes

const unsubscribe = tonConnectUI.onStatusChange(
    walletAndwalletInfo => {
        // update state/reactive variables to show updates in the ui
    } 
);

// call `unsubscribe()` later to save resources when you don't need to listen for updates anymore.

Disconnect wallet

Call to disconnect the wallet.

await tonConnectUI.disconnect();

Send transaction

Wallet must be connected when you call sendTransaction. Otherwise, an error will be thrown.

const transaction = {
    validUntil: Math.floor(Date.now() / 1000) + 60, // 60 sec
    messages: [
        {
            address: "EQBBJBB3HagsujBqVfqeDUPJ0kXjgTPLWPFFffuNXNiJL0aA",
            amount: "20000000",
         // stateInit: "base64bocblahblahblah==" // just for instance. Replace with your transaction initState or remove
        },
        {
            address: "EQDmnxDMhId6v1Ofg_h5KR5coWlFG6e86Ro3pc7Tq4CA0-Jn",
            amount: "60000000",
         // payload: "base64bocblahblahblah==" // just for instance. Replace with your transaction payload or remove
        }
    ]
}

try {
    const result = await tonConnectUI.sendTransaction(transaction);

    // you can use signed boc to find the transaction 
    const someTxData = await myAppExplorerService.getTransaction(result.boc);
    alert('Transaction was sent successfully', someTxData);
} catch (e) {
    console.error(e);
}

sendTransaction will automatically render informational modals and notifications. You can change its behaviour:

const result = await tonConnectUI.sendTransaction(defaultTx, {
    modals: ['before', 'success', 'error'],
    notifications: ['before', 'success', 'error']
});

Default configuration is:

const defaultBehaviour = {
    modals: ['before'],
    notifications: ['before', 'success', 'error']
}

You can also modify this behaviour for all actions calls using uiOptions setter:

tonConnectUI.uiOptions = {
        actionsConfiguration: {
            modals: ['before', 'success', 'error'],
            notifications: ['before', 'success', 'error']
        }
    };

Universal links redirecting issues (IOS)

Some operating systems, and especially iOS, have restrictions related to universal link usage. For instance, if you try to open a universal link on an iOS device via window.open, you can face the following problem: the mobile browser won't redirect the user to the wallet app and will open the fallback tab instead. That's because universal links can only be opened synchronously after a user's action in the browser (button click/...). This means that you either can't perform any asynchronous requests after the user clicks an action button in your dapp, either you can't redirect the user to the connected wallet on some devices.

So, by default, if the user's operating system is iOS, they won't be automatically redirected to the wallet after the dapp calls tonConnectUI.sendTransaction. You can change this behavior using the skipRedirectToWallet option:

const result = await tonConnectUI.sendTransaction(defaultTx, {
    modals: ['before', 'success', 'error'],
    notifications: ['before', 'success', 'error'],
    skipRedirectToWallet: 'ios' //'ios' (default), or 'never', or 'always'
});
tonConnectUI.uiOptions = {
        actionsConfiguration: {
            skipRedirectToWallet: 'ios'
        }
    };
// use skipRedirectToWallet: 'never' for better UX
const onClick = async ()  => {
    const txBody = packTxBodySynchrone();
    tonConnectUI.sendTransaction(txBody, { skipRedirectToWallet: 'never' });

    const myApiResponse = await notifyBackend();
    //...
}
// DON'T use skipRedirectToWallet: 'never', you should use skipRedirectToWallet: 'ios' 
const onClick = async ()  => {
    const myApiResponse = await notifyBackend();
    
    const txBody = packTxBodySynchrone();
    tonConnectUI.sendTransaction(txBody, { skipRedirectToWallet: 'ios' });
    //...
}

Add the return strategy

Return strategy (optional) specifies return strategy for the deeplink when user signs/declines the request.

'back' (default) means return to the app which initialized deeplink jump (e.g. browser, native app, ...), 'none' means no jumps after user action; a URL: wallet will open this URL after completing the user's action. Note, that you shouldn't pass your app's URL if it is a webpage. This option should be used for native apps to work around possible OS-specific issues with 'back' option.

You can set it globally with uiOptions setter, and it will be applied for connect request and all subsequent actions (send transaction/...).

tonConnectUI.uiOptions = {
        actionsConfiguration: {
            returnStrategy: 'none'
        }
    };

Or you can set it directly when you send a transaction (will be applied only for this transaction request)

const result = await tonConnectUI.sendTransaction(defaultTx, {
    returnStrategy: '<protocol>://<your_return_url>' // Note, that you shouldn't pass your app's URL if it is a webpage.
     // This option should be used for native apps to work around possible OS-specific issues with 'back' option.
});

Use inside TWA (Telegram web app)

TonConnect UI will work in TWA in the same way as in a regular website! Basically, no changes are required from the dApp's developers. The only thing you have to set is a dynamic return strategy.

Currently, it is impossible for TWA-wallets to redirect back to previous opened TWA-dApp like native wallet-apps do. It means, that you need to specify the return strategy as a link to your TWA that will be only applied if the dApp is opened in TWA mode.

tonConnectUI.uiOptions = {
        twaReturnUrl: 'https://t.me/durov'
    };

In other words,

if (isLinkToTelegram()) {
    if (isInTWA()) {
        FINAL_RETURN_STRATEGY = actionsConfiguration.twaReturnUrl || actionsConfiguration.returnStrategy;
    } else {
        FINAL_RETURN_STRATEGY = 'none';
    }
} else {
    FINAL_RETURN_STRATEGY = actionsConfiguration.returnStrategy;
}

Detect end of the connection restoring process

Before restoring previous connected wallet TonConnect has to set up SSE connection with bridge, so you have to wait a little while connection restoring. If you need to update your UI depending on if connection is restoring, you can use tonConnectUI.connectionRestored promise.

Promise that resolves after end of th connection restoring process (promise will fire after onStatusChange, so you can get actual information about wallet and session after when promise resolved). Resolved value true/false indicates if the session was restored successfully.

tonConnectUI.connectionRestored.then(restored => {
    if (restored) {
        console.log(
            'Connection restored. Wallet:',
            JSON.stringify({
                ...tonConnectUI.wallet,
                ...tonConnectUI.walletInfo
            })
        );
    } else {
        console.log('Connection was not restored.');
    }
});

UI customisation

TonConnect UI provides an interface that should be familiar and recognizable to the user when using various apps. However, the app developer can make changes to this interface to keep it consistent with the app interface.

Customise UI using tonconnectUI.uiOptions

All such updates are reactive -- change tonconnectUI.uiOptions and changes will be applied immediately.

See all available options

Change border radius

There are three border-radius modes: 'm', 's' and 'none'. Default is 'm'. You can change it via tonconnectUI.uiOptions, or set on tonConnectUI creating:

/* Pass to the constructor */
const tonConnectUI = new TonConnectUI({
    manifestUrl: 'https://<YOUR_APP_URL>/tonconnect-manifest.json',
    uiPreferences: {
        borderRadius: 's'
    }
});


/* Or update dynamically */
tonConnectUI.uiOptions = {
        uiPreferences: {
            borderRadius: 's'
        }
    };

Note, that uiOptions is a setter which will merge new options with previous ones. So you doesn't need to merge it explicitly. Just pass changed options.

/* DON'T DO THIS. SEE DESCRIPTION ABOVE */
tonConnectUI.uiOptions = {
        ...previousUIOptions,
        uiPreferences: {
            borderRadius: 's'
        }
    };

/* Just pass changed property */
tonConnectUI.uiOptions = {
    uiPreferences: {
        borderRadius: 's'
    }
};

Change theme

You can set fixed theme: 'THEME.LIGHT' or 'THEME.DARK', or use system theme. Default theme is system.

import { THEME } from '@tonconnect/ui';

tonConnectUI.uiOptions = {
        uiPreferences: {
            theme: THEME.DARK
        }
    };

You also can set 'SYSTEM' theme:

tonConnectUI.uiOptions = {
        uiPreferences: {
            theme: 'SYSTEM'
        }
    };

You can set theme in the constructor if needed:

import { THEME } from '@tonconnect/ui';

const tonConnectUI = new TonConnectUI({
    manifestUrl: 'https://<YOUR_APP_URL>/tonconnect-manifest.json',
    uiPreferences: {
        theme: THEME.DARK
    }
});

Change colors scheme

You can redefine all colors scheme for each theme or change some colors. Just pass colors that you want to change.

tonConnectUI.uiOptions = {
        uiPreferences: {
            colorsSet: {
                [THEME.DARK]: {
                    connectButton: {
                        background: '#29CC6A'
                    }
                }
            }
        }
    };

You can change colors for both themes at the same time:

tonConnectUI.uiOptions = {
        uiPreferences: {
            colorsSet: {
                [THEME.DARK]: {
                    connectButton: {
                        background: '#29CC6A'
                    }
                },
                [THEME.LIGHT]: {
                    text: {
                        primary: '#FF0000'
                    }
                }
            }
        }
    };

You can set colors scheme in the constructor if needed:

import { THEME } from '@tonconnect/ui';

const tonConnectUI = new TonConnectUI({
    manifestUrl: 'https://<YOUR_APP_URL>/tonconnect-manifest.json',
    uiPreferences: {
        colorsSet: {
            [THEME.DARK]: {
                connectButton: {
                    background: '#29CC6A'
                }
            }
        }
    }
});

See all available options

Combine options

It is possible to change all required options at the same time:

tonConnectUI.uiOptions = {
        uiPreferences: {
            theme: THEME.DARK,
            borderRadius: 's',
            colorsSet: {
                [THEME.DARK]: {
                    connectButton: {
                        background: '#29CC6A'
                    }
                },
                [THEME.LIGHT]: {
                    text: {
                        primary: '#FF0000'
                    }
                }
            }
        }
    };

Direct css customisation

It is not recommended to customise TonConnect UI elements via css as it may confuse the user when looking for known and familiar UI elements such as connect button/modals. However, it is possible if needed. You can add css styles to the specified selectors of the UI element. See list of selectors in the table below:

UI components:

ElementSelectorElement description
Connect wallet modal container[data-tc-wallets-modal-container="true"]Container of the modal window that opens when you click on the "connect wallet" button.
Mobile universal modal page content[data-tc-wallets-modal-universal-mobile="true"]Content of the general mobile modal page with horizontal list.
Desktop universal modal page content[data-tc-wallets-modal-universal-desktop="true"]Content of the universal desktop modal page with QR.
Mobile selected wallet's modal page[data-tc-wallets-modal-connection-mobile="true"]Content of the selected wallet's modal page on mobile.
Desktop selected wallet's modal page[data-tc-wallets-modal-connection-desktop="true"]Content of the selected wallet's modal page on desktop.
Wallets list modal page[data-tc-wallets-modal-list="true"]Content of the modal page with all available wallets list (desktop and mobile).
Info modal page[data-tc-wallets-modal-info="true"]Content of the modal page with "What is a wallet information".
Action modal container[data-tc-actions-modal-container="true"]Container of the modal window that opens when you call sendTransaction or other action.
Confirm action modal content[data-tc-confirm-modal="true"]Content of the modal window asking for confirmation of the action in the wallet.
"Transaction sent" modal content[data-tc-transaction-sent-modal="true"]Content of the modal window informing that the transaction was successfully sent.
"Transaction canceled" modal content[data-tc-transaction-canceled-modal="true"]Content of the modal window informing that the transaction was not sent.
"Connect Wallet" button[data-tc-connect-button="true"]"Connect Wallet" button element.
Wallet menu loading button[data-tc-connect-button-loading="true"]Button element which appears instead of "Connect Wallet" and dropdown menu buttons while restoring connection process
Wallet menu dropdown button[data-tc-dropdown-button="true"]Wallet menu button -- host of the dropdown wallet menu (copy address/disconnect).
Wallet menu dropdown container[data-tc-dropdown-container="true"]Container of the dropdown that opens when you click on the "wallet menu" button with ton address.
Wallet menu dropdown content[data-tc-dropdown="true"]Content of the dropdown that opens when you click on the "wallet menu" button with ton address.
Notifications container[data-tc-list-notifications="true"]Container of the actions notifications.
Notification confirm[data-tc-notification-confirm="true"]Confirmation notification element.
Notification tx sent[data-tc-notification-tx-sent="true"]Transaction sent notification element.
Notification cancelled tx[data-tc-notification-tx-cancelled="true"]Cancelled transaction notification element.

Basic UI elements:

ElementSelector
Button[data-tc-button="true"]
Icon-button[data-tc-icon-button="true"]
Modal window[data-tc-modal="true"]
Notification[data-tc-notification="true"]
Tab bar[data-tc-tab-bar="true"]
H1[data-tc-h1="true"]
H2[data-tc-h2="true"]
H3[data-tc-h3="true"]
Text[data-tc-text="true"]
Wallet-item[data-tc-wallet-item="true"]

Customize the list of displayed wallets

You can customize the list of displayed wallets: change order, exclude wallets or add custom wallets.

Extend wallets list

Pass custom wallets array to extend the wallets list. Passed wallets will be added to the end of the original wallets list.

You can define custom wallet with jsBridgeKey (wallet = browser extension or there is a wallet dapp browser) or with bridgeUrl and universalLink pair (for http-connection compatible wallets), or pass all of these properties.

import { UIWallet } from '@tonconnect/ui';

const customWallet: UIWallet = {
    name: '<CUSTOM_WALLET_NAME>',
    imageUrl: '<CUSTOM_WALLET_IMAGE_URL>',
    aboutUrl: '<CUSTOM_WALLET_ABOUT_URL>',
    jsBridgeKey: '<CUSTOM_WALLET_JS_BRIDGE_KEY>',
    bridgeUrl: '<CUSTOM_WALLET_HTTP_BRIDGE_URL>',
    universalLink: '<CUSTOM_WALLET_UNIVERSAL_LINK>'
};

tonConnectUI.uiOptions = {
    walletsListConfiguration: {
        includeWallets: [customWallet]
    }
}

Add connect request parameters (ton_proof)

Use tonConnectUI.setConnectRequestParameters function to pass your connect request parameters.

This function takes one parameter:

Set state to 'loading' while you are waiting for the response from your backend. If user opens connect wallet modal at this moment, he will see a loader.

tonConnectUI.setConnectRequestParameters({
    state: 'loading'
});

or

Set state to 'ready' and define tonProof value. Passed parameter will be applied to the connect request (QR and universal link).

tonConnectUI.setConnectRequestParameters({
    state: 'ready',
    value: {
        tonProof: '<your-proof-payload>'
    }
});

or

Remove loader if it was enabled via state: 'loading' (e.g. you received an error instead of a response from your backend). Connect request will be created without any additional parameters.

tonConnectUI.setConnectRequestParameters(null);

You can call tonConnectUI.setConnectRequestParameters multiple times if your tonProof payload has bounded lifetime (e.g. you can refresh connect request parameters every 10 minutes).

// enable ui loader
tonConnectUI.setConnectRequestParameters({ state: 'loading' });

// fetch you tonProofPayload from the backend
const tonProofPayload: string | null = await fetchTonProofPayloadFromBackend();

if (!tonProofPayload) {
    // remove loader, connect request will be without any additional parameters
    tonConnectUI.setConnectRequestParameters(null);
} else {
    // add tonProof to the connect request
    tonConnectUI.setConnectRequestParameters({
        state: "ready",
        value: { tonProof: tonProofPayload }
    });
}

You can find ton_proof result in the wallet object when wallet will be connected:

tonConnectUI.onStatusChange(wallet => {
        if (wallet && wallet.connectItems?.tonProof && 'proof' in wallet.connectItems.tonProof) {
            checkProofInYourBackend(wallet.connectItems.tonProof.proof);
        }
    });
2.0.3-beta.0

12 days ago

2.0.2

28 days ago

2.0.2-beta.0

29 days ago

2.0.2-beta.1

28 days ago

2.0.1

29 days ago

2.0.1-beta.8

1 month ago

2.0.1-beta.7

1 month ago

2.0.1-beta.6

1 month ago

2.0.1-beta.5

1 month ago

2.0.1-beta.4

2 months ago

2.0.1-beta.2

2 months ago

2.0.1-beta.3

2 months ago

2.0.1-beta.1

3 months ago

2.0.1-beta.0

4 months ago

2.0.0

5 months ago

2.0.0-beta.10

5 months ago

2.0.0-beta.9

5 months ago

2.0.0-beta.8

6 months ago

2.0.0-beta.7

6 months ago

2.0.0-beta.2

8 months ago

2.0.0-beta.1

8 months ago

2.0.0-beta.0

9 months ago

2.0.0-beta.6

7 months ago

2.0.0-beta.5

7 months ago

2.0.0-beta.4

7 months ago

2.0.0-beta.3

7 months ago

1.0.0-beta.6

9 months ago

1.0.0-beta.7

9 months ago

1.0.0-beta.5

1 year ago

1.0.0-beta.4

1 year ago

1.0.0-beta.2

1 year ago

1.0.0-beta.3

1 year ago

1.0.0-beta.0

1 year ago

1.0.0-beta.1

1 year ago

0.0.17

1 year ago

0.0.16

1 year ago

0.0.15

1 year ago

0.0.14

1 year ago

0.0.13

1 year ago

0.0.12

1 year ago

0.0.11

1 year ago

0.0.10

1 year ago

0.0.9

1 year ago

0.0.8

1 year ago

0.0.7

1 year ago

0.0.6

1 year ago

0.0.5

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago