/** * The TON account that the wallet exposed to the dApp during the connect handshake. * * One {@link Wallet} maps to exactly one `Account` for the lifetime of the session. * To switch accounts the user has to disconnect and reconnect from the dApp UI. * * @see [`ton_addr` reply (Connect spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/connect.md#connectitemreply) */ export declare interface Account { /** * User's address in raw hex form `:`. * * Use {@link toUserFriendlyAddress} to render the non-bounceable base64url * form (`UQ…` on mainnet, `0Q…` on testnet) used in user-facing UI. */ address: string; /** * TON network identifier. See {@link ChainId}. */ chain: ChainId; /** * Base64-encoded (not URL-safe) BoC of the wallet contract `StateInit` cell. * * @see [sign-data § Extracting the public key](https://docs.ton.org/applications/ton-connect/how-to/sign-data#extracting-the-public-key) */ walletStateInit: string; /** * Ed25519 public key advertised by the wallet during connect, hex-encoded * **without** the `0x` prefix. * * The value is not authoritative — do not trust it directly when verifying * signatures. Re-derive it from {@link Account.walletStateInit} or call * `get_public_key` on the wallet contract instead. */ publicKey?: string; } export declare type AddTonConnectPrefix = `ton-connect-${T}` | `ton-connect-ui-${T}`; export declare type AnalyticsMode = 'off' | 'telemetry' | 'full'; /** * Analytics configuration forwarded to the SDK's internal tracker. * * Analytics is opt-out. The default mode is `'telemetry'` — * minimal, anonymous signals used for technical research and issue debugging. * Set `mode: 'off'` to disable, or `mode: 'full'` to opt into the full event * stream. */ export declare interface AnalyticsSettings { /** * - `'off'` — no events are collected or sent. * - `'telemetry'` — technical analytics only (default). * - `'full'` — full user-action event stream. * * @default 'telemetry' */ mode?: AnalyticsMode; /** * Where to send events. Defaults to the hosted collector. * * Point this at a local endpoint to inspect what the SDK actually emits without reaching * the network — the only way to verify analytics changes locally, since the hosted collector * rejects requests from a development origin. */ url?: string; } /** * Anything a dApp can send to a wallet over the protocol. */ export declare type AppMessage = ConnectRequest | AppRequest; /** * Request envelope for the given RPC `method`. Each envelope follows the * same `{ method, params, id }` structure; * * @see [RPC envelope (RPC spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/rpc.md#envelope) */ export declare type AppRequest = RpcRequests[T]; /** * Requested authentication type: 'ton_addr' or 'ton_proof'. */ export declare type AuthType = ConnectItem['name']; /** * Thrown when request to the wallet contains errors. */ export declare class BadRequestError extends TonConnectError { static readonly errorName: string; protected get info(): string; } /** * UTF-8 base64 codec used by `@tonconnect/protocol`. Wraps the NaCl * helpers with optional URL-safe encoding and a typed decoder that can * yield a string, an object (JSON-parsed), or the raw byte array. * * @example * ```ts * import { Base64 } from '@tonconnect/protocol'; * * const encoded = Base64.encode({ hello: 'world' }); * const obj = Base64.decode(encoded).toObject<{ hello: string }>(); * const bin = Base64.decode(Base64.encode('Hello')).toUint8Array(); * ``` */ export declare const Base64: { encode: typeof encode; decode: typeof decode; }; /** * A concrete implementation of EventDispatcher that dispatches events to the browser window. */ export declare class BrowserEventDispatcher implements EventDispatcher { /** * The window object, possibly undefined in a server environment. * @private */ private readonly window; /** * Dispatches an event with the given name and details to the browser window. * @param eventName - The name of the event to dispatch. * @param eventDetails - The details of the event to dispatch. * @returns A promise that resolves when the event has been dispatched. */ dispatchEvent

>(eventName: P, eventDetails: T & { type: RemoveTonConnectPrefix

; }): Promise; /** * Adds an event listener to the browser window. * @param eventName - The name of the event to listen for. * @param listener - The listener to add. * @param options - The options for the listener. * @returns A function that removes the listener. */ addEventListener

>(eventName: P, listener: (event: CustomEvent; }>) => void, options?: AddEventListenerOptions): Promise<() => void>; } /** * Two baseline TON network IDs. */ export declare enum CHAIN { MAINNET = "-239", TESTNET = "-3" } /** * TON network identifier. May be extended with custom `global_id`s. * * @see [`NETWORK_ID` (Connect spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/connect.md#network_id) */ export declare type ChainId = CHAIN | string; /** * Test whether a wallet's advertised `features` satisfy a * {@link RequiredFeatures} filter. * * @returns `true` when every constraint in `walletsRequiredFeatures` matches, * `false` otherwise. * * @see [Filter wallets by required features (docs)](https://docs.ton.org/applications/ton-connect/how-to/filter-wallets) */ export declare function checkRequiredWalletFeatures(features: Feature[], walletsRequiredFeatures?: RequiredFeatures): boolean; /** Concatenate two byte arrays into a new `Uint8Array`. */ export declare function concatUint8Arrays(buffer1: Uint8Array, buffer2: Uint8Array): Uint8Array; /** * Error codes the wallet may return in {@link ConnectEventError}. * * @see [Connect event error codes (Connect spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/connect.md#connect-event-error-codes) */ export declare enum CONNECT_EVENT_ERROR_CODES { /** Unexpected wallet-side failure. */ UNKNOWN_ERROR = 0, /** Request payload is malformed. */ BAD_REQUEST_ERROR = 1, /** Wallet could not fetch the `tonconnect-manifest.json`. */ MANIFEST_NOT_FOUND_ERROR = 2, /** Manifest was fetched but fails JSON / schema validation. */ MANIFEST_CONTENT_ERROR = 3, /** Wallet does not know the app / session. */ UNKNOWN_APP_ERROR = 100, /** User explicitly declined the connect prompt. */ USER_REJECTS_ERROR = 300, /** Wallet does not support the requested method. */ METHOD_NOT_SUPPORTED = 400 } /** * Per-item error codes returned inside a {@link ConnectItemReplyError}. * * @see [Connect item error codes (Connect spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/connect.md#connect-item-error-codes) */ export declare enum CONNECT_ITEM_ERROR_CODES { /** Unexpected wallet-side failure. */ UNKNOWN_ERROR = 0, /** Wallet does not support this connect item. */ METHOD_NOT_SUPPORTED = 400 } /** * Extra items to attach to the [`ConnectRequest`](https://github.com/ton-blockchain/ton-connect/blob/main/spec/connect.md#connectrequest) * the SDK sends to the wallet. * * @see [Connect a wallet § Authenticate with `ton_proof`](https://docs.ton.org/applications/ton-connect/how-to/connect#authenticate-with-ton_proof) * @see [Address proof signature (Connect spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/connect.md#address-proof-signature-ton_proof) */ export declare interface ConnectAdditionalRequest { /** * Application payload for future verification to bind into the `ton_proof` signature. */ tonProof?: string; } /** * Wallet reply to a `ConnectRequest`. Either a success * ({@link ConnectEventSuccess}) carrying the user's account and the * requested data items, or {@link ConnectEventError} when the user declines * or the wallet fails to fulfil the request. * * @see [`ConnectEvent` (Connect spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/connect.md#connectevent) */ export declare type ConnectEvent = ConnectEventSuccess | ConnectEventError; /** * Connect failure. The dApp should surface the matching error from * {@link CONNECT_EVENT_ERROR_CODES} and unwind any pending UI. */ export declare interface ConnectEventError { event: 'connect_error'; id: number; payload: { code: CONNECT_EVENT_ERROR_CODES; message: string; }; } /** * Successful connect handshake. * * Wallets that support the [`EmbeddedRequest`](https://github.com/ton-blockchain/ton-connect/blob/main/spec/deeplinks.md#embedded-requests-e) * feature MAY attach the signed result of an embedded action on * {@link ConnectEventSuccess.response}. */ export declare interface ConnectEventSuccess { event: 'connect'; /** Monotonic event id (separate counter from RPC `id`). */ id: number; payload: { /** Replies for the {@link ConnectRequest.items}. */ items: ConnectItemReply[]; /** Wallet self-description and advertised capabilities. */ device: DeviceInfo; }; /** * Result of an embedded request that traveled in the connect URL's * `e` parameter. Present only when the wallet supports the * `EmbeddedRequest` feature and chose to process the folded request. * * @see [Embedded requests (deeplinks spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/deeplinks.md#embedded-requests-e) */ response?: WalletResponse; } /** * Successful connection event when a user successfully connected a wallet. */ export declare type ConnectionCompletedEvent = { /** * Event type. */ type: 'connection-completed'; /** * Connection success flag. */ is_success: true; /** * `true` when this completion is a replay of a stored session by * `restoreConnection()` rather than a fresh connection. Restores fire on every page load * for an already-connected user, so counting completions without excluding them measures * page views rather than connections. */ is_restore: boolean; /** * Unique identifier used for tracking a specific user flow. */ trace_id?: string | null; } & ConnectionInfo; /** * Connection error event when a user cancels a connection or there is an error during the connection process. */ export declare type ConnectionErrorEvent = { /** * Event type. */ type: 'connection-error'; /** * Connection success flag. */ is_success: false; /** * Reason for the error. */ error_message: string; /** * Error code. */ error_code: CONNECT_EVENT_ERROR_CODES | null; /** * Custom data for the connection. */ custom_data: { client_id: string | null; wallet_id: string | null; } & Version; /** * Unique identifier used for tracking a specific user flow. */ trace_id?: string | null; }; /** * Connection events. */ export declare type ConnectionEvent = ConnectionStartedEvent | ConnectionInitiatedEvent | ConnectionLinkGeneratedEvent | ConnectionCompletedEvent | ConnectionErrorEvent; /** * Information about a connected wallet. */ export declare type ConnectionInfo = { /** * Connected wallet address. */ wallet_address: string | null; /** * Connected wallet state init. */ wallet_state_init: string | null; /** * Wallet type: 'tonkeeper', 'tonhub', etc. */ wallet_type: string | null; /** * Wallet version. */ wallet_version: string | null; /** * Requested authentication types. */ auth_type: AuthType; /** * Custom data for the connection. */ custom_data: { /** * Connected chain ID. */ chain_id: string | null; /** * Wallet provider. */ provider: 'http' | 'injected' | null; client_id: string | null; wallet_id: string | null; } & Version; }; /** * A connection was initiated against a particular kind of source. * * Unlike {@link SelectedWalletEvent}, which only the UI package emits, this fires from the core * SDK on every `connect()` — so it also covers dApps that ship their own wallet picker, deep-link * straight to a wallet, or use `@tonconnect/sdk` without `@tonconnect/ui` at all. * * It counts connect *initiations*, not user actions: a single journey can legitimately produce * several, with different source kinds, sharing one trace id. */ export declare type ConnectionInitiatedEvent = { /** * Event type. */ type: 'connection-initiated'; /** * How the connection was initiated. */ connection_source_kind: WalletConnectionSourceKind; /** * Bridge key from the wallets list, for `js-embedded` and `js-injected` sources. */ bridge_key?: string; /** * Bridge URL, for an `http-specific-wallet` source. */ bridge_url?: string; /** * Custom data for the connection. */ custom_data: Version; /** * Unique identifier used for tracking a specific user flow. */ trace_id?: string | null; }; /** * A connect URL or QR code was built for display, without anyone choosing to connect. * * Separate from {@link ConnectionInitiatedEvent} rather than a flag on it, because the two are * only distinguishable by intent and a flag would have to be remembered in every query. The * desktop universal modal builds a QR as it renders, and the desktop connection screen rebuilds * one in an effect — both open a real session, so they are indistinguishable downstream from a * connect a user asked for. * * Carries the same source classification, so QR displays can be counted per wallet or per * bridge without inflating initiations. */ export declare type ConnectionLinkGeneratedEvent = { /** * Event type. */ type: 'connection-link-generated'; /** * How the link would connect, had it been used. */ connection_source_kind: WalletConnectionSourceKind; /** * Bridge key from the wallets list, for `js-embedded` and `js-injected` sources. */ bridge_key?: string; /** * Bridge URL, for an `http-specific-wallet` source. */ bridge_url?: string; /** * Custom data for the connection. */ custom_data: Version; /** * Unique identifier used for tracking a specific user flow. */ trace_id?: string | null; }; /** * Connection restoring completed event when successfully restored a connection. */ export declare type ConnectionRestoringCompletedEvent = { /** * Event type. */ type: 'connection-restoring-completed'; /** * Connection success flag. */ is_success: true; /** * Unique identifier used for tracking a specific user flow. */ trace_id?: string | null; } & ConnectionInfo; /** * Connection restoring error event when there is an error during the connection restoring process. */ export declare type ConnectionRestoringErrorEvent = { /** * Event type. */ type: 'connection-restoring-error'; /** * Connection success flag. */ is_success: false; /** * Reason for the error. */ error_message: string; /** * Custom data for the connection. */ custom_data: Version; /** * Unique identifier used for tracking a specific user flow. */ trace_id?: string | null; }; /** * Connection restoring events. */ export declare type ConnectionRestoringEvent = ConnectionRestoringStartedEvent | ConnectionRestoringCompletedEvent | ConnectionRestoringErrorEvent; /** * Connection restoring started event when initiates a connection restoring process. */ export declare type ConnectionRestoringStartedEvent = { /** * Event type. */ type: 'connection-restoring-started'; /** * Custom data for the connection. */ custom_data: Version; /** * Unique identifier used for tracking a specific user flow. */ trace_id?: string | null; }; /** * Initial connection event when a user initiates a connection. */ export declare type ConnectionStartedEvent = { /** * Event type. */ type: 'connection-started'; /** * Custom data for the connection. */ custom_data: Version; /** * Unique identifier used for tracking a specific user flow. */ trace_id?: string | null; }; /** * Data item attached to a {@link ConnectRequest}. Wallets reply to each item * inside `ConnectEventSuccess.payload.items`. * * The protocol defines two items: * * - {@link TonAddressItem} — required for the connect to be useful. * - {@link TonProofItem} — optional `ton_proof` request used for * wallet authentication. * * @see [`ConnectItem` (Connect spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/connect.md#connectrequest) */ export declare type ConnectItem = TonAddressItem | TonProofItem; /** * Per-item reply inside {@link ConnectEventSuccess}`.payload.items`. Wallets * either fulfil the item or return a {@link ConnectItemReplyError} carrying a * {@link CONNECT_ITEM_ERROR_CODES} code (`400` when the item is unsupported). */ export declare type ConnectItemReply = TonAddressItemReply | TonProofItemReply; /** * Generic per-item error envelope used inside `payload.items[]` when the * wallet cannot fulfil a specific item — for example a wallet that doesn't * implement `ton_proof` returns `{ name: 'ton_proof', error: { code: 400 } }`. */ export declare type ConnectItemReplyError = { name: T; error: { code: CONNECT_ITEM_ERROR_CODES; message?: string; }; }; /** * First message a dApp sends to a wallet. Carried inside the connect URL — * not over the encrypted bridge — because the wallet is not yet connected. * * @see [`ConnectRequest` (Connect spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/connect.md#connectrequest) */ export declare interface ConnectRequest { /** * URL of the dApp's * [`tonconnect-manifest.json`](https://github.com/ton-blockchain/ton-connect/blob/main/spec/manifest.md). * The wallet fetches this file before showing the connect prompt to * extract the dApp's name, icon and policy URLs. */ manifestUrl: string; /** * Data items the dApp wants to receive from the wallet on successful * connect. The wallet returns a matching reply for each item (or a * per-item error if unsupported). At least one entry — typically * `{ name: 'ton_addr' }` — is required. */ items: ConnectItem[]; } /** * Single-shot value envelope. Holds a value until exactly one consumer calls * {@link Consumable.consume}; subsequent reads return `undefined`. */ export declare class Consumable { private value; private readonly __isConsumable; /** * Wrap `value`. If `value` is already a `Consumable`, returns it * unchanged so the type stays flat. */ constructor(value: ConsumableLike); /** Read the wrapped value without consuming it. `undefined` once consumed. */ peek(): T | undefined; /** * Take ownership of the wrapped value. The next call returns `undefined`. * Use this when the value is about to be acted on exactly once. */ consume(): T | undefined; /** `true` once {@link Consumable.consume} has been called. */ get consumed(): boolean; } /** * Accept either a bare value or a value already wrapped in a {@link Consumable}. */ export declare type ConsumableLike = T | Consumable; /** * Create a connection completed event. * @param version * @param wallet * @param sessionInfo * @param traceId */ export declare function createConnectionCompletedEvent(version: Version, wallet: Wallet | null, sessionInfo?: SessionInfo | null, traceId?: string | null, isRestore?: boolean): ConnectionCompletedEvent; /** * Create a connection error event. * @param version * @param error_message * @param errorCode * @param sessionInfo * @param traceId */ export declare function createConnectionErrorEvent(version: Version, error_message: string, errorCode: CONNECT_EVENT_ERROR_CODES | void, sessionInfo?: SessionInfo | null, traceId?: string | null): ConnectionErrorEvent; /** * Create a connection initiated event. */ export declare function createConnectionInitiatedEvent(version: Version, source: WalletConnectionSourceInfo, traceId?: string | null): ConnectionInitiatedEvent; /** * Create a connection link generated event. */ export declare function createConnectionLinkGeneratedEvent(version: Version, source: WalletConnectionSourceInfo, traceId?: string | null): ConnectionLinkGeneratedEvent; /** * Create a connection restoring completed event. * @param version * @param wallet * @param sessionInfo * @param traceId */ export declare function createConnectionRestoringCompletedEvent(version: Version, wallet: Wallet | null, sessionInfo?: SessionInfo | null, traceId?: string | null): ConnectionRestoringCompletedEvent; /** * Create a connection restoring error event. * @param version * @param errorMessage * @param traceId */ export declare function createConnectionRestoringErrorEvent(version: Version, errorMessage: string, traceId?: string | null): ConnectionRestoringErrorEvent; /** * Create a connection restoring started event. */ export declare function createConnectionRestoringStartedEvent(version: Version, traceId?: string | null): ConnectionRestoringStartedEvent; /** * Create a connection init event. */ export declare function createConnectionStartedEvent(version: Version, traceId?: string | null): ConnectionStartedEvent; export declare function createDataSentForSignatureEvent(version: Version, wallet: Wallet | null, data: SignDataPayload, sessionInfo?: SessionInfo | null, traceId?: string | null): DataSentForSignatureEvent; export declare function createDataSignedEvent(version: Version, wallet: Wallet | null, data: SignDataPayload, signedData: SignDataResponse, sessionInfo?: SessionInfo | null, traceId?: string | null): DataSignedEvent; export declare function createDataSigningFailedEvent(version: Version, wallet: Wallet | null, data: SignDataPayload, errorMessage: string, errorCode: SIGN_DATA_ERROR_CODES | void, sessionInfo?: SessionInfo | null, traceId?: string | null): DataSigningFailedEvent; export declare function createDisconnectionEvent(version: Version, wallet: Wallet | null, scope: 'dapp' | 'wallet', sessionInfo?: SessionInfo | null, traceId?: string | null): DisconnectionEvent; /** * Create a request version event. */ export declare function createRequestVersionEvent(): RequestVersionEvent; /** * Create a response version event. * @param version */ export declare function createResponseVersionEvent(version: string): ResponseVersionEvent; export declare function createSelectedWalletEvent(version: Version, visibleWallets: string[], lastSelectedWallet: { appName?: string; } | null, walletsMenu: 'explicit_wallet' | 'main_screen' | 'other_wallets', redirectLink: string, redirectLinkType?: 'tg_link' | 'external_link', clientId?: string | null, traceId?: string | null): SelectedWalletEvent; /** * Create a transaction init event. * @param version * @param wallet * @param transaction * @param sessionInfo * @param traceId */ export declare function createTransactionSentForSignatureEvent(version: Version, wallet: Wallet | null, transaction: SendTransactionRequest, sessionInfo?: SessionInfo | null, traceId?: string | null): TransactionSentForSignatureEvent; /** * Create a transaction signed event. * @param version * @param wallet * @param transaction * @param signedTransaction * @param sessionInfo * @param traceId */ export declare function createTransactionSignedEvent(version: Version, wallet: Wallet | null, transaction: SendTransactionRequest, signedTransaction: SendTransactionResponse, sessionInfo?: SessionInfo | null, traceId?: string | null): TransactionSignedEvent; /** * Create a transaction error event. * @param version * @param wallet * @param transaction * @param errorMessage * @param errorCode * @param sessionInfo * @param traceId */ export declare function createTransactionSigningFailedEvent(version: Version, wallet: Wallet | null, transaction: SendTransactionRequest, errorMessage: string, errorCode: SEND_TRANSACTION_ERROR_CODES | void, sessionInfo?: SessionInfo | null, traceId?: string | null): TransactionSigningFailedEvent; /** * Create a version info. * @param version */ export declare function createVersionInfo(version: Version): Version; export declare function createWalletModalOpenedEvent(version: Version, visibleWallets: string[], clientId?: string | null, traceId?: string | null): WalletModalOpenedEvent; /** * Create a wallet preselected event. */ export declare function createWalletPreselectedEvent(version: Version, walletAppName: string, surface: WalletSelectionSurface, selectionSource: WalletSelectionSource, traceId: string): WalletPreselectedEvent; /** * Create a wallet selected event. */ export declare function createWalletSelectedEvent(version: Version, walletAppName: string, surface: WalletSelectionSurface, selectionSource: WalletSelectionSource, traceId: string, connectionMode?: 'mobile' | 'desktop' | 'extension'): WalletSelectedEvent; export declare interface DappMetadata { /** * Dapp name. Might be simple, will not be used as identifier. * @default `document.title` if exists, 'Unknown dapp' otherwise */ name: string; /** * URL to the dapp icon. Must be PNG, ICO, ... . SVG icons are not supported. * @default best quality favicon declared via in the document or '' if there are no any icons in the document. */ icon: string; /** * Dapp URL. Will be used as the dapp identifier. Will be used to open the dapp after click to its icon in the wallet. * It is recommended to pass url without closing slash, e.g. 'https://mydapp.com' instead of 'https://mydapp.com/'. * @default `window.location.origin` if exists, otherwise (if not explicitly specified) an error will be thrown. */ url: string; } export declare type DataSentForSignatureEvent = { type: 'sign-data-request-initiated'; data: SignDataPayload; /** * Unique identifier used for tracking a specific user flow. */ trace_id?: string | null; } & ConnectionInfo; export declare type DataSignedEvent = { type: 'sign-data-request-completed'; is_success: true; data: SignDataPayload; signed_data: SignDataResponse; /** * Unique identifier used for tracking a specific user flow. */ trace_id?: string | null; } & ConnectionInfo; export declare type DataSigningEvent = DataSentForSignatureEvent | DataSignedEvent | DataSigningFailedEvent; export declare type DataSigningFailedEvent = { type: 'sign-data-request-failed'; is_success: false; error_message: string; error_code: SIGN_DATA_ERROR_CODES | null; data: SignDataPayload; /** * Unique identifier used for tracking a specific user flow. */ trace_id?: string | null; } & ConnectionInfo; export declare function decode(value: string, urlSafe?: boolean): { toString(): string; toObject(): T | null; toUint8Array(): Uint8Array; }; export declare type DecodedEmbeddedRequest = Omit, 'id'>; /** * Decode the `e` URL parameter and return `{ method, params: [string] }` — * the same shape as a bridge `AppRequest` (without `id`). * * The `e` value is `base64url(JSON.stringify(WireEmbeddedRequest))`. */ export declare function decodeEmbeddedRequestParam(reqParam: string): DecodedEmbeddedRequest; /** Inverse of {@link encodeTelegramUrlParameters}. */ export declare function decodeTelegramUrlParameters(parameters: string): string; /** * Decode a compact {@link WireEmbeddedRequest} back to the standard JSON-RPC * `AppRequest`-shaped `{ method, params: [JSON-string] }`. */ export declare function decodeWireEmbeddedRequest(wire: WireEmbeddedRequest): DecodedEmbeddedRequest; /** * Classifies a connection source for analytics. Pure — the caller supplies the one piece of * information the source shape cannot carry. * * Ordering mirrors `createProvider()` in `ton-connect.ts` so the two cannot drift: the array case * first, then the two guarded shapes, with HTTP as the fallthrough (there is deliberately no * `isWalletConnectionSourceHTTP` guard in this module). * * @param source - the value passed to `connect()`. * @param isInsideWalletBrowser - whether the dApp is running inside the named wallet's browser, * which is what separates `embedded` from `injected`. Passed in rather than imported so this * module keeps no dependency on `provider/`, and so the classification stays testable without a * `window`. */ export declare function describeWalletConnectionSource(source: WalletConnectionSource | Pick[], isInsideWalletBrowser: (jsBridgeKey: string) => boolean): WalletConnectionSourceInfo; /** * Wallet self-description returned inside {@link ConnectEventSuccess}'s `payload.device`. * * @see [`DeviceInfo` (Connect spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/connect.md#deviceinfo) */ export declare interface DeviceInfo { /** Operating system / runtime the wallet identifies itself with. */ platform: 'iphone' | 'ipad' | 'android' | 'windows' | 'mac' | 'linux' | 'browser'; /** * Wallet identifier — same value as the `app_name` field in the wallets * list. * * @example "tonkeeper" */ appName: string; /** * The version of the wallet. * * @example "2.3.367" * */ appVersion: string; /** * Highest TON Connect protocol version the wallet implements. */ maxProtocolVersion: number; /** * Capabilities the wallet advertises. */ features: Feature[]; } /** * Error codes the wallet may return from `disconnect`. * @see [`disconnect` errors (RPC spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/rpc.md#disconnect) */ export declare enum DISCONNECT_ERROR_CODES { UNKNOWN_ERROR = 0, BAD_REQUEST_ERROR = 1, UNKNOWN_APP_ERROR = 100, METHOD_NOT_SUPPORTED = 400 } /** * Wallet-initiated session teardown. Fires when the user removes the dApp * from the wallet's connected-apps list. * * @see [Disconnect event (RPC spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/rpc.md#disconnect-event) */ export declare interface DisconnectEvent { event: 'disconnect'; /** Monotonic event id (separate counter from RPC `id`). */ id: number; /** Empty for `disconnect`. */ payload: {}; } /** * Disconnect event when a user initiates a disconnection. */ export declare type DisconnectionEvent = { /** * Event type. */ type: 'disconnection'; /** * Disconnect scope: 'dapp' or 'wallet'. */ scope: 'dapp' | 'wallet'; /** * Unique identifier used for tracking a specific user flow. */ trace_id?: string | null; } & ConnectionInfo; /** * RPC request that tells the wallet the dApp ended the session. * * @see [`disconnect` (RPC spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/rpc.md#disconnect) */ export declare interface DisconnectRpcRequest { method: 'disconnect'; /** empty tuple — no parameters */ params: []; /** dApp-assigned request id; used to match the wallet response */ id: string; } /** * Wallet reply to a `disconnect` RPC. Success carries an empty result; error * narrows the `code` enum to {@link DISCONNECT_ERROR_CODES}. */ export declare type DisconnectRpcResponse = DisconnectRpcResponseSuccess | DisconnectRpcResponseError; /** Failure envelope. `code` is one of {@link DISCONNECT_ERROR_CODES}. */ export declare interface DisconnectRpcResponseError extends WalletResponseTemplateError { error: { code: DISCONNECT_ERROR_CODES; message: string; data?: unknown; }; id: string; } /** Success envelope. `result` is empty — the wallet just acknowledged. */ export declare interface DisconnectRpcResponseSuccess { /** Echo of the request `id`. */ id: string; /** Empty. Reserved for future fields. */ result: {}; } /** * Method + payload pair the SDK can fold into the connect URL as an * [embedded request](https://docs.ton.org/applications/ton-connect/how-to/embedded-request) (`e` parameter). */ export declare type EmbeddedRequest = { method: 'sendTransaction'; request: SendTransactionRequest; } | { method: 'signData'; request: SignDataPayload; } | { method: 'signMessage'; request: SignMessageRequest; }; /** * Wallet supports the embedded-request transport (`e` query parameter on the * connect URL). * * @see [Embedded requests (deeplinks spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/deeplinks.md#embedded-requests-e) */ export declare type EmbeddedRequestFeature = { name: 'EmbeddedRequest'; }; /** * Result the wallet attached to the connect event when an * [embedded request](https://docs.ton.org/applications/ton-connect/how-to/embedded-request) * was folded into the connect URL. * * Discriminated by `ok`: * * - `ok: true` — the wallet processed the request. `result` carries the regular * method response (`SendTransactionResponse`, `SignDataResponse` or * `SignMessageResponse`), whichever method was embedded. * - `ok: false` — the wallet returned an error in place of a result. `error` * matches the RPC error shape; the per-method error tables live in the * [RPC specification](https://github.com/ton-blockchain/ton-connect/blob/main/spec/rpc.md). */ export declare type EmbeddedResponse = { ok: true; result: SendTransactionResponse | SignDataResponse | SignMessageResponse; } | { ok: false; error: { code: number; message: string; data?: unknown; }; }; export declare function enableQaMode(): void; export declare function encode(value: string | object | Uint8Array, urlSafe?: boolean): string; /** * Encode query parameters for transport inside a Telegram universal link. * Telegram normalizes ASCII punctuation in URLs, which breaks the encoded * connect payload; this helper substitutes the affected characters with * pass-through markers that {@link decodeTelegramUrlParameters} reverses. */ export declare function encodeTelegramUrlParameters(parameters: string): string; /** * Interface for an event dispatcher that sends events. */ export declare interface EventDispatcher { /** * Dispatches an event with the given name and details. * @param eventName - The name of the event to dispatch. * @param eventDetails - The details of the event to dispatch. */ dispatchEvent

>(eventName: P, eventDetails: T & { type: RemoveTonConnectPrefix

; }): Promise; /** * Adds an event listener. * @param eventName - The name of the event to listen for. * @param listener - The listener to add. * @param options - The options for the listener. * @returns A function that removes the listener. */ addEventListener

>(eventName: P, listener: (event: CustomEvent; }>) => void, options?: AddEventListenerOptions): Promise<() => void>; } /** * Capability entries advertised by a wallet inside {@link DeviceInfo.features}. * * @see [`Feature` (Connect spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/connect.md#feature) */ export declare type Feature = SendTransactionFeatureDeprecated | SendTransactionFeature | SignDataFeature | SignMessageFeature | EmbeddedRequestFeature; export declare type FeatureName = Exclude['name']; /** * Thrown when an error occurred while fetching the wallets list. */ export declare class FetchWalletsError extends TonConnectError { static readonly errorName: string; protected get info(): string; } /** The Telegram user from the Mini App launch parameters, when present. */ export declare function getTgUser(): TelegramUser | undefined; /** The Telegram Mini App platform, or `'unknown'` outside one. */ export declare function getTmaPlatform(): TmaPlatform; /** * The Telegram WebApp version, defaulting to `'6.0'`. Returned regardless of whether a Mini App * was detected, for feature checks that need to compare versions. */ export declare function getTmaWebAppVersion(): string; /** Type guard: narrows to {@link SendTransactionRequestWithItems}. */ export declare function hasItems(req: SendTransactionRequest): req is SendTransactionRequestWithItems; /** Type guard: narrows to {@link SendTransactionRequestWithMessages}. */ export declare function hasMessages(req: SendTransactionRequest): req is SendTransactionRequestWithMessages; /** * Inverse of {@link toHexString}. Throws when `hexString` has an odd length. */ export declare function hexToByteArray(hexString: string): Uint8Array; /** * Represents the client environment in which the application is running. */ export declare interface IEnvironment { /** * Retrieves the user's current locale setting. */ getLocale(): string; /** * Retrieves the name or identifier of the user's browser. */ getBrowser(): string; /** * Retrieves the name of the user's operating system or platform. */ getPlatform(): string; /** * Retrieves the Telegram user associated with the current environment, if available. */ getTelegramUser(): TelegramUser | undefined; /** * Retrieves the type of client environment. * Indicates whether the client is running as a web application, * Telegram Mini App, or another custom environment. */ getClientEnvironment(): 'web' | 'miniapp' | (string & {}); } /** * Initializes the WalletConnect integration. * * This function must be called once before using WalletConnect features. * A second call will throw an error to prevent accidental re-initialization. * * @param UniversalConnectorCls - A UniversalConnector class imported from '@reown/appkit-universal-connector' * @param {WalletConnectOptions} walletConnectOptions - Configuration options used for initializing WalletConnect. * @example * import { UniversalConnector } from '@reown/appkit-universal-connector'; * * initializeWalletConnect(UniversalConnector, { * projectId: 'abcd1234abcd1234abcd1234abcd1234', * metadata: { * name: 'Demo DApp', * icons: [ * 'https://example.com/my-icon.png' * ], * url: window.location.origin, * description: 'Demo DApp' * } * }); */ export declare function initializeWalletConnect(UniversalConnectorCls: Function, walletConnectOptions: WalletConnectOptions): void; /** * Type guard that returns `true` when `link` looks like a TON Connect connect * URL — i.e. it carries the `ton_addr` request item (raw or * Telegram-encoded). Useful for discriminating handler URLs in deep-link * routers. */ export declare function isConnectUrl(link: string | undefined): link is string; /** `true` when running in the Telegram in-app browser rather than a Mini App. */ export declare function isInTelegramBrowser(): boolean; /** `true` when running inside a Telegram Mini App. */ export declare function isInTMA(): boolean; /** * `true` when running inside Node.js (detected via `process.versions.node`). */ export declare function isNode(): boolean; export declare function isQaModeEnabled(): boolean; /** * Type guard for Telegram links — matches both the `tg://` scheme and * `https://t.me/…`. */ export declare function isTelegramUrl(link: string | undefined): link is string; /** `true` when running inside a Telegram Mini App on one of the given platforms. */ export declare function isTmaPlatform(...platforms: TmaPlatform[]): boolean; /** * Async key-value store used by the SDK to persist protocol state (session * keys, last connected wallet info, restoration markers). * * In the browser the SDK uses `window.localStorage` by default. In Node.js, * React Native or any other environment without a `localStorage` global the * dApp MUST pass a custom implementation on `TonConnectOptions.storage`. * * @example * ```ts * import type { IStorage } from '@tonconnect/sdk'; * * const memoryStorage = { * state: new Map(), * setItem(k, v) { this.state.set(k, v); return Promise.resolve(); }, * getItem(k) { return Promise.resolve(this.state.get(k) ?? null); }, * removeItem(k) { this.state.delete(k); return Promise.resolve(); }, * } satisfies IStorage & { state: Map }; * ``` */ export declare interface IStorage { /** * Persist `value` under `key`. Overwrites any existing value. * * @param key — string identifier, scoped per dApp. * @param value — value to save. */ setItem(key: string, value: string): Promise; /** * Read the value previously stored under `key`, or `null` if absent. * * @param key — string identifier set on a previous {@link IStorage.setItem} call. */ getItem(key: string): Promise; /** * Delete the value stored under `key`. A no-op if the key does not exist. * * @param key — string identifier to remove. */ removeItem(key: string): Promise; } export declare function isWalletConnectInitialized(): boolean; /** * Checks if `WalletInfo` is `WalletInfoInjectable` and dApp is opened inside this wallet's browser. * @param value WalletInfo to check. */ export declare function isWalletInfoCurrentlyEmbedded(value: WalletInfo): value is WalletInfoCurrentlyEmbedded; /** * Checks if `WalletInfo` is `WalletInfoInjectable` and `WalletInfo` is injected to the current webpage (`walletInfo.injected === true`). * @param value WalletInfo to check. */ export declare function isWalletInfoCurrentlyInjected(value: WalletInfo): value is WalletInfoCurrentlyInjected; /** * Checks if `WalletInfo` is `WalletInfoInjectable`, but doesn't check if it is injected to the page or not. * @param value WalletInfo to check. */ export declare function isWalletInfoInjectable(value: WalletInfo): value is WalletInfoInjectable; /** * @deprecated use `isWalletInfoInjectable` or `isWalletInfoCurrentlyInjected` instead. * @param value WalletInfo to check. */ export declare function isWalletInfoInjected(value: WalletInfo): value is WalletInfoInjected; /** * Checks if `WalletInfo` is `WalletInfoRemote`. * @param value WalletInfo to check. */ export declare function isWalletInfoRemote(value: WalletInfo): value is WalletInfoRemote; /** * Public contract of the TON Connect connector. * * @see [TON Connect overview (docs)](https://docs.ton.org/applications/ton-connect/overview) */ export declare interface ITonConnect { /** * `true` while a wallet session is active. Equivalent to `wallet !== null`. */ connected: boolean; /** Currently connected {@link Account}, or `null` when no wallet is connected. */ account: Account | null; /** Currently connected {@link Wallet}, or `null` when no wallet is connected. */ wallet: Wallet | null; /** * Fetch the wallets-list registry, merged with any JS-injectable wallets * detected on the page. * * @see [`wallets-list.md`](https://github.com/ton-blockchain/ton-connect/blob/main/spec/wallets-list.md) */ getWallets(): Promise; /** * Subscribe to connection state changes. The callback fires after every * connect, disconnect, restore. `errorsHandler`, when * provided, is called with a {@link TonConnectError} subclass when the * connector observes a connect failure (manifest fetch error, user * rejection, wrong network, missing features). * * @returns Unsubscribe function. Call it to stop receiving updates. */ onStatusChange(callback: (walletInfo: Wallet | null) => void, errorsHandler?: (err: TonConnectError) => void): () => void; /** * Begin a wallet-connect flow. * * - For an {@link WalletConnectionSourceHTTP} (or an array of bridge URLs): * returns the universal link to show as a QR code or open in a new tab. * The wallet's reply lands on {@link ITonConnect.onStatusChange}. * - For a {@link WalletConnectionSourceJS}: returns `void`; the call sends * the connect request to the injected wallet, which replies via * `onStatusChange`. * * @param wallet — connection source for a single wallet, or an array of * `{ bridgeUrl }` entries for a multi-wallet connection. * @param request — additional `ConnectItem`s to attach. * @param options — `openingDeadlineMS` deadline, `signal` for cancellation, * `embeddedRequest` to fold an action into the connect URL, `linkDisplayOnly` when the * call only builds a link to display, and the common `traceId` analytics id. */ connect[]>(wallet: T, request?: ConnectAdditionalRequest, options?: OptionalTraceable<{ /** Reject the connect attempt with `TonConnectError` after this many ms. */ openingDeadlineMS?: number; /** Abort the connect flow externally. */ signal?: AbortSignal; /** * Fold an action ({@link EmbeddedRequest}) into the connect URL. * * @see [Connect-and-act in one tap (docs)](https://docs.ton.org/applications/ton-connect/how-to/embedded-request) */ embeddedRequest?: ConsumableLike; /** * Set when this call exists only to render a link or QR code, not because a user * chose to connect. Such calls report `connection-link-generated` instead of * `connection-initiated`, so counting initiations does not count screens. */ linkDisplayOnly?: boolean; }>): T extends WalletConnectionSourceJS ? void : T extends WalletConnectionSourceWalletConnect ? void : string; /** * Try to restore the previous session from storage. Call this once on * dApp startup, before deciding whether to show the connect modal. * * Resolves when the restore attempt has settled — either with a successful * `onStatusChange` emission (session restored) or with the connector * remaining disconnected (no session, or the wallet ended it). */ restoreConnection(options?: OptionalTraceable<{ openingDeadlineMS?: number; signal?: AbortSignal; }>): Promise; /** * Pause the SSE bridge connection. * * @see {@link ITonConnect.unPauseConnection} */ pauseConnection(): void; /** Resume a connection paused with {@link ITonConnect.pauseConnection}. */ unPauseConnection(): Promise; /** * Constrain the network the connector will accept. Must be set **before** * calling {@link ITonConnect.connect} — attempting to change it while a * wallet is connected throws. * * If the wallet replies with a different chain id, the SDK aborts the * connection and surfaces `WalletWrongNetworkError` to * {@link ITonConnect.onStatusChange}'s error handler. * * Pass `undefined` to clear the restriction and accept any network. * * @param network — desired network. See {@link ChainId}. */ setConnectionNetwork(network?: ChainId): void; /** * End the session. Clears the local session state, fires the disconnected * `onStatusChange` event immediately, and sends a `disconnect` RPC to the * wallet so it can clean up its side too. * * @throws {@link WalletNotConnectedError} when no wallet is connected. */ disconnect(options?: OptionalTraceable<{ signal?: AbortSignal; }>): Promise; /** * Ask the connected wallet to sign **and broadcast** a transaction. * * @throws {@link WalletNotConnectedError} — no wallet is connected. * @throws {@link WalletNotSupportFeatureError} — wallet does not advertise the * required `SendTransaction` capabilities. * @throws {@link UserRejectsError} — user declined in the wallet. * @throws {@link WalletWrongNetworkError} — wallet network differs from the request. * @throws {@link TonConnectError} — bridge / validation error. * * @returns The signed BoC plus, when available, the `traceId` the SDK * propagated through the bridge. * * @see [Send a transaction (docs)](https://docs.ton.org/applications/ton-connect/how-to/send-transaction) */ sendTransaction(transaction: SendTransactionRequest, options?: OptionalTraceable<{ /** Called the moment the encrypted request is posted to the bridge. */ onRequestSent?: () => void; signal?: AbortSignal; }>): Promise>; /** * @deprecated Use `sendTransaction(transaction, options)` instead. * Provided so existing dApps keep compiling. */ sendTransaction(transaction: SendTransactionRequest, onRequestSent?: () => void): Promise>; /** * Ask the connected wallet to sign opaque data ({@link SignDataPayload}). * The signature is bound to the user's wallet address, the dApp's domain, * a timestamp, and the payload — verify on the backend or on-chain. * * @throws {@link WalletNotConnectedError} — no wallet is connected. * @throws {@link WalletNotSupportFeatureError} — wallet does not advertise the * requested `SignData.types`. * @throws {@link UserRejectsError} — user declined. * @throws {@link WalletWrongNetworkError} — wallet network differs from the request. * @throws {@link TonConnectError} — bridge / validation error. * * @returns The {@link SignDataResponse} plus, when available, the `traceId` * the SDK propagated through the bridge. * * @see [Sign data (docs)](https://docs.ton.org/applications/ton-connect/how-to/sign-data) */ signData(data: SignDataPayload, options?: OptionalTraceable<{ onRequestSent?: () => void; signal?: AbortSignal; }>): Promise>; /** * Ask the connected wallet to sign an internal message **without * broadcasting it**. * * Same payload shape as `sendTransaction`; supported by wallets that * advertise the `SignMessage` feature (typically Wallet V5). * * @throws {@link WalletNotConnectedError} — no wallet is connected. * @throws {@link WalletNotSupportFeatureError} — wallet does not advertise `SignMessage`. * @throws {@link UserRejectsError} — user declined. * @throws {@link WalletWrongNetworkError} — wallet network differs from the request. * @throws {@link TonConnectError} — bridge / validation error. * * @returns a signed BoC the dApp can wrap in an external * message and submit through a relayer (e.g. for a gasless jetton * transfer). * * @see [Sign and relay a message (gasless) (docs)](https://docs.ton.org/applications/ton-connect/how-to/sign-message-gasless) */ signMessage(message: SignMessageRequest, options?: OptionalTraceable<{ onRequestSent?: () => void; signal?: AbortSignal; }>): Promise>; /** * Current bridge session ID, or `null` if no session is open. */ getSessionId(): Promise; } /** * [TEP-74](https://github.com/ton-blockchain/TEPs/blob/master/text/0074-jettons-standard.md) * jetton transfer. The wallet resolves the user's jetton-wallet address from * `master`, builds the transfer body and attaches enough TON to pay for the * jetton-wallet execution. */ export declare interface JettonItem { type: 'jetton'; /** Jetton master contract address (friendly format). */ master: string; /** Recipient address (friendly format). */ destination: string; /** Jetton amount in elementary units. */ amount: string; /** * Nanocoins of TON to attach to the jetton-wallet call. */ attachAmount?: string; /** Where to refund excess TON. Defaults to the sender. */ responseDestination?: string; /** Raw one-cell BoC `custom_payload`, base64-encoded. */ customPayload?: string; /** * Nanocoins forwarded to the destination wallet — drives the * `transfer_notification` to the recipient. Defaults to `"1"` nanoTON. */ forwardAmount?: string; /** Raw one-cell BoC `forward_payload`, base64-encoded. */ forwardPayload?: string; /** Application-defined `query_id` for the transfer body. */ queryId?: string; } /** * Serialized form of a session keypair, used to persist a session across * page reloads. Both fields are hex-encoded (no `0x` prefix). Pass an * existing keypair into {@link SessionCrypto} to resume a session; omit it * to generate a fresh one. * * `client_id` on the bridge is `publicKey` itself. Keep `secretKey` * confidential — it grants the ability to decrypt messages addressed to * this client. * * @see [Client keypair (Session spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/session.md#client-keypair) */ export declare interface KeyPair { /** 32-byte public key, hex-encoded. */ publicKey: string; /** 32-byte secret key, hex-encoded. Must be kept private. */ secretKey: string; } /** * Thrown when no `storage` was specified in `TonConnectOptions` and a default * `localStorage` was not detected in the Node.js environment. */ export declare class LocalstorageNotFoundError extends TonConnectError { static readonly errorName: string; protected get info(): string; } /** * Thrown when the wallet does not support the requested method. */ export declare class MethodNotSupportedError extends TonConnectError { static readonly errorName: string; protected get info(): string; } /** * [TEP-62](https://github.com/ton-blockchain/TEPs/blob/master/text/0062-nft-standard.md) * NFT transfer. The wallet builds the `transfer#5fcc3d14` body addressed to the * NFT item contract. */ export declare interface NftItem { type: 'nft'; /** NFT item contract address (friendly format). */ nftAddress: string; /** New owner address (friendly format). */ newOwner: string; /** * Nanocoins of TON to attach. */ attachAmount?: string; /** Where to refund excess TON. */ responseDestination?: string; /** Raw one-cell BoC `custom_payload`, base64-encoded. */ customPayload?: string; /** Nanocoins forwarded to the new owner. */ forwardAmount?: string; /** Raw one-cell BoC `forward_payload`, base64-encoded. */ forwardPayload?: string; /** Application-defined `query_id` for the transfer body. */ queryId?: string; } /** * Wraps a value with an optional `traceId`. */ export declare type OptionalTraceable = { traceId?: string; } & T; /** * Thrown when passed hex is in incorrect format. */ export declare class ParseHexError extends TonConnectError { static readonly errorName: string; protected get info(): string; } /** * Removes the `ton-connect-` and `ton-connect-ui-` prefixes from the given string. */ export declare type RemoveTonConnectPrefix = T extends `ton-connect-ui-${infer Rest}` ? Rest : T extends `ton-connect-${infer Rest}` ? Rest : T; /** * Request TON Connect UI version. */ export declare type RequestVersionEvent = { /** * Event type. */ type: 'request-version'; }; /** * Marker filter for the wallet's * [`EmbeddedRequest`](https://github.com/ton-blockchain/ton-connect/blob/main/spec/connect.md#feature) * feature. The feature itself has no parameters; pass `{}` to require it. */ export declare type RequiredEmbeddedRequestFeature = {}; /** * Wallet capabilities the dApp depends on. * * Top-level keys combine as a logical AND — declaring `sendTransaction` and * `signMessage` requires both. A wallet matches when every requirement listed * appears in its {@link DeviceInfo.features}. * * @see [Filter wallets by required features (docs)](https://docs.ton.org/applications/ton-connect/how-to/filter-wallets) * @see [`Feature` (Connect spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/connect.md#feature) */ export declare type RequiredFeatures = { /** * Constraints on the wallet's `SendTransaction` feature. */ sendTransaction?: RequiredSendTransactionFeature; /** * Constraints on the wallet's `SignData` feature. */ signData?: RequiredSignDataFeature; /** * Constraints on the wallet's `SignMessage` feature. */ signMessage?: RequiredSignMessageFeature; /** * Require support for the embedded-request transport. The entry takes no * parameters: pass `{}`. */ embeddedRequest?: RequiredEmbeddedRequestFeature; }; /** * Filter for the wallet's [`SendTransaction`](https://github.com/ton-blockchain/ton-connect/blob/main/spec/connect.md#feature) * capability. */ export declare type RequiredSendTransactionFeature = { /** * Wallet's `maxMessages` must be greater than or equal to this value. */ minMessages?: number; /** * Require `extraCurrencySupported: true` on the wallet's `SendTransaction` * feature. */ extraCurrencyRequired?: boolean; /** * Every requested type must appear in the wallet's `itemTypes`. Use when * the dApp will send a {@link SendTransactionRequestWithItems} * request relying on `ton`, `jetton` or `nft` items. */ itemTypes?: StructuredItemType[]; }; /** * Filter for the wallet's [`SignData`](https://github.com/ton-blockchain/ton-connect/blob/main/spec/connect.md#feature) * capability. */ export declare type RequiredSignDataFeature = { /** * Every requested payload type must appear in the wallet's `types` list. * One of `'text'`, `'binary'`, `'cell'`. */ types: SignDataType[]; }; /** * Filter for the wallet's [`SignMessage`](https://github.com/ton-blockchain/ton-connect/blob/main/spec/connect.md#feature) * capability. Same shape as {@link RequiredSendTransactionFeature}; checked * against the wallet's `SignMessage` feature entry. */ export declare type RequiredSignMessageFeature = { /** Wallet's `maxMessages` must be greater than or equal to this value. */ minMessages?: number; /** Require `extraCurrencySupported: true` on the `SignMessage` feature. */ extraCurrencyRequired?: boolean; /** Every requested type must appear in the wallet's `SignMessage.itemTypes`. */ itemTypes?: StructuredItemType[]; }; /** * Response TON Connect UI version. */ export declare type ResponseVersionEvent = { /** * Event type. */ type: 'response-version'; /** * TON Connect UI version. */ version: string; }; /** [TEP-74](https://github.com/ton-blockchain/TEPs/blob/master/text/0074-jettons-standard.md) jetton transfer in RPC wire form. */ export declare interface RpcJettonItem { /** Item discriminator. */ type: 'jetton'; /** Jetton master contract address. */ master: string; /** Recipient address. */ destination: string; /** Jetton amount in elementary units (decimal string). */ amount: string; /** TON value to attach for transfer execution; wallet picks a default when omitted. */ attachAmount?: string; /** Where to refund excess TON. Defaults to the sender. */ responseDestination?: string; /** Raw one-cell BoC `custom_payload`, base64-encoded. */ customPayload?: string; /** Nanocoins forwarded to the destination wallet. Defaults to `"1"` nanoTON. */ forwardAmount?: string; /** Raw one-cell BoC `forward_payload`, base64-encoded. */ forwardPayload?: string; /** Application-defined `query_id` for the transfer body. */ queryId?: string; } /** * The set of methods a dApp can invoke after a successful connect. Wallets * accept the methods they advertise via {@link Feature}. * * @see [RPC specification](https://github.com/ton-blockchain/ton-connect/blob/main/spec/rpc.md) */ export declare type RpcMethod = 'disconnect' | 'sendTransaction' | 'signData' | 'signMessage'; /** [TEP-62](https://github.com/ton-blockchain/TEPs/blob/master/text/0062-nft-standard.md) NFT transfer in RPC wire form. */ export declare interface RpcNftItem { /** Item discriminator. */ type: 'nft'; /** NFT item contract address. */ nftAddress: string; /** New owner address. */ newOwner: string; /** TON value to attach for transfer execution; wallet picks a default when omitted. */ attachAmount?: string; /** Where to refund excess TON. Defaults to the sender. */ responseDestination?: string; /** Raw one-cell BoC `custom_payload`, base64-encoded. */ customPayload?: string; /** Nanocoins forwarded to the new owner. Defaults to `"1"` nanoTON. */ forwardAmount?: string; /** Raw one-cell BoC `forward_payload`, base64-encoded. */ forwardPayload?: string; /** Application-defined `query_id` for the transfer body. */ queryId?: string; } /** * Map from RPC method name to its request envelope. Used both as a type * registry and to derive {@link AppRequest} via index lookup. */ export declare type RpcRequests = { sendTransaction: SendTransactionRpcRequest; signData: SignDataRpcRequest; signMessage: SignMessageRpcRequest; disconnect: DisconnectRpcRequest; }; /** * Map from RPC method name to its success / error response envelope. * * Used to derive {@link WalletResponse}. */ export declare type RpcResponses = { sendTransaction: { error: SendTransactionRpcResponseError; success: SendTransactionRpcResponseSuccess; }; signData: { error: SignDataRpcResponseError; success: SignDataRpcResponseSuccess; }; signMessage: { error: SignMessageRpcResponseError; success: SignMessageRpcResponseSuccess; }; disconnect: { error: DisconnectRpcResponseError; success: DisconnectRpcResponseSuccess; }; }; /** * Wire-format structured items used inside JSON-RPC payloads and embedded-request * expansion. These match the shape that travels over the bridge / URL — field * casing follows the protocol (e.g. `extra_currency` snake_case). * * The rich, user-facing counterparts (with camelCase fields and SDK-level * conveniences) live in `@tonconnect/sdk` as `StructuredItem`. * * @see [`sendTransaction` § Structured items (RPC spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/rpc.md#sendtransaction) */ export declare type RpcStructuredItem = RpcTonItem | RpcJettonItem | RpcNftItem; /** Native TON transfer in RPC wire form. */ export declare interface RpcTonItem { /** Item discriminator. */ type: 'ton'; /** Destination address in TEP-2 user-friendly format. */ address: string; /** Nanocoins to send, as a decimal string. */ amount: string; /** Optional one-cell BoC body, base64-encoded. */ payload?: string; /** Optional one-cell BoC `StateInit`, base64-encoded. */ stateInit?: string; /** TEP-92 extra currencies: `currency_id` → decimal amount string. */ extra_currency?: { [k: number]: string; }; } /** * User action events. */ export declare type SdkActionEvent = VersionEvent | ConnectionEvent | ConnectionRestoringEvent | DisconnectionEvent | TransactionSigningEvent | DataSigningEvent | WalletModalOpenedEvent | SelectedWalletEvent | WalletPreselectedEvent | WalletSelectedEvent; /** * Represents the event triggered when the wallet is selected. */ export declare type SelectedWalletEvent = { /** * Event type. */ type: 'selected-wallet'; /** * The unique client identifier associated with the session or user. */ client_id: string | null; /** * A list of wallet identifiers that are currently visible in the modal. */ visible_wallets: string[]; wallets_menu: 'explicit_wallet' | 'main_screen' | 'other_wallets'; /** * Redirect method: tg_link, external_link */ wallet_redirect_method?: 'tg_link' | 'external_link'; /** * URL used to open the wallet */ wallet_redirect_link?: string; /** * Wallet type: 'tonkeeper', 'tonhub', etc. */ wallet_type: string | null; /** * Custom metadata containing versioning or contextual data for the modal. */ custom_data: Version; /** * Unique identifier used for tracking a specific user flow. */ trace_id: string | null; }; /** * Error codes the wallet may return from `sendTransaction`. * * @see [`sendTransaction` errors (RPC spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/rpc.md#sendtransaction) */ export declare enum SEND_TRANSACTION_ERROR_CODES { /** Unexpected wallet-side failure. */ UNKNOWN_ERROR = 0, /** Request payload is malformed. */ BAD_REQUEST_ERROR = 1, /** Wallet does not know the dApp / session. */ UNKNOWN_APP_ERROR = 100, /** User explicitly declined the transaction. */ USER_REJECTS_ERROR = 300, /** Wallet does not support the method. */ METHOD_NOT_SUPPORTED = 400 } export declare type SendTransactionFeature = { name: 'SendTransaction'; /** * Maximum number of messages the wallet accepts in a single request. */ maxMessages: number; /** * `true` if the wallet can attach extra currencies. Absent or * `false` means extra currencies are unsupported. */ extraCurrencySupported?: boolean; /** * Structured-item kinds the wallet accepts inside `items[]`. Absent means * only raw `messages[]` are supported. */ itemTypes?: StructuredItemType[]; }; export declare type SendTransactionFeatureDeprecated = 'SendTransaction'; /** * Payload of `sendTransaction` method. * * @see [Send a transaction (docs)](https://docs.ton.org/applications/ton-connect/how-to/send-transaction) * @see [`sendTransaction` (RPC spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/rpc.md#sendtransaction) */ export declare type SendTransactionRequest = SendTransactionRequestWithMessages | SendTransactionRequestWithItems; /** * Fields shared by both payload shapes of `sendTransaction` / `signMessage`. */ export declare interface SendTransactionRequestBase { /** * Deadline in unix epoch seconds. The wallet refuses the request after * this moment. */ validUntil: number; /** * Target [TON network identifier](https://github.com/ton-blockchain/ton-connect/blob/main/spec/connect.md#network_id). */ network?: ChainId; /** * Sender address in raw `:` format. * * @default {@link Account.address}. */ from?: string; } /** * Send a transaction using structured items. Use only when you * know the wallet advertises the needed {@link SendTransactionFeature.itemTypes}. * * @see {@link StructuredItem} * @see [Send a transaction § Structured items (docs)](https://docs.ton.org/applications/ton-connect/how-to/send-transaction#structured-items) */ export declare interface SendTransactionRequestWithItems extends SendTransactionRequestBase { /** * Structured items. The wallet builds the BoC for each. */ items: StructuredItem[]; messages?: never; } /** * Send a transaction using the raw `messages[]` payload. * * @see [Send a transaction § Raw messages (docs)](https://docs.ton.org/applications/ton-connect/how-to/send-transaction#raw-messages) */ export declare interface SendTransactionRequestWithMessages extends SendTransactionRequestBase { /** * Outgoing messages — at least one, no more than the wallet's * {@link SendTransactionFeature.maxMessages} (declared in `Wallet.device.features`). * * Submission is grouped (one signed external) but execution is not atomic: * each recipient contract is processed independently, so some messages can * fail or bounce while others succeed. */ messages: { /** * Destination address in [TEP-2](https://github.com/ton-blockchain/TEPs/blob/master/text/0002-address.md) * user-friendly base64url form. Wallets reject raw `0:` form. * The bounceable flag is taken from the address itself. */ address: string; /** Nanocoins to send, as a decimal string. */ amount: string; /** * Optional one-cell BoC `StateInit`, base64-encoded. */ stateInit?: string; /** Optional one-cell BoC body, base64-encoded. */ payload?: string; /** * Extra currencies to attach. */ extraCurrency?: { [k: number]: string; }; }[]; items?: never; } /** * Result of `sendTransaction` method. * * @see [`sendTransaction` response (RPC spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/rpc.md#sendtransaction) */ export declare interface SendTransactionResponse { /** * Base64-encoded BoC of the broadcasted external message. */ boc: string; } /** * RPC request to submit and broadcast a transaction. * * `params[0]` is a JSON-stringified payload that mirrors the SDK's * `SendTransactionRequest` (either raw `messages` OR structured `items`, * plus `valid_until`, `network`, and `from`). */ export declare interface SendTransactionRpcRequest { method: 'sendTransaction'; /** single-element tuple: the JSON-stringified transaction payload */ params: [string]; /** dApp-assigned request id; used to match the wallet response */ id: string; } /** * Wallet reply to a `sendTransaction` RPC. */ export declare type SendTransactionRpcResponse = SendTransactionRpcResponseSuccess | SendTransactionRpcResponseError; /** Failure envelope. */ export declare interface SendTransactionRpcResponseError extends WalletResponseTemplateError { error: { code: SEND_TRANSACTION_ERROR_CODES; message: string; data?: unknown; }; id: string; } /** * Success: `result` is the base64-encoded BoC of the external message. */ export declare interface SendTransactionRpcResponseSuccess extends WalletResponseTemplateSuccess { } /** * Implements the TON Connect session-encryption protocol on top of NaCl's * `crypto_box`. * * The protocol is symmetric: each side encrypts the messages it sends and * decrypts the messages it receives. On the dApp side that means encrypting * outgoing {@link AppMessage} and decrypting incoming {@link WalletMessage}; * the wallet does the reverse. * * @example * ```ts * import { SessionCrypto, Base64, hexToByteArray } from '@tonconnect/protocol'; * * // Generate a fresh session * const session = new SessionCrypto(); * const myClientId = session.sessionId; // hex public key (sent to the peer) * * // Encrypt an outgoing message for the peer * const ciphertext = session.encrypt( * JSON.stringify(message), * hexToByteArray(peerClientId) * ); * * // Decrypt an incoming message from the peer * const plaintext = session.decrypt( * Base64.decode(bridgeMessage.message).toUint8Array(), * hexToByteArray(bridgeMessage.from) * ); * ``` * * @see [Session protocol (Session spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/session.md) */ export declare class SessionCrypto { private readonly nonceLength; private readonly keyPair; /** * Bridge-level `client_id` — the public key as a 64-character * lowercase hex string. Share with the peer during connect; treat as * semi-private (do not publish broadly). */ readonly sessionId: string; /** * Reuse an existing {@link KeyPair} (resuming a session) or generate a * fresh one (`crypto_box.keyPair()`) when omitted. */ constructor(keyPair?: KeyPair); private createKeypair; private createKeypairFromString; private createNonce; /** * Encrypt `message` for `receiverPublicKey` using a fresh 24-byte random * nonce. Returns `nonce || ciphertext` as raw bytes; base64-encode this * value before placing it in the bridge `POST /message` body. */ encrypt(message: string, receiverPublicKey: Uint8Array): Uint8Array; /** * Decrypt the `nonce || ciphertext` blob received from the bridge. * Throws if `nacl.box.open` rejects the message — wrong key, truncated * input or tampered ciphertext. */ decrypt(message: Uint8Array, senderPublicKey: Uint8Array): string; /** * Export the underlying keypair as a {@link KeyPair} of hex strings. * Persist this in dApp / wallet storage to resume the session later. */ stringifyKeypair(): KeyPair; } export declare type SessionInfo = { clientId: string | null; walletId: string | null; }; /** * Error codes the wallet may return from `signData`. * * @see [`signData` errors (RPC spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/rpc.md#signdata) */ export declare enum SIGN_DATA_ERROR_CODES { /** Unexpected wallet-side failure. */ UNKNOWN_ERROR = 0, /** Invalid request payload. */ BAD_REQUEST_ERROR = 1, /** Wallet does not know the dApp / session. */ UNKNOWN_APP_ERROR = 100, /** User explicitly declined. */ USER_REJECTS_ERROR = 300, /** Wallet does not support `signData` method or the requested `type`. */ METHOD_NOT_SUPPORTED = 400 } /** * Error codes the wallet may return from `signMessage`. * * @see [`signMessage` errors (RPC spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/rpc.md#signmessage) */ export declare enum SIGN_MESSAGE_ERROR_CODES { /** Unexpected wallet-side failure. */ UNKNOWN_ERROR = 0, /** Invalid request payload. */ BAD_REQUEST_ERROR = 1, /** Wallet does not know the dApp / session. */ UNKNOWN_APP_ERROR = 100, /** User explicitly declined. */ USER_REJECTS_ERROR = 300, /** Wallet does not support `signMessage`. */ METHOD_NOT_SUPPORTED = 400 } export declare type SignDataFeature = { name: 'SignData'; types: SignDataType[]; }; /** * Discriminated payload for `signData`. * * @see [`signData` payload (RPC spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/rpc.md#signdata) */ export declare type SignDataPayload = { /** Target TON network; if mismatching the wallet's active network, the wallet refuses to sign. */ network?: ChainId; /** Optional signer address. */ from?: string; } & (SignDataPayloadText | SignDataPayloadBinary | SignDataPayloadCell); export declare type SignDataPayloadBinary = { type: 'binary'; /** Base64-encoded bytes. */ bytes: string; }; export declare type SignDataPayloadCell = { type: 'cell'; /** TL-B schema string describing the cell layout. */ schema: string; /** Base64-encoded cell BoC. */ cell: string; }; export declare type SignDataPayloadText = { type: 'text'; /** UTF-8 text to sign. */ text: string; }; /** * Result of `signData` method. * * @see [Sign data (docs)](https://docs.ton.org/applications/ton-connect/how-to/sign-data) * @see [`signData` response (RPC spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/rpc.md#signdata) */ export declare type SignDataResponse = { /** Base64-encoded Ed25519 signature. */ signature: string; /** Signer's wallet address in raw form (`:`). */ address: string; /** * Unix epoch seconds (UTC) at signing time. */ timestamp: number; /** * App domain — the URL host, without scheme or encoding. */ domain: string; /** * The payload from the request, echoed back verbatim. */ payload: SignDataPayload; }; /** * RPC request to sign arbitrary application data and return a wallet-provided * signature. * * `params[0]` is a JSON-stringified {@link SignDataPayload} — one of three * discriminated shapes (`text`, `binary`, `cell`). */ export declare interface SignDataRpcRequest { method: 'signData'; /** single-element tuple: the JSON-stringified sign-data payload */ params: [string]; /** dApp-assigned request id; used to match the wallet response */ id: string; } /** * Wallet reply to a `signData` RPC. */ export declare type SignDataRpcResponse = SignDataRpcResponseSuccess | SignDataRpcResponseError; export declare interface SignDataRpcResponseError extends WalletResponseTemplateError { error: { code: SIGN_DATA_ERROR_CODES; message: string; }; id: string; } /** * @see [`signData` signature (RPC spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/rpc.md#signature--text-and-binary) */ export declare interface SignDataRpcResponseSuccess { result: { /** Base64-encoded Ed25519 signature. */ signature: string; /** Raw wallet address (`:`). */ address: string; /** Unix epoch seconds (UTC) at signing time. */ timestamp: number; /** App domain from manifest bound into the signature. */ domain: string; /** Echo of the payload from the request. */ payload: SignDataPayload; }; /** Echo of the request `id`. */ id: string; } export declare type SignDataType = 'text' | 'binary' | 'cell'; export declare type SignMessageFeature = { name: 'SignMessage'; /** * Maximum number of messages the wallet will accept inside a single * `signMessage` request. */ maxMessages: number; /** `true` if extra currencies are supported in the signed message. */ extraCurrencySupported?: boolean; /** * Structured-item kinds the wallet accepts. Absent means only raw * `messages[]` are supported. */ itemTypes?: StructuredItemType[]; }; /** * Payload for `ITonConnect.signMessage` / `TonConnectUI.signMessage`. * * Identical in shape to {@link SendTransactionRequest}. * * @see [Sign and relay a message (gasless) (docs)](https://docs.ton.org/applications/ton-connect/how-to/sign-message-gasless) * @see [`signMessage` (RPC spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/rpc.md#signmessage) */ export declare type SignMessageRequest = SendTransactionRequest; /** * Result of `signMessage` method. * * * @see [Sign and relay a message (gasless) (docs)](https://docs.ton.org/applications/ton-connect/how-to/sign-message-gasless) * @see [`signMessage` response (RPC spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/rpc.md#signmessage) */ export declare interface SignMessageResponse { /** * Base64-encoded BoC of the signed internal message. The wallet does * **not** broadcast. Submit it through a relayer. */ internalBoc: string; } /** * RPC request to sign an internal message **without** broadcasting it. * * `params[0]` is a JSON-stringified payload identical in shape to * {@link SendTransactionRpcRequest}. * * @see [`signMessage` (RPC spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/rpc.md#signmessage) */ export declare interface SignMessageRpcRequest { method: 'signMessage'; /** single-element tuple: the JSON-stringified payload */ params: [string]; /** dApp-assigned request id; used to match the wallet response */ id: string; } /** * Wallet reply to a `signMessage` RPC. Success carries the signed internal * message BoC; error narrows the `code` enum to * {@link SIGN_MESSAGE_ERROR_CODES}. */ export declare type SignMessageRpcResponse = SignMessageRpcResponseSuccess | SignMessageRpcResponseError; export declare interface SignMessageRpcResponseError extends WalletResponseTemplateError { error: { code: SIGN_MESSAGE_ERROR_CODES; message: string; data?: unknown; }; id: string; } export declare interface SignMessageRpcResponseSuccess { result: { /** * Base64-encoded BoC of the signed internal message. */ internalBoc: string; }; /** Echo of the request `id`. */ id: string; } /** * Split `array` at `index` and return the two halves as fresh * `Uint8Array`s. */ export declare function splitToUint8Arrays(array: Uint8Array, index: number): [Uint8Array, Uint8Array]; /** * Structured items describe **what** the transaction should do (send TON, * transfer a jetton, transfer an NFT) and let the wallet build the BoC. * * Wallets advertise structured-item support through the * {@link SendTransactionFeature.itemTypes} and {@link SignMessageFeature.itemTypes} features. * * @see [Send a transaction § Structured items (docs)](https://docs.ton.org/applications/ton-connect/how-to/send-transaction#structured-items) * @see [Structured items wallet guide](https://github.com/ton-blockchain/ton-connect/blob/main/guides/structured-items.md) */ export declare type StructuredItem = TonItem | JettonItem | NftItem; /** * Item kinds a wallet may accept inside `sendTransaction.items` / * `signMessage.items`. Maps to the structured wallet-built transfers: * native TON, [TEP-74](https://github.com/ton-blockchain/TEPs/blob/master/text/0074-jettons-standard.md) jetton, * [TEP-62](https://github.com/ton-blockchain/TEPs/blob/master/text/0062-nft-standard.md) NFT. */ export declare type StructuredItemType = 'ton' | 'jetton' | 'nft'; /** * Basic Telegram user information. */ export declare type TelegramUser = { /** Unique Telegram user ID. */ id: number; /** Whether the user has Telegram Premium. */ isPremium: boolean; }; /** * Telegram Mini App environment detection. * * Lives in core rather than in `@tonconnect/ui` so that `client_environment` is answered the * same way for every dApp. Previously only the UI package could tell a Mini App from a web page, * so dApps on the bare SDK reported an empty value — and that is exactly the population the * connection events exist to make visible. * * Everything is computed once, on first use rather than at import: resolving it reads * `location.hash` and both reads and writes `sessionStorage`, which should not happen merely * because someone imported the SDK. */ export declare type TmaPlatform = 'android' | 'ios' | 'macos' | 'tdesktop' | 'weba' | 'web' | 'unknown'; /** Hex-encode a byte array, lowercase, no `0x` prefix. */ export declare function toHexString(byteArray: Uint8Array): string; export declare interface TonAddressItem { name: 'ton_addr'; /** * Desired TON network global_id the dApp wants to connect on. A hint only; * the network-mismatch alert is enforced at request time * (`sendTransaction` / `signData`), not at connect. * * @see {@link ChainId} */ network?: ChainId; } /** * Reply for the `ton_addr` connect item — the connected account. * * `publicKey` and `walletStateInit` are untrusted hints. Verifiers MUST * re-derive the public key from `walletStateInit` (or via on-chain * `get_public_key`) and check that `contractAddress(stateInit) === address` * before trusting it. */ export declare interface TonAddressItemReply { name: 'ton_addr'; /** Raw TON address (`:`). */ address: string; /** TON network the account belongs to. */ network: ChainId; /** Base64 BoC of the wallet contract `StateInit`. */ walletStateInit: string; /** public key as a hex string (without `0x`). Untrusted. */ publicKey: string; } /** * Headless TON Connect connector — implements the {@link ITonConnect} contract. * Wraps the protocol handshake and the HTTP / JS bridge / WalletConnect transports. * * @example * ```ts * import TonConnect from '@tonconnect/sdk'; * * const connector = new TonConnect({ * manifestUrl: 'https://example.com/tonconnect-manifest.json', * }); * ``` */ declare class TonConnect implements ITonConnect { private desiredChainId; private static readonly walletsList; /** * `true` when a wallet identified by `walletJSKey` exposes a JS bridge on * the current page. The fastest way to detect a browser extension before * deciding which connect source to build. * * @param walletJSKey — value of the wallet's `jsBridgeKey` in the wallets list. */ static isWalletInjected: (walletJSKey: string) => boolean; /** * `true` when the dApp is running inside the named wallet's in-app * browser. Use it to pick the JS-bridge transport automatically and skip * the QR-code modal. * * @param walletJSKey — value of the wallet's `jsBridgeKey` in the wallets list. */ static isInsideWalletBrowser: (walletJSKey: string) => boolean; /** * Fetch the wallets-list registry without instantiating a connector. * Equivalent to {@link ITonConnect.getWallets} but usable before * constructing a `TonConnect`. */ static getWallets(): Promise; /** * Emits user action event to the EventDispatcher. By default, it uses `window.dispatchEvent` for browser environment. * @private */ private readonly tracker; private readonly walletsList; private analytics?; private readonly environment; private readonly dappSettings; private readonly bridgeConnectionStorage; private _wallet; private provider; private statusChangeSubscriptions; private statusChangeErrorSubscriptions; private readonly walletsRequiredFeatures; private abortController?; private pendingEmbeddedRequestMethod?; /** * Shows if the wallet is connected right now. */ get connected(): boolean; /** * Current connected account or null if no account is connected. */ get account(): Account | null; /** * Current connected wallet or null if no account is connected. */ get wallet(): Wallet | null; private set wallet(value); /** * Create a new connector. See {@link TonConnectOptions} for every option; * the most common shape is `{ manifestUrl }` in the browser, and * `{ manifestUrl, storage }` in Node.js / non-browser hosts. * * @throws `DappMetadataError` when `manifestUrl` is omitted and * `window.location.origin` is not available. */ constructor(options?: TonConnectOptions); /** * Returns available wallets list. */ getWallets(): Promise; /** * Allows to subscribe to connection status changes and handle connection errors. * @param callback will be called after connections status changes with actual wallet or null. * @param errorsHandler (optional) will be called with some instance of TonConnectError when connect error is received. * @returns unsubscribe callback. */ onStatusChange(callback: (wallet: Wallet | null) => void, errorsHandler?: (err: TonConnectError) => void): () => void; /** * Generates universal link for an external wallet and subscribes to the wallet's bridge, or sends connect request to the injected wallet. * @param wallet wallet's bridge url and universal link for an external wallet or jsBridge key for the injected wallet. * @param request (optional) additional request to pass to the wallet while connect (currently only ton_proof is available). * @param options (optional) openingDeadlineMS for the connection opening deadline and signal for the connection abort. * @returns universal link if external wallet was passed or void for the injected wallet. */ connect[]>(wallet: T, options?: OptionalTraceable<{ request?: ConnectAdditionalRequest; openingDeadlineMS?: number; signal?: AbortSignal; embeddedRequest?: ConsumableLike; /** * Set when this call exists only to render a link or QR code, not because a user * chose to connect. Such calls report `connection-link-generated` instead of * `connection-initiated`, so counting initiations does not count screens. */ linkDisplayOnly?: boolean; }>): T extends WalletConnectionSourceJS ? void : T extends WalletConnectionSourceWalletConnect ? void : string; /** @deprecated use connect(wallet, options) instead */ connect[]>(wallet: T, request?: ConnectAdditionalRequest, options?: OptionalTraceable<{ openingDeadlineMS?: number; signal?: AbortSignal; embeddedRequest?: ConsumableLike; /** * Set when this call exists only to render a link or QR code, not because a user * chose to connect. Such calls report `connection-link-generated` instead of * `connection-initiated`, so counting initiations does not count screens. */ linkDisplayOnly?: boolean; }>): T extends WalletConnectionSourceJS ? void : T extends WalletConnectionSourceWalletConnect ? void : string; /** * Try to restore existing session and reconnect to the corresponding wallet. Call it immediately when your app is loaded. */ restoreConnection(options?: OptionalTraceable<{ openingDeadlineMS?: number; signal?: AbortSignal; }>): Promise; /** * Asks connected wallet to sign and send the transaction. * @param transaction transaction to send. * @param options (optional) onRequestSent will be called after the request was sent to the wallet and signal for the transaction abort. * @returns signed transaction boc that allows you to find the transaction in the blockchain. * If user rejects transaction, method will throw the corresponding error. */ sendTransaction(transaction: SendTransactionRequest, options?: OptionalTraceable<{ onRequestSent?: () => void; signal?: AbortSignal; }>): Promise>; /** @deprecated use sendTransaction(transaction, options) instead */ sendTransaction(transaction: SendTransactionRequest, onRequestSent?: () => void): Promise>; /** * Sends a request to the wallet and reports a failure that produced no * wallet response through `trackFailure` before rethrowing it. Wallet error * responses are tracked by the caller, and a failure of the dApp's own * `onRequestSent` is not a signing failure, so both pass through here. */ private sendRequestTrackingTransport; private extractRequiredFeatures; signData(data: SignDataPayload, options?: OptionalTraceable<{ onRequestSent?: () => void; signal?: AbortSignal; }>): Promise>; signMessage(message: SignMessageRequest, options?: OptionalTraceable<{ onRequestSent?: () => void; signal?: AbortSignal; }>): Promise>; /** * Set desired network for the connection. Can only be set before connecting. * If wallet connects with a different chain, the SDK will throw an error and abort connection. * @param network desired network id (e.g., '-239', '-3', or custom). Pass undefined to allow any network. */ setConnectionNetwork(network?: ChainId): void; /** * Disconnect from the connected wallet and drop current session. */ disconnect(options?: OptionalTraceable<{ signal?: AbortSignal; }>): Promise; /** * Gets the current session ID if available. * @returns session ID string or null if not available. */ getSessionId(): Promise; private getSessionInfo; private buildMessagesRpcPayload; private buildItemsRpcPayload; /** * Pause bridge HTTP connection. Might be helpful, if you want to pause connections while browser tab is unfocused, * or if you use SDK with NodeJS and want to save server resources. */ pauseConnection(): void; /** * Unpause bridge HTTP connection if it is paused. */ unPauseConnection(): Promise; private addWindowFocusAndBlurSubscriptions; private initAnalytics; private createProvider; private walletEventsListener; private onWalletConnected; private onWalletConnectError; private onWalletDisconnected; private checkConnection; private createConnectRequest; } export { TonConnect } export default TonConnect; /** * Base class for every error thrown by `@tonconnect/sdk`. Catch it to handle * TON Connect failures uniformly. * * @example * ```ts * try { * await connector.sendTransaction(tx); * } catch (e) { * if (e instanceof TonConnectError) { * // wallet error, validation error, user rejection — all subclass this. * } * } * ``` */ export declare class TonConnectError extends Error { private static prefix; /** * Class name as a string literal, so it survives the class renaming a dApp's * minifier applies. Every SDK error class declares its own; it becomes the * error's `name` and the name in its `message`. */ static readonly errorName: string; /** * The wallet's own error, when this error was built from a wallet * response. Absent for errors raised by the SDK itself. */ readonly walletError?: WalletErrorDetail; protected get info(): string; constructor(message?: string, options?: { cause?: T; walletError?: WalletErrorDetail; }); } /** * Constructor options for the `TonConnect` connector. * * For most browser dApps `{ manifestUrl }` is enough; the SDK fills in * `localStorage`, fetches the canonical wallets list, and runs analytics in * the default `'telemetry'` mode. */ export declare interface TonConnectOptions { /** * HTTPS URL of the dApp's `tonconnect-manifest.json`. The wallet fetches * this file before showing the connect prompt to extract the dApp's name, * icon and policy URLs. If omitted, the SDK falls back to * `${window.location.origin}/tonconnect-manifest.json`. * * @see [App manifest spec](https://github.com/ton-blockchain/ton-connect/blob/main/spec/manifest.md) */ manifestUrl?: string; /** * Storage backend for protocol state (session keys, last connected * wallet). Defaults to `window.localStorage` in the browser. Required * when running the SDK in Node.js. */ storage?: IStorage; /** * Custom event dispatcher for user-action events. Defaults to * `window.dispatchEvent` in the browser, emitting `CustomEvent`s prefixed * with `ton-connect-`. */ eventDispatcher?: EventDispatcher; /** * Override the wallets-list JSON source. Must point to a file matching the * [wallets-v2 schema](https://github.com/ton-connect/wallets-list). * * @default 'https://config.ton.org/wallets-v2.json' */ walletsListSource?: string; /** * In-memory cache TTL for the fetched wallets list, in milliseconds. * `Infinity` (default) caches forever for the lifetime of the page. * * @default Infinity */ walletsListCacheTTLMs?: number; /** * Required wallet capabilities. Wallets that do not advertise every * requested feature are hidden from the picker (and rejected at connect * time if the user selects one through a custom flow). * * @see [Filter wallets by required features (docs)](https://docs.ton.org/applications/ton-connect/how-to/filter-wallets) */ walletsRequiredFeatures?: RequiredFeatures; /** * Disable the automatic pause / unpause of the SSE bridge connection * driven by `document.visibilitychange`. */ disableAutoPauseConnection?: boolean; /** * Override the runtime environment (platform, user-agent, Telegram user * context). The SDK auto-detects in browsers; pass an {@link IEnvironment} * implementation when embedding the SDK in a non-standard host. */ environment?: IEnvironment; /** * Analytics configuration. */ analytics?: AnalyticsSettings; } /** * Native TON transfer. */ export declare interface TonItem { type: 'ton'; /** * Destination address in [TEP-2](https://github.com/ton-blockchain/TEPs/blob/master/text/0002-address.md) * user-friendly base64url form. The bounceable flag is taken from the * address itself. */ address: string; /** Nanocoins to send, as a decimal string (e.g. `"5000000"` for 0.005 TON). */ amount: string; /** Optional one-cell BoC body, base64-encoded. Omit for a plain transfer. */ payload?: string; /** * Optional one-cell BoC `StateInit`, base64-encoded. Use it to deploy a * contract together with the value transfer. */ stateInit?: string; /** * Extra currencies to attach: map of TEP-92 currency id (decimal integer * key) to amount in elementary units (decimal string value). */ extraCurrency?: { [k: number]: string; }; } /** * Ask the wallet for a `ton_proof` signature binding the connected account, * the dApp domain and a server-issued nonce. dApps use the reply to * authenticate the user. * * @see [Address proof signature (`ton_proof`) (Connect spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/connect.md#address-proof-signature-ton_proof) */ export declare interface TonProofItem { name: 'ton_proof'; /** * Payload to embed in the signed message. */ payload: string; } /** * Reply for the `ton_proof` connect item. Either a success carrying the * signed proof or a per-item error when the wallet doesn't support the item. */ export declare type TonProofItemReply = TonProofItemReplySuccess | TonProofItemReplyError; export declare type TonProofItemReplyError = ConnectItemReplyError; /** * Successful `ton_proof` reply. `proof` carries the Ed25519 signature plus * the bound fields needed to reconstruct the signed bytes on the verifier * side. * * @see [Address proof signature (Connect spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/connect.md#address-proof-signature-ton_proof) */ export declare interface TonProofItemReplySuccess { name: 'ton_proof'; proof: { /** Unix epoch seconds at signing time. */ timestamp: number; /** App domain bound into the signature. */ domain: { /** Length of `value` in UTF-8 bytes. */ lengthBytes: number; /** Domain name, without scheme or encoding. */ value: string; }; /** dApp-provided payload (typically a server-issued nonce). */ payload: string; /** Base64-encoded Ed25519 signature. */ signature: string; }; } /** * Convert a raw `:` TON address into the URL-safe, * non-bounceable user-friendly form (`UQ…` on mainnet, `0Q…` on testnet). * * @param hexAddress — raw address, e.g. `'0:348bcf...0415f'`. * @param testOnly — set the test-only flag; Defaults to `false`. * @returns Base64url-encoded user-friendly address. * * @see [User-friendly address format](https://docs.ton.org/blockchain-basics/primitives/addresses/formats#user-friendly-format) */ export declare function toUserFriendlyAddress(hexAddress: string, testOnly?: boolean): string; /** * Wraps a value with a required `traceId` — a UUID * used to correlate logs and analytics across the dApp, bridge and wallet for * one user-visible operation. * * @see [`trace_id` (Bridge spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/bridge.md#trace_id--analytics-correlation) */ export declare type Traceable = { traceId: string; } & T; /** * Transaction information. */ export declare type TransactionFullInfo = Omit & { messages: TransactionFullMessage[]; }; /** * Transaction message. */ export declare type TransactionFullMessage = { /** * Recipient address. */ address: string | null; /** * Transfer amount. */ amount: string | null; /** * Message payload */ payload: string | null; /** * Message state init */ state_init: string | null; }; /** * Transaction information. */ export declare type TransactionInfo = { /** * Transaction validity time in unix timestamp. */ valid_until: string | null; /** * Sender address. */ from: string | null; /** * Transaction messages. */ messages: TransactionMessage[]; }; /** * Transaction message. */ export declare type TransactionMessage = { /** * Recipient address. */ address: string | null; /** * Transfer amount. */ amount: string | null; }; /** * Initial transaction event when a user initiates a transaction. */ export declare type TransactionSentForSignatureEvent = { /** * Event type. */ type: 'transaction-sent-for-signature'; /** * Unique identifier used for tracking a specific user flow. */ trace_id?: string | null; } & ConnectionInfo & TransactionInfo; /** * Transaction signed event when a user successfully signed a transaction. */ export declare type TransactionSignedEvent = { /** * Event type. */ type: 'transaction-signed'; /** * Connection success flag. */ is_success: true; /** * Signed transaction. */ signed_transaction: string; /** * Unique identifier used for tracking a specific user flow. */ trace_id?: string | null; } & ConnectionInfo & TransactionInfo; /** * Transaction events. */ export declare type TransactionSigningEvent = TransactionSentForSignatureEvent | TransactionSignedEvent | TransactionSigningFailedEvent; /** * Transaction error event when a user cancels a transaction or there is an error during the transaction process. */ export declare type TransactionSigningFailedEvent = { /** * Event type. */ type: 'transaction-signing-failed'; /** * Connection success flag. */ is_success: false; /** * Reason for the error. */ error_message: string; /** * Error code. */ error_code: SEND_TRANSACTION_ERROR_CODES | null; /** * Unique identifier used for tracking a specific user flow. */ trace_id?: string | null; } & ConnectionInfo & TransactionFullInfo; /** * Thrown when the wallet returns `UNKNOWN_APP` (code 100): the session or app is unknown to the wallet. */ export declare class UnknownAppError extends TonConnectError { static readonly errorName: string; protected get info(): string; } /** * Unhanded unknown error. */ export declare class UnknownError extends TonConnectError { static readonly errorName: string; } /** * Thrown when user rejects the action in the wallet. */ export declare class UserRejectsError extends TonConnectError { static readonly errorName: string; protected get info(): string; } /** * The MIT License (MIT) * * Copyright (c) 2010-2020 Robert Kieffer and other contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ export declare type UUIDTypes = string | TBuf; export declare function UUIDv7(options?: Version7Options, buf?: undefined, offset?: number): string; export declare function UUIDv7(options: Version7Options | undefined, buf: TBuf, offset?: number): TBuf; /** * Version of the TON Connect SDK and TON Connect UI. */ export declare type Version = { /** * TON Connect SDK version. */ ton_connect_sdk_lib: string | null; /** * TON Connect UI version. */ ton_connect_ui_lib: string | null; }; export declare type Version7Options = { random?: Uint8Array; msecs?: number; seq?: number; rng?: () => Uint8Array; }; /** * Version events. */ export declare type VersionEvent = RequestVersionEvent | ResponseVersionEvent; /** * The connected wallet as seen by the dApp. Returned by `ITonConnect.wallet` * and emitted on every `onStatusChange` callback after a successful connect; * `null` while no wallet is connected. * * @see [Connect a wallet (docs)](https://docs.ton.org/applications/ton-connect/how-to/connect) */ export declare interface Wallet { /** * Metadata reported by the wallet during the connect handshake — platform, * application name and version, max supported protocol version, and the * list of advertised features. * * @see [`DeviceInfo` (Connect spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/connect.md#deviceinfo) */ device: DeviceInfo; /** * Transport carrying the session. * * - `'http'` — the wallet is reached through the HTTP (SSE) bridge listed in * the wallets registry. dApp and wallet typically run on different devices. * - `'injected'` — the wallet exposes a JS bridge object on `window` (a * browser extension, or the dApp running inside the wallet's webview). */ provider: 'http' | 'injected'; /** * Account the user picked during connect. */ account: Account; /** * Replies for the optional [`ConnectItem`s](https://github.com/ton-blockchain/ton-connect/blob/main/spec/connect.md#connectrequest) * the dApp requested in addition to `ton_addr`. */ connectItems?: { /** * `ton_proof` reply, present only when the dApp requested it via {@link ConnectAdditionalRequest}. */ tonProof?: TonProofItemReply; }; /** * Result of an embedded request, when one was folded into the connect URL. * * Set only if the SDK encoded an * [`EmbeddedRequest`](https://docs.ton.org/applications/ton-connect/how-to/embedded-request) * into the connect URL, and the wallet advertises the * `EmbeddedRequest` feature and processed it during connect. * * Absence means the wallet completed only the connect step. */ embeddedResponse?: EmbeddedResponse; } /** * Thrown when wallet connection called but wallet already connected. */ export declare class WalletAlreadyConnectedError extends TonConnectError { static readonly errorName: string; protected get info(): string; } /** * Selector passed to `ITonConnect.connect()` that tells the SDK *how* to reach * a specific wallet. Discriminated union of the three transports the protocol * supports. * * @see [`bridge.md` (Bridge spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/bridge.md) */ export declare type WalletConnectionSource = WalletConnectionSourceHTTP | WalletConnectionSourceJS | WalletConnectionSourceWalletConnect; /** * Connect via the wallet's HTTP (SSE) bridge plus a universal link. * * Both fields are sourced from the wallets list entry — see * [`wallets-list.md`](https://github.com/ton-blockchain/ton-connect/blob/main/spec/wallets-list.md). */ export declare interface WalletConnectionSourceHTTP { /** * HTTPS base of the wallet's universal link, e.g. * `'https://app.tonkeeper.com/ton-connect'`. The SDK appends the connect * parameters (`v`, `id`, `r`, optional `ret`, `trace_id`, `e`). */ universalLink: string; /** * URL of the wallet's HTTP (SSE) bridge, e.g. * `'https://connect.ton.org/bridge'`. */ bridgeUrl: string; } /** What {@link describeWalletConnectionSource} could determine about a connection source. */ export declare interface WalletConnectionSourceInfo { kind: WalletConnectionSourceKind; /** Set for `js-embedded` and `js-injected`. */ jsBridgeKey?: string; /** Set for `http-specific-wallet`. */ bridgeUrl?: string; } /** * Connect via an injected JS bridge — the wallet is a browser extension or the * dApp is running inside the wallet's webview. */ export declare interface WalletConnectionSourceJS { /** * Name of the `window` property where the wallet exposes its * `TonConnectBridge` object. For example, `jsBridgeKey: 'tonkeeper'` * resolves to `window.tonkeeper.tonconnect`. */ jsBridgeKey: string; } /** * How a connection was initiated, derived from what was handed to `connect()`. * * Values are prefixed by transport so the transport axis stays recoverable — `js-*` covers the * injected JS bridge, `http-*` the HTTP (SSE) bridge — while the suffix carries what actually * differs within it. * * - `js-embedded` — the dApp is running inside this wallet's own browser. * - `js-injected` — the wallet exposes a JS bridge on the page, typically an extension. * - `http-specific-wallet` — one named wallet, reached via its own bridge and universal link. * - `http-any-wallet` — the universal `tc://` link, which any wallet can answer; none chosen yet. * - `wallet-connect` — the WalletConnect transport. * * `embedded` and `injected` share the {@link WalletConnectionSourceJS} shape, so the shape alone * cannot separate them — see {@link describeWalletConnectionSource}. */ export declare type WalletConnectionSourceKind = 'js-embedded' | 'js-injected' | 'http-specific-wallet' | 'http-any-wallet' | 'wallet-connect'; /** * Connect via the WalletConnect transport. Requires {@link initializeWalletConnect} * to have been called once at app startup. */ export declare interface WalletConnectionSourceWalletConnect { type: 'wallet-connect'; } /** * Metadata information about your application that will be displayed to users during WalletConnect pairing. */ export declare type WalletConnectMetadata = { /** * The name of your application. * @example 'My DApp' */ name: string; /** * A brief description of your application. * @example 'My awesome TON DApp' */ description: string; /** * The URL of your application. This is used as the domain for ton_proof authentication. * @example 'https://mydapp.com' */ url: string; /** * An array of icon URLs representing your application. These icons are shown in wallet interfaces. * @example ['https://mydapp.com/icon-192.png', 'https://mydapp.com/icon-512.png'] */ icons: string[]; }; /** * Configuration options for initializing WalletConnect integration. */ export declare type WalletConnectOptions = { /** * Your WalletConnect project ID. Get one at https://dashboard.reown.com/ * @example 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6' */ projectId: string; /** * Metadata about your application that will be displayed to users. */ metadata: WalletConnectMetadata; }; /** * The error a wallet returned, as it arrived. Present only on errors built * from a wallet response. */ export declare interface WalletErrorDetail { /** Wallet error code from the TON Connect spec. */ code: number; /** Wallet error message; empty when the wallet sent none. */ message: string; /** Wallet-provided `data`, when present. */ data?: unknown; /** `id` of the wallet response, when present. */ responseId?: string; /** * Set when the wallet rejected the request instead of answering with an * error response, and the SDK rebuilt the response from the rejection. */ normalized?: true; } /** * Server-initiated events the wallet emits to the dApp. * * - {@link ConnectEvent} — `connect` success or `connect_error`. Emitted * in response to a `ConnectRequest`. * - {@link DisconnectEvent} — wallet-initiated session teardown. * * @see [Wallet events (RPC spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/rpc.md#wallet-events) */ export declare type WalletEvent = ConnectEvent | DisconnectEvent; export declare type WalletInfo = WalletInfoRemote | WalletInfoInjectable | (WalletInfoRemote & WalletInfoInjectable); /** * Common fields shared by every wallet returned from the wallets list. * * @see [Wallets list (spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/wallets-list.md) */ export declare interface WalletInfoBase { /** Human-readable display name shown in the wallet picker. */ name: string; /** * Wallet identifier — equals the {@link DeviceInfo.appName} reported by the * connected {@link Wallet} at runtime. */ appName: string; /** * HTTPS URL of the wallet icon. 288×288 PNG on a non-transparent * background, no rounded corners. */ imageUrl: string; tondns?: string; /** Info or landing page for the wallet — shown to new users. */ aboutUrl: string; /** * Wallet capabilities advertised in the registry. */ features?: Feature[]; /** * Presentation hints from the registry, so the wallet picker can be restyled without an * SDK release. Absent for most wallets — treat every field as optional. */ ui?: WalletInfoUI; /** Operating systems / browsers the wallet supports. */ platforms: ('ios' | 'android' | 'macos' | 'windows' | 'linux' | 'chrome' | 'firefox' | 'safari')[]; } /** * {@link WalletInfoCurrentlyInjected} narrowed to the case where the dApp is * running inside the wallet's webview. Detect with {@link isWalletInfoCurrentlyEmbedded}. * * When the dApp boots inside a wallet, prefer connecting via this entry rather * than showing a QR-code modal. */ export declare interface WalletInfoCurrentlyEmbedded extends WalletInfoCurrentlyInjected { injected: true; embedded: true; } /** * {@link WalletInfoInjectable} narrowed to wallets actually injected on the * current page. Filter the wallets list with {@link isWalletInfoCurrentlyInjected}. */ export declare interface WalletInfoCurrentlyInjected extends WalletInfoInjectable { injected: true; } /** * Wallet exposed through a JS bridge — typically a browser extension, or the * dApp running inside the wallet's webview. */ export declare interface WalletInfoInjectable extends WalletInfoBase { /** * `window` property name where the wallet exposes its `TonConnectBridge` * object. `key: 'tonkeeper'` → `window.tonkeeper.tonconnect`. */ jsBridgeKey: string; /** `true` when the wallet is injected into the current page. */ injected: boolean; /** `true` when the dApp is running inside this wallet's in-app browser. */ embedded: boolean; } /** * @deprecated Use `WalletInfoInjectable` or `WalletInfoCurrentlyInjected` instead. */ export declare interface WalletInfoInjected extends WalletInfoBase { jsBridgeKey: string; injected: boolean; embedded: boolean; } /** * Wallet reached over the HTTP (SSE) bridge. */ export declare interface WalletInfoRemote extends WalletInfoBase { /** * HTTPS base of the wallet's universal link. The SDK appends the connect * parameters (`v`, `id`, `r`, optional `ret`, `trace_id`, `e`). */ universalLink: string; /** * Optional custom-scheme deep link (e.g. `tonkeeper-tc://`). Same protocol * parameters as the universal link. */ deepLink?: string; /** URL of the wallet's HTTP (SSE) bridge endpoint. */ bridgeUrl: string; } /** * Registry-driven presentation hints. These affect how a wallet is rendered, never how it is * connected to, so consumers that don't render a picker can ignore them. */ export declare interface WalletInfoUI { /** Render this wallet's promoted button without a background fill. */ isButtonTransparent?: boolean; } /** * Anything a wallet can send to a dApp over the protocol. */ export declare type WalletMessage = WalletEvent | WalletResponse; /** * Thrown when a wallet completes the connect handshake but its advertised * `DeviceInfo.features` do not satisfy the dApp's * `walletsRequiredFeatures` filter. The SDK aborts the connection and emits * this error to `onStatusChange`'s error handler. * * Use `cause.connectEvent` to inspect what the wallet returned (its * `DeviceInfo`, the `ConnectItemReply` array) when surfacing a useful * message to the user. * * @see [Filter wallets by required features (docs)](https://docs.ton.org/applications/ton-connect/how-to/filter-wallets) */ export declare class WalletMissingRequiredFeaturesError extends TonConnectError<{ connectEvent: ConnectEventSuccess['payload']; }> { static readonly errorName: string; cause: { connectEvent: ConnectEventSuccess['payload']; }; protected get info(): string; constructor(message: string, options: { cause: { connectEvent: ConnectEventSuccess['payload']; }; }); } /** * Represents the event triggered when the wallet modal is opened. */ export declare type WalletModalOpenedEvent = { /** * Event type. */ type: 'wallet-modal-opened'; /** * The unique client identifier associated with the session or user. */ client_id: string | null; /** * A list of wallet identifiers that are currently visible in the modal. */ visible_wallets: string[]; /** * Custom metadata containing versioning or contextual data for the modal. */ custom_data: Version; /** * Unique identifier used for tracking a specific user flow. */ trace_id: string | null; }; /** * Thrown when send transaction or other methods called while wallet is not connected. */ export declare class WalletNotConnectedError extends TonConnectError { static readonly errorName: string; protected get info(): string; } /** * Thrown when there is an attempt to connect to the injected wallet while it is not exists in the webpage. */ export declare class WalletNotInjectedError extends TonConnectError { static readonly errorName: string; protected get info(): string; } /** * Thrown when the dApp issues a request the connected wallet does not * advertise support for — e.g. `signMessage` on a wallet missing the * {@link SignMessageFeature}, or `signData({ type: 'cell' })` on a wallet whose * {@link SignDataFeature.types} lacks `'cell'`. * * `cause.requiredFeature` reflects what the SDK looked for, so the UI can * tell the user which capability is missing and prompt them to switch wallet. * * @see [`Feature` (Connect spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/connect.md#feature) */ export declare class WalletNotSupportFeatureError extends TonConnectError { static readonly errorName: string; cause: { requiredFeature: { featureName: FeatureName; value?: RequiredFeatures[keyof RequiredFeatures]; }; }; protected get info(): string; constructor(message: string, options: { cause: { requiredFeature: { featureName: FeatureName; value?: RequiredFeatures[keyof RequiredFeatures]; }; }; }); } /** * A wallet was picked, but nothing is committed yet. * * Desktop only in practice: picking a wallet there opens a second screen offering QR, browser * extension and desktop app, so the choice is not final. A preselection with no matching * {@link WalletSelectedEvent} on the same trace means the user scanned the default QR. */ export declare type WalletPreselectedEvent = { /** * Event type. */ type: 'wallet-preselected'; /** * Wallet the user picked: 'tonkeeper', 'tonhub', etc. */ wallet_app_name: string; /** * Where the pick happened. */ surface: WalletSelectionSurface; /** * Who made the choice. */ selection_source: WalletSelectionSource; /** * Custom data for the connection. */ custom_data: Version; /** * Unique identifier used for tracking a specific user flow. */ trace_id: string; }; /** * Wallet reply to an {@link AppRequest}. * * @see [`WalletResponse` (RPC spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/rpc.md#walletresponse) */ export declare type WalletResponse = WalletResponseSuccess | WalletResponseError; export declare type WalletResponseError = RpcResponses[T]['error']; export declare type WalletResponseSuccess = RpcResponses[T]['success']; export declare type WalletResponseTemplate = WalletResponseTemplateSuccess | WalletResponseTemplateError; export declare interface WalletResponseTemplateError { error: { code: number; message: string; data?: unknown; }; id: string; } export declare interface WalletResponseTemplateSuccess { result: string; id: string; } /** * This wallet is the one being connected with. * * On mobile the pick is the commitment — the connection modal redirects to the wallet app on * mount. On desktop it is the later click on the second screen's Mobile / Browser Extension / * Desktop buttons. * * Unlike {@link SelectedWalletEvent}, which it replaces, this is emitted directly from the click * handler with every field supplied by the call site. Nothing here is reconstructed from ambient * state, and `trace_id` is required rather than optional. */ export declare type WalletSelectedEvent = { /** * Event type. */ type: 'wallet-selected'; /** * Wallet being connected with: 'tonkeeper', 'tonhub', etc. */ wallet_app_name: string; /** * Where the selection happened. */ surface: WalletSelectionSurface; /** * Who made the choice. */ selection_source: WalletSelectionSource; /** * Which transport the user picked on the desktop connection screen. Set only when `surface` * is `connection-modal`, because the concept does not exist on the other surfaces. */ connection_mode?: 'mobile' | 'desktop' | 'extension'; /** * Custom data for the connection. */ custom_data: Version; /** * Unique identifier used for tracking a specific user flow. */ trace_id: string; }; /** * Who made the choice. The `auto-` prefix groups every non-user-initiated case, so consumers can * exclude them all with a prefix match rather than an exhaustive list. * * - `manual` — a human clicked a wallet in our UI. * - `auto-embedded` — running inside a wallet's browser, so that wallet was chosen by circumstance. * - `auto-dapp-directed` — the dApp named the wallet via `openSingleWalletModal()`; the user may * well have clicked something, but not in our UI. */ export declare type WalletSelectionSource = 'manual' | 'auto-embedded' | 'auto-dapp-directed'; /** * Where in the UI a wallet was picked. Recorded at the click, never inferred — the field this * replaces was a module-level signal's initial value, which is why 93% of rows reported a * "no list shown" default that no code path ever assigned. * * `embedded` means no modal was rendered at all: the dApp is running inside a wallet's own * browser and that wallet was connected directly. */ export declare type WalletSelectionSurface = 'universal-modal' | 'all-wallets-list' | 'connection-modal' | 'single-wallet-modal' | 'embedded'; /** * Fetches and caches the wallets-list registry (`wallets-v2.json`) and merges * it with any JS-injectable wallets the SDK detects on the page. * * @see [Wallets list (spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/wallets-list.md) */ export declare class WalletsListManager { private walletsListDTOCache; private walletsListDTOCacheCreationTimestamp; private readonly cacheTTLMs; private readonly walletsListSource; private readonly onDownloadDurationMeasured?; constructor(options?: { walletsListSource?: string; cacheTTLMs?: number; onDownloadDurationMeasured?: (duration: number | undefined) => void; }); getWallets(): Promise; getEmbeddedWallet(): Promise; private fetchWalletsListDTO; getRemoteWallet(appName: string): Promise; private fetchWalletsListFromSource; private getCurrentlyInjectedWallets; private walletConfigDTOListToWalletConfigList; private mergeWalletsLists; private isCorrectWalletConfigDTO; } /** * Thrown when a request to the wallet failed without the wallet returning a * TON Connect response: the wallet's bridge threw, rejected with something * that is not a TON Connect error, or the SDK could not prepare the request. * `cause` holds the original value. */ export declare class WalletTransportError extends TonConnectError { static readonly errorName: string; protected get info(): string; } /** * Thrown when the wallet is connected to a network that does not match the one * the dApp requested via `ITonConnect.setConnectionNetwork` or the `network` * field of `sendTransaction` / `signData` / `signMessage`. * * @see [`network` field (RPC spec)](https://github.com/ton-blockchain/ton-connect/blob/main/spec/rpc.md#sendtransaction) */ export declare class WalletWrongNetworkError extends TonConnectError<{ expectedChainId: string; actualChainId: string; }> { static readonly errorName: string; cause: { /** Chain id the dApp asked for. */ expectedChainId: string; /** Chain id the wallet returned / is connected to. */ actualChainId: string; }; constructor(message: string, options: { cause: { expectedChainId: string; actualChainId: string; }; }); } /** * Top-level wire shape of an embedded app-request. Discriminated on `m` (method). * One of: * - {@link WireSendTransaction} (`m: 'st'`) * - {@link WireSignMessage} (`m: 'sm'`) * - {@link WireSignData} (`m: 'sd'`) */ export declare type WireEmbeddedRequest = WireSendTransaction | WireSignMessage | WireSignData; /** * Wire form of a single structured item. Discriminated on `t`. * Counterpart of the user-facing `StructuredItem` (SDK). */ export declare type WireItem = WireTonItem | WireJettonItem | WireNftItem; /** Structured item: jetton (TEP-74) transfer. */ export declare interface WireJettonItem { /** item type discriminator */ t: 'jetton'; /** jetton master contract address */ ma: string; /** jetton recipient address */ d: string; /** jetton amount in elementary units */ am: string; /** TON to attach for fees (wallet estimates if omitted) */ aa?: string; /** where to send excess TON (defaults to sender) */ rd?: string; /** optional custom_payload cell BoC, base64 */ cp?: string; /** forward_ton_amount in nanocoins */ fa?: string; /** optional forward_payload cell BoC, base64 */ fp?: string; /** optional query_id */ qi?: string; } /** * Wire form of a raw transaction message (non-structured — the caller is * responsible for the BoC). Counterpart of the standard `SendTransaction` * `messages[]` element. */ export declare interface WireMessage { /** destination address */ a: string; /** amount in nanocoins (decimal string) */ am: string; /** optional one-cell BoC body, base64 */ p?: string; /** optional state init, base64 */ si?: string; /** extra currencies map */ ec?: { [k: number]: string; }; } /** Structured item: NFT (TEP-62) transfer. */ export declare interface WireNftItem { /** item type discriminator */ t: 'nft'; /** NFT item contract address */ na: string; /** new owner address */ no: string; /** TON to attach for fees */ aa?: string; /** where to send excess TON (defaults to sender) */ rd?: string; /** optional custom_payload cell BoC, base64 */ cp?: string; /** forward_ton_amount in nanocoins */ fa?: string; /** optional forward_payload cell BoC, base64 */ fp?: string; /** optional query_id */ qi?: string; } /** * Compact wire form of `AppRequest<'sendTransaction'>`. * The payload carries EITHER `ms` (raw messages) OR `i` (structured items), * never both. */ export declare interface WireSendTransaction { /** method discriminator: `sendTransaction` */ m: 'st'; /** from — sender address (optional; defaults to connected account) */ f?: string; /** network — TON chain id (e.g. `"-239"` for mainnet) */ n?: string; /** valid_until — unix epoch seconds */ vu?: number; /** raw messages (mutually exclusive with `i`) */ ms?: WireMessage[]; /** structured items (mutually exclusive with `ms`) */ i?: WireItem[]; } /** * Compact wire form of `AppRequest<'signData'>`. * Discriminated on `t` (payload type): `text` | `binary` | `cell`. */ export declare type WireSignData = { /** method discriminator: `signData` */ m: 'sd'; /** network — TON chain id */ n?: string; /** from — sender address */ f?: string; } & (WireSignDataText | WireSignDataBinary | WireSignDataCell); /** Sign-data payload: arbitrary binary blob, base64-encoded. */ export declare interface WireSignDataBinary { /** payload type discriminator */ t: 'binary'; /** base64-encoded bytes */ b: string; } /** Sign-data payload: a TVM cell with a TL-B schema. */ export declare interface WireSignDataCell { /** payload type discriminator */ t: 'cell'; /** TL-B schema describing the cell layout */ s: string; /** base64-encoded cell BoC */ c: string; } /** Sign-data payload: plain UTF-8 text. */ export declare interface WireSignDataText { /** payload type discriminator */ t: 'text'; /** text to sign */ tx: string; } /** * Compact wire form of `AppRequest<'signMessage'>`. * Same shape as {@link WireSendTransaction}; only the method discriminator differs. */ export declare interface WireSignMessage { /** method discriminator: `signMessage` */ m: 'sm'; /** from — sender address */ f?: string; /** network — TON chain id */ n?: string; /** valid_until — unix epoch seconds */ vu?: number; /** raw messages (mutually exclusive with `i`) */ ms?: WireMessage[]; /** structured items (mutually exclusive with `ms`) */ i?: WireItem[]; } /** Structured item: native TON transfer. */ export declare interface WireTonItem { /** item type discriminator */ t: 'ton'; /** destination address */ a: string; /** amount in nanocoins (decimal string) */ am: string; /** optional one-cell BoC body, base64 */ p?: string; /** optional state init, base64 */ si?: string; /** extra currencies map */ ec?: { [k: number]: string; }; } /** * Parameters without version field. */ export declare type WithoutVersion = T extends [Version, ...infer Rest] ? [...Rest] : never; /** * Thrown when passed address is in incorrect format. */ export declare class WrongAddressError extends TonConnectError { static readonly errorName: string; protected get info(): string; } export { }