Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions ecosystem/ton-connect/walletkit/web/connections.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,12 @@ kit.onConnectRequest(async (event) => {
await kit.rejectConnectRequest(event, 'No wallets available');
return;
}
const dappName = event.preview.manifest?.name || 'Unknown dApp';
const dappUrl = event.preview.manifest?.url || 'Unknown URL';
const dappName = event.preview.dAppInfo?.name || 'Unknown dApp';
const dappUrl = event.preview.dAppInfo?.url || event.preview.dAppInfo?.manifestUrl || 'Unknown URL';
// Show the connection confirmation UI to the user of the wallet service
if (confirm(`Connect to ${dappName} from ${dappUrl}?`)) {
// Set wallet address on the request before approving
event.walletAddress = wallets[0].getAddress();
// Set `walletId` on the request before approving
event.walletId = wallets[0].getWalletId();
await kit.approveConnectRequest(event);
console.log('Connected to:', dappName);
} else {
Expand Down Expand Up @@ -101,12 +101,12 @@ kit.onConnectRequest(async (event) => {
await kit.rejectConnectRequest(event, 'No wallet selected');
return;
}
const dappName = event.preview.manifest?.name || 'Unknown dApp';
const dappUrl = event.preview.manifest?.url || 'Unknown URL';
const dappName = event.preview.dAppInfo?.name || 'Unknown dApp';
const dappUrl = event.preview.dAppInfo?.url || event.preview.dAppInfo?.manifestUrl || 'Unknown URL';
// Show the connection confirmation UI to the user of the wallet service
if (confirm(`Connect to ${dappName} from ${dappUrl}?`)) {
// Set wallet address on the request before approving
event.walletAddress = selectedWallet.wallet.getAddress();
// Set `walletId` on the request before approving
event.walletId = selectedWallet.wallet.getWalletId();
await kit.approveConnectRequest(event);
console.log('Connected to:', dappName);
} else {
Expand Down
56 changes: 20 additions & 36 deletions ecosystem/ton-connect/walletkit/web/events.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -27,22 +27,24 @@ If a dApp is connected to the wallet service, the former can request to initiate
On TON, transactions are initiated by sending an external message to the TON wallet contract, which then processes it and sends internal messages as requested. To estimate money flows for planned transactions, WalletKit uses emulation via the configured API client, if supported.

<Aside>
The API client in use is determined by the optional [`apiClient` configuration parameter](/ecosystem/ton-connect/walletkit/web/init#param-api-client) during [WalletKit initialization](/ecosystem/ton-connect/walletkit/web/init#initialization). By default, the TON Center APIs are used, which provide rich emulation capabilities.
The API client in use is determined by the required [`networks` configuration parameter](/ecosystem/ton-connect/walletkit/web/init#param-networks) during [WalletKit initialization](/ecosystem/ton-connect/walletkit/web/init#initialization).
</Aside>

```ts title="TypeScript"
kit.onTransactionRequest(async (event) => {
try {
if (event.preview.result === 'success') {
if (!event.preview.data) {
console.log('Transaction emulation skipped');
} else if (event.preview.data.result === 'success') {
// If the emulation was successful,
// show net asset changes to the user for a confirmation.
// There, positive amounts mean incoming transfers,
// and negative mean outgoing ones.
console.log(event.preview.moneyFlow.ourTransfers);
console.log(event.preview.data.moneyFlow?.ourTransfers ?? []);
} else {
// Transaction emulation was not successful,
// but you can still allow a user to proceed — with a warning.
console.log('Transaction emulation failed');
console.warn('Transaction emulation failed');
}
if (confirm('Do you confirm this transaction?')) {
await kit.approveTransactionRequest(event);
Expand All @@ -67,34 +69,35 @@ kit.onSignDataRequest(async (event) => {
try {
// Data to be signed can be of three distinct types.
// Depending on a type, show it to the user for a confirmation.
switch (event.request.type) {
const dataToSign = event.payload.data;
switch (dataToSign.type) {
case 'text':
console.log(event.request.text);
console.log(dataToSign.value.content);
break;
case 'binary':
console.log(event.request.bytes);
console.log(dataToSign.value.content);
break;
case 'cell':
// The `request.cell` contains a hex-encoded string with a serialized cell
// and the `request.schema` describes a TL-B schema to parse the `request.cell`
console.log(event.request.cell);
console.log(event.request.schema);
console.log(dataToSign.value.content);
console.log(dataToSign.value.schema);
break;
}
if (confirm('Do you confirm this data sign request?')) {
try {
// Sign the data receiver with the user's approval
const result = await kit.signDataRequest(event);
// Sign the data with the user's approval
const result = await kit.approveSignDataRequest(event);
console.log('Signed successfully:', result);
} catch (error) {
console.error('Signing failed:', error);
}
} else {
await kit.rejectTransactionRequest(event, 'User rejected');
await kit.rejectSignDataRequest(event, 'User rejected');
}
} catch (error) {
console.error('Data sign handler error:', error);
await kit.rejectTransactionRequest(event, 'Fatal error in the data sign handler');
await kit.rejectSignDataRequest(event, 'Fatal error in the data sign handler');
}
});
```
Expand All @@ -104,29 +107,10 @@ kit.onSignDataRequest(async (event) => {
Upon any error in any of the requests, the `onRequestError()` method is invoked. Provide it with a callback function that would handle arbitrary errors and display useful information to the user.

```ts title="TypeScript"
await kit.onRequestError(async (event) => {
// To distinguish incoming events, look for their corresponding type:
console.error(event.incomingEvent.method);

// Event's .method can be one of the following:
// - connect (failure in onConnectRequest)
// - disconnect (failure in onDisconnect)
// - transaction (failure in onTransactionRequest)
// - signData (failure in onSignDataRequest)
// - restoreConnection (JS bridge failures)
// - none (generic request errors)
console.error(event.incomingEvent);

// The result is a following object:
// {
// id: string,
// error: {
// code: number,
// message: string,
// data?: unknown,
// }
// }
console.error(event.result);
kit.onRequestError(async (event) => {
console.error('Error in request ID:', event.id);
console.error('Details:', event.error);
console.error('Data:', event.data);
});
```

Expand Down
143 changes: 99 additions & 44 deletions ecosystem/ton-connect/walletkit/web/init.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -33,25 +33,44 @@ Alternatively, explore the complete demo wallet with WalletKit integration:

## Initialization

The basic kit initialization consists of creating a corresponding object by passing it a minimal set of necessary arguments. One needs to pick a TON network to operate on, provide the necessary device and wallet manifest configurations.
The basic kit initialization consists of creating a corresponding object by passing it a minimal set of necessary arguments: TON networks to operate on.

Yet, it's often useful to configure optional parameters right away — the following example also specifies core wallet information, TON Connect manifest, and bridge settings.

```ts
import {
// Main class
TonWalletKit,
// Network constants (MAINNET/TESTNET)
CHAIN,
// Network object
Network,
// Helper functions
createDeviceInfo,
createWalletManifest,
} from '@ton/walletkit';

// 0. Create a kit object
// 0. Create a kit object.
const kit = new TonWalletKit({
// 1. Pick a network — prefer CHAIN.TESTNET during development,
// and only switch to CHAIN.MAINNET and production deployments
// after rigorous testing.
network: CHAIN.TESTNET,
// 1. Configure networks.
networks: {
// Production network. All contracts and funds are real.
[Network.mainnet().chainId]: {
apiClient: {
// Most commonly used, official API provider.
url: 'https://toncenter.com',

// A key to access higher RPS limits.
// Get it from https://t.me/toncenter
key: '<MAINNET_API_KEY>',
},
},
// Testing network. For experiments, beta tests, and feature previews.
[Network.testnet().chainId]: {
apiClient: {
url: 'https://testnet.toncenter.com',
key: '<TESTNET_API_KEY>',
},
},
},

// 2. Specify core information and constraints of the given wallet.
deviceInfo: createDeviceInfo({
Expand All @@ -70,9 +89,18 @@ const kit = new TonWalletKit({
// but you may want to specify some custom values,
// such as the human-readable name of your wallet or its icon image url.
walletManifest: createWalletManifest(),

// 4. Specify the TON Connect's bridge settings
bridge: {
// The main TON Connect bridge for dApp communication.
// It is capable to withstand significant load.
//
// To self-host, see https://github.com/ton-connect/bridge
bridgeUrl: 'https://connect.ton.org/bridge',
},
});

// 4. Finally, wait for the initialization to complete
// 5. Finally, wait for the initialization to complete
await kit.waitForReady();
```

Expand Down Expand Up @@ -100,29 +128,67 @@ See also: [TON Connect's wallet manifest](/ecosystem/ton-connect/manifest#wallet
### Required

<ParamField
path="network"
type="CHAIN.TESTNET | CHAIN.MAINNET"
path="networks"
type="Record<CHAIN, NetworkConfig>"
required
>
The TON network to use.
For one or more TON networks, configure their respective API or RPC providers to interact with.

```ts
import { CHAIN } from '@ton/walletkit';
import { Network } from '@ton/walletkit';

new TonWalletKit({
networks: {
// Production network. All contracts and funds are real.
[Network.mainnet().chainId]: { // "-239"
apiClient: {
// Most commonly used, official API provider.
//
// To self-host, see:
// * Real-time API: https://github.com/toncenter/ton-http-api-cpp
// * Indexer: https://github.com/toncenter/ton-indexer
// It is important to put real-time API under `/api/v2` route and indexer API under `/api/v3` route.
url: 'https://toncenter.com',

// Optional key to access higher RPS limits.
key: '<MAINNET_API_KEY>',
},
},
// Testing network. For experiments, beta tests, and feature previews.
[Network.testnet().chainId]: { // "-3"
apiClient: {
url: 'https://testnet.toncenter.com',
key: '<TESTNET_API_KEY>',
},
},
},
// ...later fields...
});
```

// Testing network of TON Blockchain. For experiments, beta tests, and feature previews.
CHAIN.TESTNET; // "-3"
It is also possible to provide an entirely custom provider with its own `ApiClient` interface implementation.

// Production network of TON Blockchain. All contracts and funds are real.
CHAIN.MAINNET; // "-239"
```ts
import { Network } from '@ton/walletkit';

new TonWalletKit({
networks: {
[Network.testnet().chainId]: { // "-3"
apiClient: /* A complete ApiClient interface implementation */,
},
},
// ...later fields...
});
```
</ParamField>

### Optional

<ParamField
path="deviceInfo"
type="DeviceInfo"
required
>
Core information and constraints of the given wallet.
Core information and constraints of the given wallet. If not provided, defaults will be used.

```ts
interface DeviceInfo {
Expand Down Expand Up @@ -184,9 +250,8 @@ See also: [TON Connect's wallet manifest](/ecosystem/ton-connect/manifest#wallet
<ParamField
path="walletManifest"
type="WalletInfo"
required
>
How your wallet interacts with the TON Connect. This field is closely related to the [corresponding JSON manifest file](/ecosystem/ton-connect/manifest#wallet-manifest).
How your wallet interacts with the TON Connect. If not provided, defaults will be used. This field is closely related to the [corresponding JSON manifest file](/ecosystem/ton-connect/manifest#wallet-manifest).

```ts expandable
interface WalletInfo {
Expand Down Expand Up @@ -260,27 +325,6 @@ See also: [TON Connect's wallet manifest](/ecosystem/ton-connect/manifest#wallet
```
</ParamField>

### Optional

<ParamField
path="apiClient"
type="object | ApiClient"
>
Which API or RPC provider to use to interact with TON Blockchain.

```ts
// Either a small object:
const _: {
// Defaults to "https://toncenter.com".
url?: string;

// A key to access higher RPS limits.
key?: string;
}
// Or a complete ApiClient interface implementation.
```
</ParamField>

<ParamField
path="bridge"
type="BridgeConfig"
Expand Down Expand Up @@ -325,8 +369,8 @@ See also: [TON Connect's wallet manifest](/ecosystem/ton-connect/manifest#wallet
// Either a small object:
interface StorageConfig {
prefix?: string;
cacheTimeout?: number;
maxCacheSize?: number;
maxRetries?: number;
retryDelay?: number;
allowMemory?: boolean;
}

Expand All @@ -349,6 +393,10 @@ See also: [TON Connect's wallet manifest](/ecosystem/ton-connect/manifest#wallet
```ts
interface EventProcessorConfig {
disableEvents?: boolean;

// If true, transaction events will not be emulated,
// and their `preview` field will be undefined.
disableTransactionEmulation?: boolean;
}
```
</ParamField>
Expand Down Expand Up @@ -385,6 +433,13 @@ See also: [TON Connect's wallet manifest](/ecosystem/ton-connect/manifest#wallet
horizontal="true"
href="/ecosystem/ton-connect/walletkit/web/wallets"
/>

<Card
title="Handle connections"
icon="plug"
horizontal="true"
href="/ecosystem/ton-connect/walletkit/web/connections"
/>
</Columns>

## See also
Expand Down
Loading