Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@tonconnect/ui

Package Overview
Dependencies
Maintainers
3
Versions
72
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@tonconnect/ui

⚠️ **API is work in progress right now. Don't use this package in production.**

  • 0.0.9
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
21K
decreased by-29.79%
Maintainers
3
Weekly downloads
 
Created
Source

TON Connect UI

⚠️ API is work in progress right now. Don't use this package in production.

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: Date.now() + 1000000,
    messages: [
        {
            address: "0:412410771DA82CBA306A55FA9E0D43C9D245E38133CB58F1457DFB8D5CD8892F",
            amount: "20000000",
            stateInit: "base64bocblahblahblah==" // just for instance. Replace with your transaction initState or remove
        },
        {
            address: "0:E69F10CC84877ABF539F83F879291E5CA169451BA7BCE91A37A5CED3AB8080D3",
            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']
}

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:

ElementSelectorElement description
Connect wallet modal container#tc-wallets-modal-containerContainer of the modal window that opens when you click on the "connect wallet" button.
Select wallet modal content#tc-wallets-modalContent of the modal window with wallet selection.
QR-code modal content#tc-qr-modalContent of the modal window with QR-code.
Action modal container#tc-actions-modal-containerContainer of the modal window that opens when you call sendTransaction or other action.
Confirm action modal content#tc-confirm-modalContent of the modal window asking for confirmation of the action in the wallet.
"Transaction sent" modal content#tc-transaction-sent-modalContent of the modal window informing that the transaction was successfully sent.
"Transaction canceled" modal content#tc-transaction-canceled-modalContent of the modal window informing that the transaction was not sent.
"Connect Wallet" button#tc-connect-button"Connect Wallet" button element.
Wallet menu dropdown button#tc-dropdown-buttonWallet menu button -- host of the dropdown wallet menu (copy address/disconnect).
Wallet menu dropdown container#tc-dropdown-containerContainer of the dropdown that opens when you click on the "wallet menu" button with ton address.
Wallet menu dropdown content#tc-dropdownContent of the dropdown that opens when you click on the "wallet menu" button with ton address.
Notifications container#tc-notificationsContainer of the actions notifications.

Customize the list of displayed wallets

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

Redefine wallets list

Pass an array of the wallet's names and custom wallets. Array items order will be applied to the wallets in modal window.

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 = {
        walletsList: {
            wallets: ['tonkeeper', 'openmask', customWallet]
        }
    };

Modify default wallets list

Exclude some wallets with excludeWallets property. Include custom wallets with includeWallets property. Setup place where custom wallets will appear in the all wallets list with includeWalletsOrder. Default value id 'end''.

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 = {
        walletsList: {
            excludeWallets: ['openmask'],
            includeWallets: [customWallet],
            includeWalletsOrder: 'start'
        }
    };

See all available options

Keywords

FAQs

Package last updated on 09 Jan 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc