TON DocsTON Docs
TON ConnectAPI reference

@tonconnect/protocol reference

@tonconnect/protocol is the low-level package of request, response, and event models that describe the TON Connect wire format, plus the session cryptography (SessionCrypto, Base64, hex helpers) used to encrypt bridge traffic. Wallet implementers consume this package; dApp developers normally use @tonconnect/sdk, which re-exports the relevant types.

For protocol semantics behind these models, see the TON Connect spec.

Installation

Install from npm:

npm i @tonconnect/protocol

There is no CDN bundle for this package — it is intended for wallet and SDK implementers building on top of the protocol.

Generated from @tonconnect/protocol v3.0.0-beta.2.

SessionCrypto

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 AppMessage and decrypting incoming WalletMessage; the wallet does the reverse.

Constructor

Reuse an existing KeyPair (resuming a session) or generate a fresh one (crypto_box.keyPair()) when omitted.

new SessionCrypto(keyPair?: KeyPair)
ParameterTypeDescription
keyPairKeyPairOptional.

Instance properties

PropertyTypeDescription
sessionIdstringBridge-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).

encrypt()

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;
ParameterTypeDescription
messagestring
receiverPublicKeyUint8Array

Returns Uint8Array.

decrypt()

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;
ParameterTypeDescription
messageUint8Array
senderPublicKeyUint8Array

Returns string.

stringifyKeypair()

Export the underlying keypair as a KeyPair of hex strings. Persist this in dApp / wallet storage to resume the session later.

stringifyKeypair(): KeyPair;

Returns KeyPair.

Types

KeyPair

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 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.

interface KeyPair {
    publicKey: string;
    secretKey: string;
}
FieldTypeDescription
publicKeystring32-byte public key, hex-encoded.
secretKeystring32-byte secret key, hex-encoded. Must be kept private.

TonAddressItem

interface TonAddressItem {
    name: 'ton_addr';
    network?: ChainId;
}
FieldTypeDescription
name'ton_addr'
networkChainIdOptional. 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.

TonProofItem

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.

interface TonProofItem {
    name: 'ton_proof';
    payload: string;
}
FieldTypeDescription
name'ton_proof'
payloadstringPayload to embed in the signed message.

ConnectRequest

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.

interface ConnectRequest {
    manifestUrl: string;
    items: ConnectItem[];
}
FieldTypeDescription
manifestUrlstringURL 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.
itemsConnectItem[]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.

DisconnectRpcRequest

RPC request that tells the wallet the dApp ended the session.

interface DisconnectRpcRequest {
    method: 'disconnect';
    params: [];
    id: string;
}
FieldTypeDescription
method'disconnect'
params[]Empty tuple — no parameters
idstringdApp-assigned request ID; used to match the wallet response

SendTransactionRpcRequest

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).

interface SendTransactionRpcRequest {
    method: 'sendTransaction';
    params: [string];
    id: string;
}
FieldTypeDescription
method'sendTransaction'
params[string]Single-element tuple: the JSON-stringified transaction payload
idstringdApp-assigned request ID; used to match the wallet response

SignDataRpcRequest

RPC request to sign arbitrary application data and return a wallet-provided signature.

params[0] is a JSON-stringified SignDataPayload — one of three discriminated shapes (text, binary, cell).

interface SignDataRpcRequest {
    method: 'signData';
    params: [string];
    id: string;
}
FieldTypeDescription
method'signData'
params[string]Single-element tuple: the JSON-stringified sign-data payload
idstringdApp-assigned request ID; used to match the wallet response

SignMessageRpcRequest

RPC request to sign an internal message without broadcasting it.

params[0] is a JSON-stringified payload identical in shape to SendTransactionRpcRequest.

interface SignMessageRpcRequest {
    method: 'signMessage';
    params: [string];
    id: string;
}
FieldTypeDescription
method'signMessage'
params[string]Single-element tuple: the JSON-stringified payload
idstringdApp-assigned request ID; used to match the wallet response

DeviceInfo

Wallet self-description returned inside ConnectEventSuccess's payload.device.

interface DeviceInfo {
    platform: 'iphone' | 'ipad' | 'android' | 'windows' | 'mac' | 'linux' | 'browser';
    appName: string;
    appVersion: string;
    maxProtocolVersion: number;
    features: Feature[];
}
FieldTypeDescription
platform'iphone' | 'ipad' | 'android' | 'windows' | 'mac' | 'linux' | 'browser'Operating system / runtime the wallet identifies itself with.
appNamestringWallet identifier — same value as the app_name field in the wallets list.
appVersionstringThe version of the wallet.
maxProtocolVersionnumberHighest TON Connect protocol version the wallet implements.
featuresFeature[]Capabilities the wallet advertises.

WireSendTransaction

Compact wire form of AppRequest<'sendTransaction'>. The payload carries EITHER ms (raw messages) OR i (structured items), never both.

interface WireSendTransaction {
    m: 'st';
    f?: string;
    n?: string;
    vu?: number;
    ms?: WireMessage[];
    i?: WireItem[];
}
FieldTypeDescription
m'st'Method discriminator: sendTransaction
fstringOptional. From — sender address (optional; defaults to connected account)
nstringOptional. Network — TON chain ID (e.g. "-239" for mainnet)
vunumberOptional. valid_until — unix epoch seconds
msWireMessage[]Optional. Raw messages (mutually exclusive with i)
iWireItem[]Optional. Structured items (mutually exclusive with ms)

WireSignMessage

Compact wire form of AppRequest<'signMessage'>. Same shape as WireSendTransaction; only the method discriminator differs.

interface WireSignMessage {
    m: 'sm';
    f?: string;
    n?: string;
    vu?: number;
    ms?: WireMessage[];
    i?: WireItem[];
}
FieldTypeDescription
m'sm'Method discriminator: signMessage
fstringOptional. From — sender address
nstringOptional. Network — TON chain ID
vunumberOptional. valid_until — unix epoch seconds
msWireMessage[]Optional. Raw messages (mutually exclusive with i)
iWireItem[]Optional. Structured items (mutually exclusive with ms)

WireSignDataText

Sign-data payload: plain UTF-8 text.

interface WireSignDataText {
    t: 'text';
    tx: string;
}
FieldTypeDescription
t'text'Payload type discriminator
txstringText to sign

WireSignDataBinary

Sign-data payload: arbitrary binary blob, base64-encoded.

interface WireSignDataBinary {
    t: 'binary';
    b: string;
}
FieldTypeDescription
t'binary'Payload type discriminator
bstringBase64-encoded bytes

WireSignDataCell

Sign-data payload: a TVM cell with a TL-B schema.

interface WireSignDataCell {
    t: 'cell';
    s: string;
    c: string;
}
FieldTypeDescription
t'cell'Payload type discriminator
sstringTL-B schema describing the cell layout
cstringBase64-encoded cell BoC

WireMessage

Wire form of a raw transaction message (non-structured — the caller is responsible for the BoC). Counterpart of the standard SendTransaction messages[] element.

interface WireMessage {
    a: string;
    am: string;
    p?: string;
    si?: string;
    ec?: { [k: number]: string };
}
FieldTypeDescription
astringDestination address
amstringAmount in nanograms (decimal string)
pstringOptional. Optional one-cell BoC body, base64
sistringOptional. Optional state init, base64
ec{ [k: number]: string }Optional. Extra currencies map

WireTonItem

Structured item: native GRAM transfer.

interface WireTonItem {
    t: 'gram';
    a: string;
    am: string;
    p?: string;
    si?: string;
    ec?: { [k: number]: string };
}
FieldTypeDescription
t'gram'Item type discriminator
astringDestination address
amstringAmount in nanograms (decimal string)
pstringOptional. Optional one-cell BoC body, base64
sistringOptional. Optional state init, base64
ec{ [k: number]: string }Optional. Extra currencies map

WireJettonItem

Structured item: jetton (TEP-74) transfer.

interface WireJettonItem {
    t: 'jetton';
    ma: string;
    d: string;
    am: string;
    aa?: string;
    rd?: string;
    cp?: string;
    fa?: string;
    fp?: string;
    qi?: string;
}
FieldTypeDescription
t'jetton'Item type discriminator
mastringJetton master contract address
dstringJetton recipient address
amstringJetton amount in elementary units
aastringOptional. GRAM to attach for fees (wallet estimates if omitted)
rdstringOptional. Where to send excess GRAM (defaults to sender)
cpstringOptional. Optional custom_payload cell BoC, base64
fastringOptional. forward_ton_amount in nanograms
fpstringOptional. Optional forward_payload cell BoC, base64
qistringOptional. Optional query_id

WireNftItem

Structured item: NFT (TEP-62) transfer.

interface WireNftItem {
    t: 'nft';
    na: string;
    no: string;
    aa?: string;
    rd?: string;
    cp?: string;
    fa?: string;
    fp?: string;
    qi?: string;
}
FieldTypeDescription
t'nft'Item type discriminator
nastringNFT item contract address
nostringNew owner address
aastringOptional. GRAM to attach for fees
rdstringOptional. Where to send excess GRAM (defaults to sender)
cpstringOptional. Optional custom_payload cell BoC, base64
fastringOptional. forward_ton_amount in nanograms
fpstringOptional. Optional forward_payload cell BoC, base64
qistringOptional. Optional query_id

RpcTonItem

Native GRAM transfer in RPC wire form.

interface RpcTonItem {
    type: 'gram';
    address: string;
    amount: string;
    payload?: string;
    stateInit?: string;
    extra_currency?: { [k: number]: string };
}
FieldTypeDescription
type'gram'Item discriminator.
addressstringDestination address in TEP-2 user-friendly format.
amountstringNanograms to send, as a decimal string.
payloadstringOptional. Optional one-cell BoC body, base64-encoded.
stateInitstringOptional. Optional one-cell BoC StateInit, base64-encoded.
extra_currency{ [k: number]: string }Optional. TEP-92 extra currencies: currency_id → decimal amount string.

RpcJettonItem

TEP-74 jetton transfer in RPC wire form.

interface RpcJettonItem {
    type: 'jetton';
    master: string;
    destination: string;
    amount: string;
    attachAmount?: string;
    responseDestination?: string;
    customPayload?: string;
    forwardAmount?: string;
    forwardPayload?: string;
    queryId?: string;
}
FieldTypeDescription
type'jetton'Item discriminator.
masterstringJetton master contract address.
destinationstringRecipient address.
amountstringJetton amount in elementary units (decimal string).
attachAmountstringOptional. GRAM value to attach for transfer execution; wallet picks a default when omitted.
responseDestinationstringOptional. Where to refund excess GRAM. Defaults to the sender.
customPayloadstringOptional. Raw one-cell BoC custom_payload, base64-encoded.
forwardAmountstringOptional. Nanograms forwarded to the destination wallet. Defaults to "1" nanogram.
forwardPayloadstringOptional. Raw one-cell BoC forward_payload, base64-encoded.
queryIdstringOptional. Application-defined query_id for the transfer body.

RpcNftItem

TEP-62 NFT transfer in RPC wire form.

interface RpcNftItem {
    type: 'nft';
    nftAddress: string;
    newOwner: string;
    attachAmount?: string;
    responseDestination?: string;
    customPayload?: string;
    forwardAmount?: string;
    forwardPayload?: string;
    queryId?: string;
}
FieldTypeDescription
type'nft'Item discriminator.
nftAddressstringNFT item contract address.
newOwnerstringNew owner address.
attachAmountstringOptional. GRAM value to attach for transfer execution; wallet picks a default when omitted.
responseDestinationstringOptional. Where to refund excess GRAM. Defaults to the sender.
customPayloadstringOptional. Raw one-cell BoC custom_payload, base64-encoded.
forwardAmountstringOptional. Nanograms forwarded to the new owner. Defaults to "1" nanogram.
forwardPayloadstringOptional. Raw one-cell BoC forward_payload, base64-encoded.
queryIdstringOptional. Application-defined query_id for the transfer body.

ConnectEventSuccess

Successful connect handshake.

Wallets that support the EmbeddedRequest feature MAY attach the signed result of an embedded action on ConnectEventSuccess.response.

interface ConnectEventSuccess {
    event: 'connect';
    id: number;
    payload: { items: ConnectItemReply[]; device: DeviceInfo };
    response?: WalletResponse<RpcMethod>;
}
FieldTypeDescription
event'connect'
idnumberMonotonic event ID (separate counter from RPC id).
payload{ items: ConnectItemReply[]; device: DeviceInfo }
responseWalletResponse<RpcMethod>Optional. 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.

ConnectEventError

Connect failure. The dApp should surface the matching error from CONNECT_EVENT_ERROR_CODES and unwind any pending UI.

interface ConnectEventError {
    event: 'connect_error';
    id: number;
    payload: { code: CONNECT_EVENT_ERROR_CODES; message: string };
}
FieldTypeDescription
event'connect_error'
idnumber
payload{ code: CONNECT_EVENT_ERROR_CODES; message: string }

TonAddressItemReply

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.

interface TonAddressItemReply {
    name: 'ton_addr';
    address: string;
    network: ChainId;
    walletStateInit: string;
    publicKey: string;
}
FieldTypeDescription
name'ton_addr'
addressstringRaw TON address (<workchain>:<hex>).
networkChainIdTON network the account belongs to.
walletStateInitstringBase64 BoC of the wallet contract StateInit.
publicKeystringPublic key as a hex string (without 0x). Untrusted.

TonProofItemReplySuccess

Successful ton_proof reply. proof carries the Ed25519 signature plus the bound fields needed to reconstruct the signed bytes on the verifier side.

interface TonProofItemReplySuccess {
    name: 'ton_proof';
    proof: { timestamp: number; domain: { lengthBytes: number; value: string }; payload: string; signature: string };
}
FieldTypeDescription
name'ton_proof'
proof{ timestamp: number; domain: { lengthBytes: number; value: string }; payload: string; signature: string }

DisconnectEvent

Wallet-initiated session teardown. Fires when the user removes the dApp from the wallet's connected-apps list.

interface DisconnectEvent {
    event: 'disconnect';
    id: number;
    payload: {};
}
FieldTypeDescription
event'disconnect'
idnumberMonotonic event ID (separate counter from RPC id).
payload{}Empty for disconnect.

DisconnectRpcResponseSuccess

Success envelope. result is empty — the wallet just acknowledged.

interface DisconnectRpcResponseSuccess {
    id: string;
    result: {};
}
FieldTypeDescription
idstringEcho of the request id.
result{}Empty. Reserved for future fields.

DisconnectRpcResponseError

Failure envelope. code is one of DISCONNECT_ERROR_CODES.

interface DisconnectRpcResponseError {
    error: { code: DISCONNECT_ERROR_CODES; message: string; data?: unknown };
    id: string;
}
FieldTypeDescription
error{ code: DISCONNECT_ERROR_CODES; message: string; data?: unknown }
idstring

SendTransactionRpcResponseSuccess

Success: result is the base64-encoded BoC of the external message.

interface SendTransactionRpcResponseSuccess {
    result: string;
    id: string;
}
FieldTypeDescription
resultstring
idstring

SendTransactionRpcResponseError

Failure envelope.

interface SendTransactionRpcResponseError {
    error: { code: SEND_TRANSACTION_ERROR_CODES; message: string; data?: unknown };
    id: string;
}
FieldTypeDescription
error{ code: SEND_TRANSACTION_ERROR_CODES; message: string; data?: unknown }
idstring

SignDataRpcResponseSuccess

interface SignDataRpcResponseSuccess {
    result: { signature: string; address: string; timestamp: number; domain: string; payload: SignDataPayload };
    id: string;
}
FieldTypeDescription
result{ signature: string; address: string; timestamp: number; domain: string; payload: SignDataPayload }
idstringEcho of the request id.

SignDataRpcResponseError

interface SignDataRpcResponseError {
    error: { code: SIGN_DATA_ERROR_CODES; message: string };
    id: string;
}
FieldTypeDescription
error{ code: SIGN_DATA_ERROR_CODES; message: string }
idstring

SignMessageRpcResponseSuccess

interface SignMessageRpcResponseSuccess {
    result: { internalBoc: string };
    id: string;
}
FieldTypeDescription
result{ internalBoc: string }
idstringEcho of the request id.

SignMessageRpcResponseError

interface SignMessageRpcResponseError {
    error: { code: SIGN_MESSAGE_ERROR_CODES; message: string; data?: unknown };
    id: string;
}
FieldTypeDescription
error{ code: SIGN_MESSAGE_ERROR_CODES; message: string; data?: unknown }
idstring

WalletResponseTemplateSuccess

interface WalletResponseTemplateSuccess {
    result: string;
    id: string;
}
FieldTypeDescription
resultstring
idstring

WalletResponseTemplateError

interface WalletResponseTemplateError {
    error: { code: number; message: string; data?: unknown };
    id: string;
}
FieldTypeDescription
error{ code: number; message: string; data?: unknown }
idstring

ChainId

TON network identifier. May be extended with custom global_ids.

type ChainId = CHAIN | string;

AppMessage

Anything a dApp can send to a wallet over the protocol.

type AppMessage = ConnectRequest | AppRequest<keyof RpcRequests>;

ConnectItem

Data item attached to a ConnectRequest. Wallets reply to each item inside ConnectEventSuccess.payload.items.

The protocol defines two items:

  • TonAddressItem — required for the connect to be useful.
  • TonProofItem — optional ton_proof request used for wallet authentication.
type ConnectItem = TonAddressItem | TonProofItem;

RpcRequests

Map from RPC method name to its request envelope. Used both as a type registry and to derive AppRequest via index lookup.

type RpcRequests = {
    sendTransaction: SendTransactionRpcRequest;
    signData: SignDataRpcRequest;
    signMessage: SignMessageRpcRequest;
    disconnect: DisconnectRpcRequest;
};

AppRequest

Request envelope for the given RPC method. Each envelope follows the same { method, params, id } structure;

type AppRequest<T extends RpcMethod> = RpcRequests[T];

WireEmbeddedRequest

Top-level wire shape of an embedded app-request. Discriminated on m (method). One of:

type WireEmbeddedRequest = WireSendTransaction | WireSignMessage | WireSignData;

WireSignData

Compact wire form of AppRequest<'signData'>. Discriminated on t (payload type): text | binary | cell.

type WireSignData = { m: 'sd'; n?: string; f?: string } & (WireSignDataText | WireSignDataBinary | WireSignDataCell);

WireItem

Wire form of a single structured item. Discriminated on t. Counterpart of the user-facing StructuredItem (SDK).

type WireItem = WireTonItem | WireJettonItem | WireNftItem;

DecodedEmbeddedRequest

type DecodedEmbeddedRequest = Omit<AppRequest<'sendTransaction' | 'signMessage' | 'signData'>, 'id'>;

Feature

Capability entries advertised by a wallet inside DeviceInfo.features.

type Feature =
    | SendTransactionFeatureDeprecated
    | SendTransactionFeature
    | SignDataFeature
    | SignMessageFeature
    | EmbeddedRequestFeature;

FeatureName

type FeatureName = Exclude<Feature, 'SendTransaction'>['name'];

SendTransactionFeatureDeprecated

type SendTransactionFeatureDeprecated = 'SendTransaction';

StructuredItemType

Item kinds a wallet may accept inside sendTransaction.items / signMessage.items. Maps to the structured wallet-built transfers: native GRAM, TEP-74 jetton, TEP-62 NFT.

type StructuredItemType = 'gram' | 'jetton' | 'nft';

SendTransactionFeature

type SendTransactionFeature = {
    name: 'SendTransaction';
    maxMessages: number;
    extraCurrencySupported?: boolean;
    itemTypes?: StructuredItemType[];
};

SignDataType

type SignDataType = 'text' | 'binary' | 'cell';

SignDataFeature

type SignDataFeature = { name: 'SignData'; types: SignDataType[] };

SignMessageFeature

type SignMessageFeature = {
    name: 'SignMessage';
    maxMessages: number;
    extraCurrencySupported?: boolean;
    itemTypes?: StructuredItemType[];
};

EmbeddedRequestFeature

Wallet supports the embedded-request transport (e query parameter on the connect URL).

type EmbeddedRequestFeature = { name: 'EmbeddedRequest' };

RpcMethod

The set of methods a dApp can invoke after a successful connect. Wallets accept the methods they advertise via Feature.

type RpcMethod = 'disconnect' | 'sendTransaction' | 'signData' | 'signMessage';

RpcStructuredItem

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.

type RpcStructuredItem = RpcTonItem | RpcJettonItem | RpcNftItem;

ConnectEvent

Wallet reply to a ConnectRequest. Either a success (ConnectEventSuccess) carrying the user's account and the requested data items, or ConnectEventError when the user declines or the wallet fails to fulfil the request.

type ConnectEvent = ConnectEventSuccess | ConnectEventError;

ConnectItemReply

Per-item reply inside ConnectEventSuccess.payload.items. Wallets either fulfil the item or return a ConnectItemReplyError carrying a CONNECT_ITEM_ERROR_CODES code (400 when the item is unsupported).

type ConnectItemReply = TonAddressItemReply | TonProofItemReply;

TonProofItemReply

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.

type TonProofItemReply = TonProofItemReplySuccess | TonProofItemReplyError;

TonProofItemReplyError

type TonProofItemReplyError = ConnectItemReplyError<TonProofItemReplySuccess['name']>;

ConnectItemReplyError

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 } }.

type ConnectItemReplyError<T> = { name: T; error: { code: CONNECT_ITEM_ERROR_CODES; message?: string } };

WalletEvent

Server-initiated events the wallet emits to the dApp.

type WalletEvent = ConnectEvent | DisconnectEvent;

WalletMessage

Anything a wallet can send to a dApp over the protocol.

type WalletMessage = WalletEvent | WalletResponse<RpcMethod>;

DisconnectRpcResponse

Wallet reply to a disconnect RPC. Success carries an empty result; error narrows the code enum to DISCONNECT_ERROR_CODES.

type DisconnectRpcResponse = DisconnectRpcResponseSuccess | DisconnectRpcResponseError;

SendTransactionRpcResponse

Wallet reply to a sendTransaction RPC.

type SendTransactionRpcResponse = SendTransactionRpcResponseSuccess | SendTransactionRpcResponseError;

SignDataRpcResponse

Wallet reply to a signData RPC.

type SignDataRpcResponse = SignDataRpcResponseSuccess | SignDataRpcResponseError;

SignDataPayload

Discriminated payload for signData.

type SignDataPayload =
    & { network?: ChainId; from?: string }
    & (SignDataPayloadText | SignDataPayloadBinary | SignDataPayloadCell);

SignDataPayloadText

type SignDataPayloadText = { type: 'text'; text: string };

SignDataPayloadBinary

type SignDataPayloadBinary = { type: 'binary'; bytes: string };

SignDataPayloadCell

type SignDataPayloadCell = { type: 'cell'; schema: string; cell: string };

SignMessageRpcResponse

Wallet reply to a signMessage RPC. Success carries the signed internal message BoC; error narrows the code enum to SIGN_MESSAGE_ERROR_CODES.

type SignMessageRpcResponse = SignMessageRpcResponseSuccess | SignMessageRpcResponseError;

WalletResponseTemplate

type WalletResponseTemplate = WalletResponseTemplateSuccess | WalletResponseTemplateError;

RpcResponses

Map from RPC method name to its success / error response envelope.

Used to derive WalletResponse.

type RpcResponses = {
    sendTransaction: { error: SendTransactionRpcResponseError; success: SendTransactionRpcResponseSuccess };
    signData: { error: SignDataRpcResponseError; success: SignDataRpcResponseSuccess };
    signMessage: { error: SignMessageRpcResponseError; success: SignMessageRpcResponseSuccess };
    disconnect: { error: DisconnectRpcResponseError; success: DisconnectRpcResponseSuccess };
};

WalletResponseSuccess

type WalletResponseSuccess<T extends RpcMethod> = RpcResponses[T]['success'];

WalletResponseError

type WalletResponseError<T extends RpcMethod> = RpcResponses[T]['error'];

WalletResponse

Wallet reply to an AppRequest.

type WalletResponse<T extends RpcMethod> = WalletResponseSuccess<T> | WalletResponseError<T>;

CHAIN

Two baseline TON network IDs.

enum CHAIN {
    MAINNET = '-239',
    TESTNET = '-3',
}

CONNECT_EVENT_ERROR_CODES

Error codes the wallet may return in ConnectEventError.

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,
}
MemberValueDescription
UNKNOWN_ERROR0Unexpected wallet-side failure.
BAD_REQUEST_ERROR1Request payload is malformed.
MANIFEST_NOT_FOUND_ERROR2Wallet could not fetch the tonconnect-manifest.json.
MANIFEST_CONTENT_ERROR3Manifest was fetched but fails JSON / schema validation.
UNKNOWN_APP_ERROR100Wallet does not know the app / session.
USER_REJECTS_ERROR300User explicitly declined the connect prompt.
METHOD_NOT_SUPPORTED400Wallet does not support the requested method.

CONNECT_ITEM_ERROR_CODES

Per-item error codes returned inside a ConnectItemReplyError.

enum CONNECT_ITEM_ERROR_CODES {
    UNKNOWN_ERROR = 0,
    METHOD_NOT_SUPPORTED = 400,
}
MemberValueDescription
UNKNOWN_ERROR0Unexpected wallet-side failure.
METHOD_NOT_SUPPORTED400Wallet does not support this connect item.

DISCONNECT_ERROR_CODES

Error codes the wallet may return from disconnect.

enum DISCONNECT_ERROR_CODES {
    UNKNOWN_ERROR = 0,
    BAD_REQUEST_ERROR = 1,
    UNKNOWN_APP_ERROR = 100,
    METHOD_NOT_SUPPORTED = 400,
}

SEND_TRANSACTION_ERROR_CODES

Error codes the wallet may return from sendTransaction.

enum SEND_TRANSACTION_ERROR_CODES {
    UNKNOWN_ERROR = 0,
    BAD_REQUEST_ERROR = 1,
    UNKNOWN_APP_ERROR = 100,
    USER_REJECTS_ERROR = 300,
    METHOD_NOT_SUPPORTED = 400,
}
MemberValueDescription
UNKNOWN_ERROR0Unexpected wallet-side failure.
BAD_REQUEST_ERROR1Request payload is malformed.
UNKNOWN_APP_ERROR100Wallet does not know the dApp / session.
USER_REJECTS_ERROR300User explicitly declined the transaction.
METHOD_NOT_SUPPORTED400Wallet does not support the method.

SIGN_DATA_ERROR_CODES

Error codes the wallet may return from signData.

enum SIGN_DATA_ERROR_CODES {
    UNKNOWN_ERROR = 0,
    BAD_REQUEST_ERROR = 1,
    UNKNOWN_APP_ERROR = 100,
    USER_REJECTS_ERROR = 300,
    METHOD_NOT_SUPPORTED = 400,
}
MemberValueDescription
UNKNOWN_ERROR0Unexpected wallet-side failure.
BAD_REQUEST_ERROR1Invalid request payload.
UNKNOWN_APP_ERROR100Wallet does not know the dApp / session.
USER_REJECTS_ERROR300User explicitly declined.
METHOD_NOT_SUPPORTED400Wallet does not support signData method or the requested type.

SIGN_MESSAGE_ERROR_CODES

Error codes the wallet may return from signMessage.

enum SIGN_MESSAGE_ERROR_CODES {
    UNKNOWN_ERROR = 0,
    BAD_REQUEST_ERROR = 1,
    UNKNOWN_APP_ERROR = 100,
    USER_REJECTS_ERROR = 300,
    METHOD_NOT_SUPPORTED = 400,
}
MemberValueDescription
UNKNOWN_ERROR0Unexpected wallet-side failure.
BAD_REQUEST_ERROR1Invalid request payload.
UNKNOWN_APP_ERROR100Wallet does not know the dApp / session.
USER_REJECTS_ERROR300User explicitly declined.
METHOD_NOT_SUPPORTED400Wallet does not support signMessage.

Namespaces

Base64

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.

Base64.encode()

Base64.encode(value: string | object | Uint8Array, urlSafe: boolean = false): string;

Base64.decode()

Base64.decode(
    value: string,
    urlSafe: boolean = false
): { toString(): string; toObject<T>(): T | null; toUint8Array(): Uint8Array };

Utility functions

decodeWireEmbeddedRequest()

Decode a compact WireEmbeddedRequest back to the standard JSON-RPC AppRequest-shaped { method, params: [JSON-string] }.

function decodeWireEmbeddedRequest(wire: WireEmbeddedRequest): DecodedEmbeddedRequest;
ParameterTypeDescription
wireWireEmbeddedRequest

Returns DecodedEmbeddedRequest.

decodeEmbeddedRequestParam()

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)).

function decodeEmbeddedRequestParam(reqParam: string): DecodedEmbeddedRequest;
ParameterTypeDescription
reqParamstring

Returns DecodedEmbeddedRequest.

concatUint8Arrays()

Concatenate two byte arrays into a new Uint8Array.

function concatUint8Arrays(buffer1: Uint8Array, buffer2: Uint8Array): Uint8Array;
ParameterTypeDescription
buffer1Uint8Array
buffer2Uint8Array

Returns Uint8Array.

splitToUint8Arrays()

Split array at index and return the two halves as fresh Uint8Arrays.

function splitToUint8Arrays(array: Uint8Array, index: number): [Uint8Array, Uint8Array];
ParameterTypeDescription
arrayUint8Array
indexnumber

Returns [Uint8Array, Uint8Array].

toHexString()

Hex-encode a byte array, lowercase, no 0x prefix.

function toHexString(byteArray: Uint8Array): string;
ParameterTypeDescription
byteArrayUint8Array

Returns string.

hexToByteArray()

Inverse of toHexString. Throws when hexString has an odd length.

function hexToByteArray(hexString: string): Uint8Array;
ParameterTypeDescription
hexStringstring

Returns Uint8Array.

isNode()

true when running inside Node.js (detected via process.versions.node).

function isNode(): boolean;

Returns boolean.

On this page

InstallationSessionCryptoConstructorInstance propertiesencrypt()decrypt()stringifyKeypair()TypesKeyPairTonAddressItemTonProofItemConnectRequestDisconnectRpcRequestSendTransactionRpcRequestSignDataRpcRequestSignMessageRpcRequestDeviceInfoWireSendTransactionWireSignMessageWireSignDataTextWireSignDataBinaryWireSignDataCellWireMessageWireTonItemWireJettonItemWireNftItemRpcTonItemRpcJettonItemRpcNftItemConnectEventSuccessConnectEventErrorTonAddressItemReplyTonProofItemReplySuccessDisconnectEventDisconnectRpcResponseSuccessDisconnectRpcResponseErrorSendTransactionRpcResponseSuccessSendTransactionRpcResponseErrorSignDataRpcResponseSuccessSignDataRpcResponseErrorSignMessageRpcResponseSuccessSignMessageRpcResponseErrorWalletResponseTemplateSuccessWalletResponseTemplateErrorChainIdAppMessageConnectItemRpcRequestsAppRequestWireEmbeddedRequestWireSignDataWireItemDecodedEmbeddedRequestFeatureFeatureNameSendTransactionFeatureDeprecatedStructuredItemTypeSendTransactionFeatureSignDataTypeSignDataFeatureSignMessageFeatureEmbeddedRequestFeatureRpcMethodRpcStructuredItemConnectEventConnectItemReplyTonProofItemReplyTonProofItemReplyErrorConnectItemReplyErrorWalletEventWalletMessageDisconnectRpcResponseSendTransactionRpcResponseSignDataRpcResponseSignDataPayloadSignDataPayloadTextSignDataPayloadBinarySignDataPayloadCellSignMessageRpcResponseWalletResponseTemplateRpcResponsesWalletResponseSuccessWalletResponseErrorWalletResponseCHAINCONNECT_EVENT_ERROR_CODESCONNECT_ITEM_ERROR_CODESDISCONNECT_ERROR_CODESSEND_TRANSACTION_ERROR_CODESSIGN_DATA_ERROR_CODESSIGN_MESSAGE_ERROR_CODESNamespacesBase64Base64.encode()Base64.decode()Utility functionsdecodeWireEmbeddedRequest()decodeEmbeddedRequestParam()concatUint8Arrays()splitToUint8Arrays()toHexString()hexToByteArray()isNode()Related pages