@tonconnect/sdk
Version:
Use it to connect your app to TON wallets via TonConnect protocol. You can find more details and the protocol specification in the [docs](https://docs.ton.org/develop/dapps/ton-connect/overview). See the example of sdk usage [here](https://github.com/ton
1,394 lines (1,268 loc) • 45.4 kB
TypeScript
export declare interface Account {
/**
* User's address in "hex" format: "<wc>:<hex>".
*/
address: string;
/**
* User's selected chain.
*/
chain: CHAIN;
/**
* Base64 (not url safe) encoded wallet contract stateInit.
* Can be used to get user's public key from the stateInit if the wallet contract doesn't support corresponding get method.
*/
walletStateInit: string;
/**
* Hex string without 0x prefix.
*/
publicKey?: string;
}
export declare type AddTonConnectPrefix<T extends string> = `ton-connect-${T}` | `ton-connect-ui-${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 {
protected get info(): string;
constructor(...args: ConstructorParameters<typeof TonConnectError>);
}
/**
* A concrete implementation of EventDispatcher that dispatches events to the browser window.
*/
export declare class BrowserEventDispatcher<T extends {
type: string;
}> implements EventDispatcher<T> {
/**
* 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<P extends AddTonConnectPrefix<T['type']>>(eventName: P, eventDetails: T & {
type: RemoveTonConnectPrefix<P>;
}): Promise<void>;
/**
* 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<P extends AddTonConnectPrefix<T['type']>>(eventName: P, listener: (event: CustomEvent<T & {
type: RemoveTonConnectPrefix<P>;
}>) => void, options?: AddEventListenerOptions): Promise<() => void>;
}
export declare enum CHAIN {
MAINNET = "-239",
TESTNET = "-3"
}
export declare function checkRequiredWalletFeatures(features: Feature[], walletsRequiredFeatures?: RequiredFeatures): boolean;
export declare enum CONNECT_EVENT_ERROR_CODES {
UNKNOWN_ERROR = 0,
BAD_REQUEST_ERROR = 1,
MANIFEST_NOT_FOUND_ERROR = 2,
MANIFEST_CONTENT_ERROR = 3,
UNKNOWN_APP_ERROR = 100,
USER_REJECTS_ERROR = 300,
METHOD_NOT_SUPPORTED = 400
}
export declare enum CONNECT_ITEM_ERROR_CODES {
UNKNOWN_ERROR = 0,
METHOD_NOT_SUPPORTED = 400
}
export declare interface ConnectAdditionalRequest {
/**
* Payload for ton_proof
*/
tonProof?: string;
}
export declare interface ConnectEventSuccess {
event: 'connect';
id: number;
payload: {
items: ConnectItemReply[];
device: DeviceInfo;
};
}
/**
* 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;
} & 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: Version;
};
/**
* Connection events.
*/
export declare type ConnectionEvent = ConnectionStartedEvent | ConnectionCompletedEvent | ConnectionErrorEvent;
/**
* Information about a connected wallet.
*/
export declare type ConnectionInfo = {
/**
* Connected wallet address.
*/
wallet_address: 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;
} & Version;
};
/**
* 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;
} & 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;
};
/**
* 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;
};
/**
* 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;
};
export declare type ConnectItem = TonAddressItem | TonProofItem;
export declare type ConnectItemReply = TonAddressItemReply | TonProofItemReply;
export declare type ConnectItemReplyError<T> = {
name: T;
error: {
code: CONNECT_ITEM_ERROR_CODES;
message?: string;
};
};
/**
* Create a connection completed event.
* @param version
* @param wallet
*/
export declare function createConnectionCompletedEvent(version: Version, wallet: Wallet | null): ConnectionCompletedEvent;
/**
* Create a connection error event.
* @param version
* @param error_message
* @param errorCode
*/
export declare function createConnectionErrorEvent(version: Version, error_message: string, errorCode: CONNECT_EVENT_ERROR_CODES | void): ConnectionErrorEvent;
/**
* Create a connection restoring completed event.
* @param version
* @param wallet
*/
export declare function createConnectionRestoringCompletedEvent(version: Version, wallet: Wallet | null): ConnectionRestoringCompletedEvent;
/**
* Create a connection restoring error event.
* @param version
* @param errorMessage
*/
export declare function createConnectionRestoringErrorEvent(version: Version, errorMessage: string): ConnectionRestoringErrorEvent;
/**
* Create a connection restoring started event.
*/
export declare function createConnectionRestoringStartedEvent(version: Version): ConnectionRestoringStartedEvent;
/**
* Create a connection init event.
*/
export declare function createConnectionStartedEvent(version: Version): ConnectionStartedEvent;
export declare function createDataSentForSignatureEvent(version: Version, wallet: Wallet | null, data: SignDataPayload): DataSentForSignatureEvent;
export declare function createDataSignedEvent(version: Version, wallet: Wallet | null, data: SignDataPayload, signedData: SignDataResponse): DataSignedEvent;
export declare function createDataSigningFailedEvent(version: Version, wallet: Wallet | null, data: SignDataPayload, errorMessage: string, errorCode: SIGN_DATA_ERROR_CODES | void): DataSigningFailedEvent;
/**
* Create a disconnect event.
* @param version
* @param wallet
* @param scope
* @returns
*/
export declare function createDisconnectionEvent(version: Version, wallet: Wallet | null, scope: 'dapp' | 'wallet'): 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;
/**
* Create a transaction init event.
* @param version
* @param wallet
* @param transaction
*/
export declare function createTransactionSentForSignatureEvent(version: Version, wallet: Wallet | null, transaction: SendTransactionRequest): TransactionSentForSignatureEvent;
/**
* Create a transaction signed event.
* @param version
* @param wallet
* @param transaction
* @param signedTransaction
*/
export declare function createTransactionSignedEvent(version: Version, wallet: Wallet | null, transaction: SendTransactionRequest, signedTransaction: SendTransactionResponse): TransactionSignedEvent;
/**
* Create a transaction error event.
* @param version
* @param wallet
* @param transaction
* @param errorMessage
* @param errorCode
*/
export declare function createTransactionSigningFailedEvent(version: Version, wallet: Wallet | null, transaction: SendTransactionRequest, errorMessage: string, errorCode: SEND_TRANSACTION_ERROR_CODES | void): TransactionSigningFailedEvent;
/**
* Create a version info.
* @param version
*/
export declare function createVersionInfo(version: Version): Version;
export declare interface DappMetadata {
/**
* Dapp name. Might be simple, will not be used as identifier.
* @default `document.title` if exists, 'Unknown dapp' overwise
*/
name: string;
/**
* URL to the dapp icon. Must be PNG, ICO, ... . SVG icons are not supported.
* @default best quality favicon declared via <link> 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;
} & ConnectionInfo;
export declare type DataSignedEvent = {
type: 'sign-data-request-completed';
is_success: true;
data: SignDataPayload;
signed_data: SignDataResponse;
} & 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;
} & ConnectionInfo;
export declare interface DeviceInfo {
platform: 'iphone' | 'ipad' | 'android' | 'windows' | 'mac' | 'linux' | 'browser';
appName: string;
appVersion: string;
maxProtocolVersion: number;
features: Feature[];
}
/**
* Disconnect event when a user initiates a disconnection.
*/
export declare type DisconnectionEvent = {
/**
* Event type.
*/
type: 'disconnection';
/**
* Disconnect scope: 'dapp' or 'wallet'.
*/
scope: 'dapp' | 'wallet';
} & ConnectionInfo;
export declare function enableQaMode(): void;
export declare function encodeTelegramUrlParameters(parameters: string): string;
/**
* Interface for an event dispatcher that sends events.
*/
export declare interface EventDispatcher<T extends {
type: string;
}> {
/**
* 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<P extends AddTonConnectPrefix<T['type']>>(eventName: P, eventDetails: T & {
type: RemoveTonConnectPrefix<P>;
}): Promise<void>;
/**
* 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<P extends AddTonConnectPrefix<T['type']>>(eventName: P, listener: (event: CustomEvent<T & {
type: RemoveTonConnectPrefix<P>;
}>) => void, options?: AddEventListenerOptions): Promise<() => void>;
}
export declare type Feature = SendTransactionFeatureDeprecated | SendTransactionFeature | SignDataFeature;
export declare type FeatureName = Exclude<Feature, 'SendTransaction'>['name'];
/**
* Thrown when an error occurred while fetching the wallets list.
*/
export declare class FetchWalletsError extends TonConnectError {
protected get info(): string;
constructor(...args: ConstructorParameters<typeof TonConnectError>);
}
export declare function isQaModeEnabled(): boolean;
export declare function isTelegramUrl(link: string | undefined): link is string;
/**
* Imitation of the localStorage.
*/
export declare interface IStorage {
/**
* Saves the `value` to the storage. Value can be accessed later by the `key`. Implementation may use backend as a storage due to the fact that the function returns a promise.
* @param key key to access to the value later.
* @param value value to save.
*/
setItem(key: string, value: string): Promise<void>;
/**
* Reads the `value` from the storage. Implementation may use backend as a storage due to the fact that the function returns a promise.
* @param key key to access the value.
*/
getItem(key: string): Promise<string | null>;
/**
* Removes the `value` from the storage. Implementation may use backend as a storage due to the fact that the function returns a promise.
* @param key key to access the value.
*/
removeItem(key: string): Promise<void>;
}
/**
* 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 `WalletInfoInjected`, 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;
export declare interface ITonConnect {
/**
* Shows if the wallet is connected right now.
*/
connected: boolean;
/**
* Current connected account or null if no account is connected.
*/
account: Account | null;
/**
* Current connected wallet or null if no account is connected.
*/
wallet: Wallet | null;
/**
* Returns available wallets list.
*/
getWallets(): Promise<WalletInfo[]>;
/**
* 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: (walletInfo: 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, or list of bridges urls for creating an universal connection request for the corresponding wallets.
* @param request (optional) additional request to pass to the wallet while connect (currently only ton_proof is available).
* @returns universal link if external wallet was passed or void for the injected wallet.
*/
connect<T extends WalletConnectionSource | Pick<WalletConnectionSourceHTTP, 'bridgeUrl'>[]>(wallet: T, request?: ConnectAdditionalRequest): T extends WalletConnectionSourceJS ? void : string;
/**
* Try to restore existing session and reconnect to the corresponding wallet. Call it immediately when your app is loaded.
*/
restoreConnection(options?: {
openingDeadlineMS?: number;
signal?: AbortSignal;
}): Promise<void>;
/**
* 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<void>;
/**
* Disconnect form thw connected wallet and drop current session.
*/
disconnect(options?: {
signal?: AbortSignal;
}): Promise<void>;
/**
* Asks connected wallet to sign and send the transaction.
* @param transaction transaction to send.
* @param options (optional) onRequestSent callback will be called after the transaction is sent and signal to abort the request.
* @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?: {
onRequestSent?: () => void;
signal?: AbortSignal;
}): Promise<SendTransactionResponse>;
/** @deprecated use sendTransaction(transaction, options) instead */
sendTransaction(transaction: SendTransactionRequest, onRequestSent?: () => void): Promise<SendTransactionResponse>;
signData(data: SignDataPayload, options?: {
onRequestSent?: () => void;
signal?: AbortSignal;
}): Promise<SignDataResponse>;
/**
* Gets the current session ID if available.
* @returns session ID string or null if not available.
*/
getSessionId(): Promise<string | null>;
}
export declare interface KeyPair {
publicKey: string;
secretKey: string;
}
/**
* Thrown when `Storage` was not specified in the `DappMetadata` and default `localStorage` was not detected in the Node.js environment.
*/
export declare class LocalstorageNotFoundError extends TonConnectError {
protected get info(): string;
constructor(...args: ConstructorParameters<typeof TonConnectError>);
}
/**
* Thrown when passed hex is in incorrect format.
*/
export declare class ParseHexError extends TonConnectError {
protected get info(): string;
constructor(...args: ConstructorParameters<typeof TonConnectError>);
}
/**
* Removes the `ton-connect-` and `ton-connect-ui-` prefixes from the given string.
*/
export declare type RemoveTonConnectPrefix<T> = 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';
};
/**
* Required features for wallets.
*/
export declare type RequiredFeatures = {
/**
* Required features for the send transaction feature.
*/
sendTransaction?: RequiredSendTransactionFeature;
signData?: RequiredSignDataFeature;
};
/**
* Required features for the send transaction feature.
*/
export declare type RequiredSendTransactionFeature = {
/**
* Minimum number of messages to send.
*/
minMessages?: number;
/**
* Whether extra currency is required.
*/
extraCurrencyRequired?: boolean;
};
/**
* Required features for the sign data feature.
*/
export declare type RequiredSignDataFeature = {
/**
* Supported sign data types.
*/
types: SignDataType[];
};
/**
* Response TON Connect UI version.
*/
export declare type ResponseVersionEvent = {
/**
* Event type.
*/
type: 'response-version';
/**
* TON Connect UI version.
*/
version: string;
};
/**
* User action events.
*/
export declare type SdkActionEvent = VersionEvent | ConnectionEvent | ConnectionRestoringEvent | DisconnectionEvent | TransactionSigningEvent | DataSigningEvent;
export declare enum SEND_TRANSACTION_ERROR_CODES {
UNKNOWN_ERROR = 0,
BAD_REQUEST_ERROR = 1,
UNKNOWN_APP_ERROR = 100,
USER_REJECTS_ERROR = 300,
METHOD_NOT_SUPPORTED = 400
}
export declare type SendTransactionFeature = {
name: 'SendTransaction';
maxMessages: number;
extraCurrencySupported?: boolean;
};
export declare type SendTransactionFeatureDeprecated = 'SendTransaction';
export declare interface SendTransactionRequest {
/**
* Sending transaction deadline in unix epoch seconds.
*/
validUntil: number;
/**
* The network (mainnet or testnet) where DApp intends to send the transaction. If not set, the transaction is sent to the network currently set in the wallet, but this is not safe and DApp should always strive to set the network. If the network parameter is set, but the wallet has a different network set, the wallet should show an alert and DO NOT ALLOW TO SEND this transaction.
*/
network?: CHAIN;
/**
* The sender address in '<wc>:<hex>' format from which DApp intends to send the transaction. Current account.address by default.
*/
from?: string;
/**
* Messages to send: min is 1, max is 4.
*/
messages: {
/**
* Receiver's address.
*/
address: string;
/**
* Amount to send in nanoTon.
*/
amount: string;
/**
* Contract specific data to add to the transaction.
*/
stateInit?: string;
/**
* Contract specific data to add to the transaction.
*/
payload?: string;
/**
* Extra currencies to send.
*/
extraCurrency?: {
[k: number]: string;
};
}[];
}
export declare interface SendTransactionResponse {
/**
* Signed boc
*/
boc: string;
}
export declare class SessionCrypto {
private readonly nonceLength;
private readonly keyPair;
readonly sessionId: string;
constructor(keyPair?: KeyPair);
private createKeypair;
private createKeypairFromString;
private createNonce;
encrypt(message: string, receiverPublicKey: Uint8Array): Uint8Array;
decrypt(message: Uint8Array, senderPublicKey: Uint8Array): string;
stringifyKeypair(): KeyPair;
}
export declare enum SIGN_DATA_ERROR_CODES {
UNKNOWN_ERROR = 0,
BAD_REQUEST_ERROR = 1,
UNKNOWN_APP_ERROR = 100,
USER_REJECTS_ERROR = 300,
METHOD_NOT_SUPPORTED = 400
}
export declare type SignDataFeature = {
name: 'SignData';
types: SignDataType[];
};
export declare type SignDataPayload = {
network?: CHAIN;
from?: string;
} & (SignDataPayloadText | SignDataPayloadBinary | SignDataPayloadCell);
export declare type SignDataPayloadBinary = {
type: 'binary';
bytes: string;
};
export declare type SignDataPayloadCell = {
type: 'cell';
schema: string;
cell: string;
};
export declare type SignDataPayloadText = {
type: 'text';
text: string;
};
export declare type SignDataResponse = {
signature: string;
address: string;
timestamp: number;
domain: string;
payload: SignDataPayload;
};
export declare type SignDataType = 'text' | 'binary' | 'cell';
export declare interface TonAddressItem {
name: 'ton_addr';
}
export declare interface TonAddressItemReply {
name: 'ton_addr';
address: string;
network: CHAIN;
walletStateInit: string;
publicKey: string;
}
declare class TonConnect implements ITonConnect {
private static readonly walletsList;
/**
* Check if specified wallet is injected and available to use with the app.
* @param walletJSKey target wallet's js bridge key.
*/
static isWalletInjected: (walletJSKey: string) => boolean;
/**
* Check if the app is opened inside specified wallet's browser.
* @param walletJSKey target wallet's js bridge key.
*/
static isInsideWalletBrowser: (walletJSKey: string) => boolean;
/**
* Returns available wallets list.
*/
static getWallets(): Promise<WalletInfo[]>;
/**
* Emits user action event to the EventDispatcher. By default, it uses `window.dispatchEvent` for browser environment.
* @private
*/
private readonly tracker;
private readonly walletsList;
private readonly dappSettings;
private readonly bridgeConnectionStorage;
private _wallet;
private provider;
private statusChangeSubscriptions;
private statusChangeErrorSubscriptions;
private readonly walletsRequiredFeatures;
private abortController?;
/**
* 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);
constructor(options?: TonConnectOptions);
/**
* Returns available wallets list.
*/
getWallets(): Promise<WalletInfo[]>;
/**
* 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<T extends WalletConnectionSource | Pick<WalletConnectionSourceHTTP, 'bridgeUrl'>[]>(wallet: T, options?: {
request?: ConnectAdditionalRequest;
openingDeadlineMS?: number;
signal?: AbortSignal;
}): T extends WalletConnectionSourceJS ? void : string;
/** @deprecated use connect(wallet, options) instead */
connect<T extends WalletConnectionSource | Pick<WalletConnectionSourceHTTP, 'bridgeUrl'>[]>(wallet: T, request?: ConnectAdditionalRequest, options?: {
openingDeadlineMS?: number;
signal?: AbortSignal;
}): T extends WalletConnectionSourceJS ? void : string;
/**
* Try to restore existing session and reconnect to the corresponding wallet. Call it immediately when your app is loaded.
*/
restoreConnection(options?: {
openingDeadlineMS?: number;
signal?: AbortSignal;
}): Promise<void>;
/**
* 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?: {
onRequestSent?: () => void;
signal?: AbortSignal;
}): Promise<SendTransactionResponse>;
/** @deprecated use sendTransaction(transaction, options) instead */
sendTransaction(transaction: SendTransactionRequest, onRequestSent?: () => void): Promise<SendTransactionResponse>;
signData(data: SignDataPayload, options?: {
onRequestSent?: () => void;
signal?: AbortSignal;
}): Promise<SignDataResponse>;
/**
* Disconnect form thw connected wallet and drop current session.
*/
disconnect(options?: {
signal?: AbortSignal;
}): Promise<void>;
/**
* Gets the current session ID if available.
* @returns session ID string or null if not available.
*/
getSessionId(): Promise<string | null>;
/**
* 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<void>;
private addWindowFocusAndBlurSubscriptions;
private createProvider;
private walletEventsListener;
private onWalletConnected;
private onWalletConnectError;
private onWalletDisconnected;
private checkConnection;
private createConnectRequest;
}
export { TonConnect }
export default TonConnect;
/**
* Base class for TonConnect errors. You can check if the error was triggered by the @tonconnect/sdk using `err instanceof TonConnectError`.
*/
export declare class TonConnectError<T = unknown> extends Error {
private static prefix;
protected get info(): string;
constructor(message?: string, options?: {
cause?: T;
});
}
/**
* TonConnect constructor options
*/
export declare interface TonConnectOptions {
/**
* Url to the [manifest]{@link https://github.com/ton-connect/docs/blob/main/requests-responses.md#app-manifest} with the Dapp metadata that will be displayed in the user's wallet.
* If not passed, manifest from `${window.location.origin}/tonconnect-manifest.json` will be taken.
*/
manifestUrl?: string;
/**
* Storage to save protocol data. For browser default is `localStorage`. If you use SDK with nodeJS, you have to specify this field.
*/
storage?: IStorage;
/**
* Event dispatcher to track user actions. By default, it uses `window.dispatchEvent` for browser environment.
*/
eventDispatcher?: EventDispatcher<SdkActionEvent>;
/**
* Redefine wallets list source URL. Must be a link to a json file with [following structure]{@link https://github.com/ton-connect/wallets-list}
* @default https://config.ton.org/wallets-v2.json
* @
*/
walletsListSource?: string;
/**
* Wallets list cache time to live
* @default Infinity
*/
walletsListCacheTTLMs?: number;
/**
* Required features for wallets. If wallet doesn't support required features, it will be disabled.
*/
walletsRequiredFeatures?: RequiredFeatures;
/**
* Allows to disable auto pause/unpause SSE connection on 'document.visibilitychange' event. It is not recommended to change default behaviour.
*/
disableAutoPauseConnection?: boolean;
}
export declare interface TonProofItem {
name: 'ton_proof';
payload: string;
}
export declare type TonProofItemReply = TonProofItemReplySuccess | TonProofItemReplyError;
export declare type TonProofItemReplyError = ConnectItemReplyError<TonProofItemReplySuccess['name']>;
export declare interface TonProofItemReplySuccess {
name: 'ton_proof';
proof: {
timestamp: number;
domain: {
lengthBytes: number;
value: string;
};
payload: string;
signature: string;
};
}
/**
* Converts raw TON address to no-bounceable user-friendly format. [See details]{@link https://ton.org/docs/learn/overviews/addresses#user-friendly-address}
* @param hexAddress raw TON address formatted as "0:<hex string without 0x>".
* @param [testOnly=false] convert address to test-only form. [See details]{@link https://ton.org/docs/learn/overviews/addresses#user-friendly-address}
*/
export declare function toUserFriendlyAddress(hexAddress: string, testOnly?: boolean): string;
/**
* 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';
} & 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;
} & 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;
} & ConnectionInfo & TransactionInfo;
/**
* Thrown when app tries to send rpc request to the injected wallet while not connected.
*/
export declare class UnknownAppError extends TonConnectError {
protected get info(): string;
constructor(...args: ConstructorParameters<typeof TonConnectError>);
}
/**
* Unhanded unknown error.
*/
export declare class UnknownError extends TonConnectError {
constructor(...args: ConstructorParameters<typeof TonConnectError>);
}
/**
* Thrown when user rejects the action in the wallet.
*/
export declare class UserRejectsError extends TonConnectError {
protected get info(): string;
constructor(...args: ConstructorParameters<typeof TonConnectError>);
}
/**
* 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;
};
/**
* Version events.
*/
export declare type VersionEvent = RequestVersionEvent | ResponseVersionEvent;
export declare interface Wallet {
/**
* Information about user's wallet's device.
*/
device: DeviceInfo;
/**
* Provider type: http bridge or injected js.
*/
provider: 'http' | 'injected';
/**
* Selected account.
*/
account: Account;
/**
* Response for connect items request.
*/
connectItems?: {
tonProof?: TonProofItemReply;
};
}
/**
* Thrown when wallet connection called but wallet already connected. To avoid the error, disconnect the wallet before doing a new connection.
*/
export declare class WalletAlreadyConnectedError extends TonConnectError {
protected get info(): string;
constructor(...args: ConstructorParameters<typeof TonConnectError>);
}
export declare type WalletConnectionSource = WalletConnectionSourceHTTP | WalletConnectionSourceJS;
export declare interface WalletConnectionSourceHTTP {
/**
* Base part of the wallet universal url. The link should support [Ton Connect parameters]{@link https://github.com/ton-connect/docs/blob/main/bridge.md#universal-link}.
*/
universalLink: string;
/**
* Url of the wallet's implementation of the [HTTP bridge]{@link https://github.com/ton-connect/docs/blob/main/bridge.md#http-bridge}.
*/
bridgeUrl: string;
}
export declare interface WalletConnectionSourceJS {
/**
* If the wallet handles JS Bridge connection, specifies the binding for the bridge object accessible through window. Example: the key "tonkeeper" means the bridge can be accessed as window.tonkeeper.
*/
jsBridgeKey: string;
}
export declare type WalletInfo = WalletInfoRemote | WalletInfoInjectable | (WalletInfoRemote & WalletInfoInjectable);
/**
* Common information for injectable and http-compatible wallets.
*/
export declare interface WalletInfoBase {
/**
* Human-readable name of the wallet.
*/
name: string;
/**
* ID of the wallet, equals to the `appName` property into {@link Wallet.device}.
*/
appName: string;
/**
* Url to the icon of the wallet. Resolution 288×288px. On non-transparent background, without rounded corners. PNG format.
*/
imageUrl: string;
/**
* Will be used in the protocol later.
*/
tondns?: string;
/**
* Info or landing page of your wallet. May be useful for TON newcomers.
*/
aboutUrl: string;
/**
* List of features supported by the wallet.
*/
features?: Feature[];
/**
* OS and browsers where the wallet could be installed
*/
platforms: ('ios' | 'android' | 'macos' | 'windows' | 'linux' | 'chrome' | 'firefox' | 'safari')[];
}
/**
* Information about the JS-injectable wallet in the browser of which the dApp is opened.
*/
export declare interface WalletInfoCurrentlyEmbedded extends WalletInfoCurrentlyInjected {
injected: true;
embedded: true;
}
/**
* Information about the JS-injectable wallet that is injected to the current webpage.
*/
export declare interface WalletInfoCurrentlyInjected extends WalletInfoInjectable {
injected: true;
}
/**
* JS-injectable wallet information.
*/
export declare interface WalletInfoInjectable extends WalletInfoBase {
/**
* If the wallet handles JS Bridge connection, specifies the binding for the bridge object accessible through window. Example: the key "tonkeeper" means the bridge can be accessed as window.tonkeeper.
*/
jsBridgeKey: string;
/**
* Indicates if the wallet currently is injected to the webpage.
*/
injected: boolean;
/**
* Indicates if the dapp is opened inside this wallet's browser.
*/
embedded: boolean;
}
/**
* @deprecated Use `WalletInfoInjectable` or `WalletInfoCurrentlyInjected` instead.
*/
export declare interface WalletInfoInjected extends WalletInfoBase {
jsBridgeKey: string;
injected: boolean;
embedded: boolean;
}
/**
* Http-compatible wallet information.
*/
export declare interface WalletInfoRemote extends WalletInfoBase {
/**
* Base part of the wallet universal url. The link should support [Ton Connect parameters]{@link https://github.com/ton-connect/docs/blob/main/bridge.md#universal-link}.
*/
universalLink: string;
/**
* Native wallet app deepLink. The link should support [Ton Connect parameters]{@link https://github.com/ton-connect/docs/blob/main/bridge.md#universal-link}.
*/
deepLink?: string;
/**
* Url of the wallet's implementation of the [HTTP bridge]{@link https://github.com/ton-connect/docs/blob/main/bridge.md#http-bridge}.
*/
bridgeUrl: string;
}
/**
* Thrown when wallet can't get manifest by passed manifestUrl.
*/
export declare class WalletMissingRequiredFeaturesError extends TonConnectError<{
connectEvent: ConnectEventSuccess['payload'];
}> {
cause: {
connectEvent: ConnectEventSuccess['payload'];
};
protected get info(): string;
constructor(message: string, options: {
cause: {
connectEvent: ConnectEventSuccess['payload'];
};
});
}
/**
* Thrown when send transaction or other protocol methods called while wallet is not connected.
*/
export declare class WalletNotConnectedError extends TonConnectError {
protected get info(): string;
constructor(...args: ConstructorParameters<typeof TonConnectError>);
}
/**
* 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 {
protected get info(): string;
constructor(...args: ConstructorParameters<typeof TonConnectError>);
}
/**
* Thrown when wallet doesn't support requested feature method.
*/
export declare class WalletNotSupportFeatureError extends TonConnectError {
cause: {
requiredFeature: {
featureName: FeatureName;
value?: RequiredFeatures['sendTransaction'] | RequiredFeatures['signData'];
};
};
protected get info(): string;
constructor(message: string, options: {
cause: {
requiredFeature: {
featureName: FeatureName;
value?: RequiredFeatures['sendTransaction'] | RequiredFeatures['signData'];
};
};
});
}
export declare class WalletsListManager {
private walletsListDTOCache;
private walletsListDTOCacheCreationTimestamp;
private readonly cacheTTLMs;
private readonly walletsListSource;
constructor(options?: {
walletsListSource?: string;
cacheTTLMs?: number;
});
getWallets(): Promise<WalletInfo[]>;
getEmbeddedWallet(): Promise<WalletInfoCurrentlyEmbedded | null>;
private fetchWalletsListDTO;
private fetchWalletsListFromSource;
private getCurrentlyInjectedWallets;
private walletConfigDTOListToWalletConfigList;
private mergeWalletsLists;
private isCorrectWalletConfigDTO;
}
/**
* Parameters without version field.
*/
export declare type WithoutVersion<T> = T extends [Version, ...infer Rest] ? [...Rest] : never;
/**
* Thrown when passed address is in incorrect format.
*/
export declare class WrongAddressError extends TonConnectError {
protected get info(): string;
constructor(...args: ConstructorParameters<typeof TonConnectError>);
}
export { }