UNPKG

@tonconnect/ui

Version:

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

554 lines (533 loc) 19.8 kB
import { WalletInfoInjectable, WalletInfoRemote, RequiredFeatures, VersionEvent, ConnectionEvent, ConnectionRestoringEvent, DisconnectionEvent, TransactionSigningEvent, DataSigningEvent, EventDispatcher, SdkActionEvent, ITonConnect, Wallet, FeatureName, WalletInfo, Account, ConnectAdditionalRequest, TonConnectError, SendTransactionRequest, SendTransactionResponse, SignDataPayload, SignDataResponse } from '@tonconnect/sdk'; export * from '@tonconnect/sdk'; import { Property } from 'csstype'; type Locales = 'en' | 'ru'; declare enum THEME { DARK = "DARK", LIGHT = "LIGHT" } type Theme = THEME | 'SYSTEM'; type BorderRadius = 'm' | 's' | 'none'; type Color$1 = Property.Color; type ColorsSet = { constant: { black: Color$1; white: Color$1; }; connectButton: { background: Color$1; foreground: Color$1; }; accent: Color$1; telegramButton: Color$1; icon: { primary: Color$1; secondary: Color$1; tertiary: Color$1; success: Color$1; error: Color$1; }; background: { primary: Color$1; secondary: Color$1; segment: Color$1; tint: Color$1; qr: Color$1; }; text: { primary: Color$1; secondary: Color$1; }; }; type PartialColorsSet = { constant?: { black?: Color$1; white?: Color$1; }; connectButton?: { background?: Color$1; foreground?: Color$1; }; accent?: Color$1; telegramButton?: Color$1; icon?: { primary?: Color$1; secondary?: Color$1; tertiary?: Color$1; success?: Color$1; error?: Color$1; }; background?: { primary?: Color$1; secondary?: Color$1; segment?: Color$1; tint?: Color$1; qr?: Color$1; }; text?: { primary?: Color$1; secondary?: Color$1; }; }; interface UIPreferences { /** * Color theme for the UI elements. * @default SYSTEM theme. */ theme?: Theme; /** * Border radius for UI elements. * @default 'm' */ borderRadius?: BorderRadius; /** * Configure colors scheme for different themes. */ colorsSet?: Partial<Record<THEME, PartialColorsSet>>; } type UIWallet = Omit<WalletInfoInjectable, 'injected' | 'embedded'> | WalletInfoRemote; /** * Add corrections to the default wallets list in the modal: add custom wallets and change wallets order. */ type WalletsListConfiguration = { /** * Allows to include extra wallets to the wallets list in the modal. */ includeWallets?: UIWallet[]; }; /** * Specifies return strategy for the deeplink when user signs/declines the request. * [See details]{@link https://github.com/ton-connect/docs/blob/main/bridge.md#universal-link}. */ type ReturnStrategy = 'back' | 'none' | `${string}://${string}`; interface ActionConfiguration { /** * Configure action modals behavior. * @default ['before'] */ modals?: ('before' | 'success' | 'error')[] | 'all'; /** * Configure action notifications behavior. * @default 'all' */ notifications?: ('before' | 'success' | 'error')[] | 'all'; /** * Specifies return strategy for the deeplink when user signs/declines the request. * @default 'back' */ returnStrategy?: ReturnStrategy; /** * Specifies return url for TWA-TWA connections. * This will be applied as a return strategy if dApp is opened as a TWA and user selects TWA wallet (overrides `returnStrategy` if). */ twaReturnUrl?: `${string}://${string}`; /** * @deprecated Shouldn't be used anymore, SDK will automatically detect return strategy for TWA-TWA connections. * Specifies whether the method should redirect user to the connected wallet * @default 'ios' */ skipRedirectToWallet?: 'ios' | 'always' | 'never'; } interface TonConnectUiOptions { /** * UI elements configuration. */ uiPreferences?: UIPreferences; /** * HTML element id to attach the wallet connect button. If not passed button won't appear. * @default null. */ buttonRootId?: string | null; /** * Language for the phrases it the UI elements. * @default system */ language?: Locales; /** * Configuration for the wallets list in the connect wallet modal. */ walletsListConfiguration?: WalletsListConfiguration; /** * Required features for wallets. If wallet doesn't support required features, it will be disabled. */ walletsRequiredFeatures?: RequiredFeatures; /** * Preferred features for wallets. If wallet doesn't support preferred features, it will be moved to the end of the list. */ walletsPreferredFeatures?: RequiredFeatures; /** * Configuration for action-period (e.g. sendTransaction) UI elements: modals and notifications and wallet behaviour (return strategy). */ actionsConfiguration?: ActionConfiguration; /** * Specifies whether the Android back button should be used to close modals and notifications on Android devices. * @default true */ enableAndroidBackHandler?: boolean; } /** * User action events. */ type UserActionEvent = VersionEvent | ConnectionEvent | ConnectionRestoringEvent | DisconnectionEvent | TransactionSigningEvent | DataSigningEvent; type TonConnectUiCreateOptions = TonConnectUiOptionsWithConnector | TonConnectUiOptionsWithManifest; interface TonConnectUiOptionsWithManifest extends TonConnectUiCreateOptionsBase { /** * Url to the [manifest]{@link https://github.com/ton-connect/docs/blob/main/requests-responses.md#app-manifest} with the Dapp metadata that will be displayed in the user's wallet. * If not passed, manifest from `${window.location.origin}/tonconnect-manifest.json` will be taken. */ manifestUrl?: string; } interface TonConnectUiOptionsWithConnector extends TonConnectUiCreateOptionsBase { /** * TonConnect instance. Can be helpful if you use custom ITonConnect implementation, or use both of @tonconnect/sdk and @tonconnect/ui in your app. */ connector?: ITonConnect; } interface TonConnectUiCreateOptionsBase extends TonConnectUiOptions { /** * Try to restore existing session and reconnect to the corresponding wallet. * @default true. */ restoreConnection?: boolean; /** * HTML element id to attach the modal window element. If not passed, `div#tc-widget-root` in the end of the <body> will be added and used. * @default `div#tc-widget-root`. */ widgetRootId?: string; /** * Event dispatcher to track user actions. By default, it uses `window.dispatchEvent` for browser environment. * @default BrowserEventDispatcher. */ eventDispatcher?: EventDispatcher<UserActionEvent | SdkActionEvent>; } type WalletOpenMethod = 'qrcode' | 'universal-link' | 'custom-deeplink'; type WalletInfoWithOpenMethod = WalletInfoInjectable | WalletInfoRemoteWithOpenMethod | (WalletInfoInjectable & WalletInfoRemoteWithOpenMethod); type WalletInfoRemoteWithOpenMethod = WalletInfoRemote & { openMethod?: WalletOpenMethod; }; type ConnectedWallet = Wallet & WalletInfoWithOpenMethod; type Loadable<T> = LoadableLoading | LoadableReady<T>; type LoadableLoading = { state: 'loading'; }; type LoadableReady<T> = { state: 'ready'; value: T; }; interface WalletsModal { /** * Open the modal. */ open: () => void; /** * Close the modal. * @default 'action-cancelled' */ close: (reason?: WalletsModalCloseReason) => void; /** * Subscribe to the modal window status changes. */ onStateChange: (callback: (state: WalletsModalState) => void) => () => void; /** * Current modal window state. */ state: WalletsModalState; } /** * Opened modal window state. */ type WalletModalOpened = { /** * Modal window status. */ status: 'opened'; /** * Always `null` for opened modal window. */ closeReason: null; }; /** * Closed modal window state. */ type WalletModalClosed = { /** * Modal window status. */ status: 'closed'; /** * Close reason, if the modal window was closed. */ closeReason: WalletsModalCloseReason | null; }; type ChooseSupportedFeatureWalletsModal = { /** * Modal window status. */ status: 'opened'; /** * Always `null` for choose supported feature wallet modal. */ closeReason: null; type: 'wallet-not-support-feature'; requiredFeature: { featureName: FeatureName; value?: RequiredFeatures['sendTransaction']; }; }; /** * Modal window state. */ type WalletsModalState = WalletModalOpened | WalletModalClosed | ChooseSupportedFeatureWalletsModal; /** * Modal window close reason. */ type WalletsModalCloseReason = 'action-cancelled' | 'wallet-selected'; /** * Opened modal window state. */ type SingleWalletModalOpened = { /** * Modal window status. */ status: 'opened'; /** * Wallet info. */ walletInfo: WalletInfoRemote; /** * Always `null` for opened modal window. */ closeReason: null; }; /** * Closed modal window state. */ type SingleWalletModalClosed = { /** * Modal window status. */ status: 'closed'; /** * Close reason, if the modal window was closed. */ closeReason: SingleWalletModalCloseReason | null; }; /** * Modal window state. */ type SingleWalletModalState = SingleWalletModalOpened | SingleWalletModalClosed; /** * Modal window close reason. */ type SingleWalletModalCloseReason = 'action-cancelled' | 'wallet-selected'; declare class TonConnectUI { static getWallets(): Promise<WalletInfo[]>; private readonly walletInfoStorage; private readonly preferredWalletStorage; /** * Emits user action event to the EventDispatcher. By default, it uses `window.dispatchEvent` for browser environment. * @private */ private readonly tracker; private walletInfo; private systemThemeChangeUnsubscribe; private actionsConfiguration?; private readonly walletsList; private _walletsRequiredFeatures?; get walletsRequiredFeatures(): RequiredFeatures | undefined; private _walletsPreferredFeatures?; get walletsPreferredFeatures(): RequiredFeatures | undefined; private connectRequestParametersCallback?; /** * TonConnect instance. */ readonly connector: ITonConnect; /** * Manages the modal window state. */ readonly modal: WalletsModal; /** * Manages the single wallet modal window state. * TODO: make it public when interface will be ready for external usage. */ private readonly singleWalletModal; /** * Manages the transaction modal window state. * TODO: make it public when interface will be ready for external usage. */ private readonly transactionModal; /** * 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. */ readonly connectionRestored: Promise<boolean>; /** * Current connection status. */ get connected(): boolean; /** * Current connected account or null. */ get account(): Account | null; /** * Curren connected wallet app and its info or null. */ get wallet(): Wallet | (Wallet & WalletInfoWithOpenMethod) | null; /** * Set and apply new UI options. Object with partial options should be passed. Passed options will be merged with current options. * @param options */ set uiOptions(options: TonConnectUiOptions); constructor(options?: TonConnectUiCreateOptions); /** * Use it to customize ConnectRequest and add `tonProof` payload. * You can call it multiply times to set updated tonProof payload if previous one is outdated. * If `connectRequestParameters.state === 'loading'` loader will appear instead of the qr code in the wallets modal. * If `connectRequestParameters.state` was changed to 'ready' or it's value has been changed, QR will be re-rendered. */ setConnectRequestParameters(connectRequestParameters: Loadable<ConnectAdditionalRequest> | undefined | null): void; /** * Returns available wallets list. */ getWallets(): Promise<WalletInfo[]>; /** * Subscribe to connection status change. * @return function which has to be called to unsubscribe. */ onStatusChange(callback: (wallet: ConnectedWallet | null) => void, errorsHandler?: (err: TonConnectError) => void): ReturnType<ITonConnect['onStatusChange']>; /** * Opens the modal window, returns a promise that resolves after the modal window is opened. */ openModal(): Promise<void>; /** * Closes the modal window. */ closeModal(reason?: WalletsModalCloseReason): void; /** * Subscribe to the modal window state changes, returns a function which has to be called to unsubscribe. */ onModalStateChange(onChange: (state: WalletsModalState) => void): () => void; /** * Returns current modal window state. */ get modalState(): WalletsModalState; /** * Opens the single wallet modal window, returns a promise that resolves after the modal window is opened. * @experimental */ openSingleWalletModal(wallet: string): Promise<void>; /** * Close the single wallet modal window. * @experimental */ closeSingleWalletModal(closeReason?: WalletsModalCloseReason): void; /** * Subscribe to the single wallet modal window state changes, returns a function which has to be called to unsubscribe. * @experimental */ onSingleWalletModalStateChange(onChange: (state: SingleWalletModalState) => void): () => void; /** * Returns current single wallet modal window state. * @experimental */ get singleWalletModalState(): SingleWalletModalState; /** * @deprecated Use `tonConnectUI.openModal()` instead. Will be removed in the next major version. * Opens the modal window and handles a wallet connection. * @return Connected wallet. * @throws TonConnectUIError if connection was aborted. */ connectWallet(): Promise<ConnectedWallet>; /** * Disconnect wallet and clean localstorage. */ disconnect(): Promise<void>; /** * Opens the modal window and handles the transaction sending. * @param tx transaction to send. * @param options modal and notifications behaviour settings. Default is show only 'before' modal and all notifications. */ sendTransaction(tx: SendTransactionRequest, options?: ActionConfiguration & { onRequestSent?: (redirectToWallet: () => void) => void; }): Promise<SendTransactionResponse>; /** * Signs the data and returns the signature. * @param data data to sign. */ signData(data: SignDataPayload, options?: { onRequestSent?: (redirectToWallet: () => void) => void; }): Promise<SignDataResponse>; /** * Gets the current session ID if available. * @returns session ID string or null if not available. */ private getSessionId; private redirectAfterRequestSent; /** * TODO: remove in the next major version. * Initiates a connection with an embedded wallet, awaits its completion, and returns the connected wallet information. * @param embeddedWallet - Information about the embedded wallet to connect to. * @throws Error if the connection process fails. * @internal */ private connectEmbeddedWallet; /** * TODO: remove in the next major version. * Initiates the connection process for an external wallet by opening the wallet modal * and returns the connected wallet information upon successful connection. * @throws Error if the user cancels the connection process or if the connection process fails. * @internal */ private connectExternalWallet; /** * TODO: remove in the next major version. * Waits for a wallet connection based on provided options, returning connected wallet information. * @param options - Configuration for connection statuses and errors handling. * @options.ignoreErrors - If true, ignores errors during waiting, waiting continues until a valid wallet connects. Default is false. * @options.abortSignal - Optional AbortSignal for external cancellation. Throws TonConnectUIError if aborted. * @throws TonConnectUIError if waiting is aborted or no valid wallet connection is received and ignoreErrors is false. * @internal */ private waitForWalletConnection; /** * Waits for a transaction to be sent based on provided options, returning the transaction response. * @param options - Configuration for transaction statuses and errors handling. * @options.transaction - Transaction to send. * @options.ignoreErrors - If true, ignores errors during waiting, waiting continues until a valid transaction is sent. Default is false. * @options.abortSignal - Optional AbortSignal for external cancellation. Throws TonConnectUIError if aborted. * @param onRequestSent (optional) will be called after the transaction is sent to the wallet. * @throws TonConnectUIError if waiting is aborted or no valid transaction response is received and ignoreErrors is false. * @internal */ private waitForSendTransaction; /** * Waits for a transaction to be sent based on provided options, returning the transaction response. * @param options - Configuration for transaction statuses and errors handling. * @options.transaction - Transaction to send. * @options.ignoreErrors - If true, ignores errors during waiting, waiting continues until a valid transaction is sent. Default is false. * @options.abortSignal - Optional AbortSignal for external cancellation. Throws TonConnectUIError if aborted. * @param onRequestSent (optional) will be called after the transaction is sent to the wallet. * @throws TonConnectUIError if waiting is aborted or no valid transaction response is received and ignoreErrors is false. * @internal */ private waitForSignData; /** * Subscribe to the transaction modal window state changes, returns a function which has to be called to unsubscribe. * @internal */ private onTransactionModalStateChange; private subscribeToWalletChange; private setPreferredWalletAppName; private getSelectedWalletInfo; private updateWalletInfo; private normalizeWidgetRoot; private checkButtonRootExist; private getModalsAndNotificationsConfiguration; } type Color = Property.Color; declare class TonConnectUIError extends TonConnectError { constructor(...args: ConstructorParameters<typeof Error>); } export { THEME, TonConnectUI, TonConnectUIError }; export type { ActionConfiguration, BorderRadius, Color, ColorsSet, ConnectedWallet, Loadable, LoadableLoading, LoadableReady, Locales, PartialColorsSet, ReturnStrategy, Theme, TonConnectUiCreateOptions, TonConnectUiCreateOptionsBase, TonConnectUiOptions, TonConnectUiOptionsWithConnector, TonConnectUiOptionsWithManifest, UIPreferences, UIWallet, UserActionEvent, WalletInfoRemoteWithOpenMethod, WalletInfoWithOpenMethod, WalletModalClosed, WalletModalOpened, WalletOpenMethod, WalletsListConfiguration, WalletsModal, WalletsModalCloseReason, WalletsModalState };