Skip to content

Commit fc016b7

Browse files
committed
improve integrating wallet doc
1 parent 17c414d commit fc016b7

File tree

1 file changed

+177
-5
lines changed

1 file changed

+177
-5
lines changed

docs/develop/dapps/ton-connect/protocol/integrating-wallet.md

Lines changed: 177 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,13 @@
1111
## How to Use
1212

1313
### Step 1: Review Specifications
14-
Begin by familiarizing yourself with the core specifications and documentation:
14+
15+
:::caution **IMPORTANT**
16+
17+
The main answers to your questions are emphasized within the specification. Be sure to refer to these highlighted sections for critical information.
18+
19+
:::
20+
1521
- [TON Connect Specification](https://github.com/ton-blockchain/ton-connect)
1622
- [Protocol Workflow](https://github.com/ton-blockchain/ton-connect/blob/main/workflows.md)
1723
- [Bridge API](https://github.com/ton-blockchain/ton-connect/blob/main/bridge.md)
@@ -39,7 +45,48 @@ Use the [@tonconnect/protocol package](https://github.com/ton-connect/sdk/tree/m
3945
Also, pay close attention to the creation of encrypted communication channels between the wallet and the dApp. You can find detailed information in the [Session Protocol documentation](https://github.com/ton-blockchain/ton-connect/blob/main/session.md). For a practical implementation reference, check out the [@tonconnect/protocol package](https://github.com/ton-connect/sdk/blob/main/packages/protocol/src/crypto/session-crypto.ts).
4046

4147
### Step 4: Implement Wallet State Init
42-
Generate the StateInit for your wallet using parameters like wallet ID and public key. An example implementation can be found in the guide.
48+
49+
The wallet state init is a base64-encoded BOC containing the standard `StateInit` structure for all contracts in TON.
50+
51+
To create the `StateInit` for the wallet, you will need various parameters depending on the wallet version, but the data set always includes the wallet ID and the public key.
52+
53+
- **Wallet ID**: Set the wallet ID to `698983191`. This value is the sum of the "magic number" `698983191` (which is the first 4 bytes of the reversed hash of the zero state) and the workchain number (0 for users).
54+
- **Public Key**: Generate the public key from the seed.
55+
- **Wallet Version**: Determine which version of the wallet is being used. TON has several wallet versions, but most often `v5r1`, `v4r2` or `v3r2` is used.
56+
57+
Regardless of the version, the `StateInit` is formed in the same way:
58+
59+
```ts
60+
import { beginCell, storeStateInit } from '@ton/core';
61+
62+
const stateInitCell = beginCell().store(storeStateInit(walletContract.init)).endCell();
63+
const stateInitBocBase64 = stateInitCell.toBoc().toString('base64');
64+
```
65+
66+
Here, walletContract.init is a JS structure in the format { code: codeCell, data: dataCell }. If you are using @ton/core, you can generate such structures automatically:
67+
68+
```ts
69+
import { WalletContractV5R1, WalletContractV4, WalletContractV3R2 } from '@ton/core';
70+
71+
const walletContractV4 = WalletContractV4.create({ workchain: 0, publicKey: publicKey });
72+
const walletContractV3R2 = WalletContractV3R2.create({ workchain: 0, publicKey: publicKey });
73+
const walletContractV5R1 = WalletContractV5R1.create({ publicKey: publicKey });
74+
```
75+
#### Creating a Signature for TON Proof
76+
To create a signature for the TON proof, you need to compute the required payload according to the [TON Connect Address Proof Signature Documentation](https://github.com/ton-blockchain/ton-connect/blob/main/requests-responses.md#address-proof-signature-ton_proof), or use the [TON Proof Service Example](https://github.com/ton-connect/demo-dapp-with-react-ui/blob/master/src/server/services/ton-proof-service.ts#L29-L116), and then sign it using the secret key.
77+
78+
#### Creating a Signature for a Message
79+
For creating a signature for a message, you can either use the ready-made method of the wallet contract [v4 Wallet Contract Signature Method](https://github.com/ton-org/ton/blob/master/src/wallets/WalletContractV4.ts#L93-L112), or use it as a reference for your own implementation.
80+
81+
#### Resources
82+
83+
Here are the links to the wallet contracts implementations:
84+
85+
- [v5r1 Wallet Contract](https://github.com/ton-org/ton/blob/master/src/wallets/v5r1/WalletContractV5R1.ts)
86+
- [v4 Wallet Contract](https://github.com/ton-org/ton/blob/master/src/wallets/WalletContractV4.ts)
87+
- [v3r2 Wallet Contract](https://github.com/ton-org/ton/blob/master/src/wallets/WalletContractV3R2.ts)
88+
89+
We also have a guide on wallet smart contracts that can be useful for many other questions: [TON Wallet Smart Contracts Guide](https://docs.ton.org/develop/smart-contracts/tutorials/wallet).
4390

4491
### Step 5: Validate Parameters
4592
In addition to the guidelines, here is further information for validating request fields. Please review the [guidelines](https://github.com/ton-blockchain/ton-connect/blob/main/wallet-guidelines.md) before examining the information below.
@@ -64,14 +111,139 @@ In addition to the guidelines, here is further information for validating reques
64111
- **`ret` Contains an Unknown Value:** The wallet should follow the strategy as if `ret` was `none`.
65112

66113
### Step 6: Demo Integration
67-
To test and demonstrate the integration, use the [demo dapp with wallet](https://github.com/ton-connect/demo-dapp-with-wallet). This repository provides a starting point for setting up a demo environment. Also try some real world examples:
114+
To test and demonstrate the integration, you can use the following resources:
115+
- [Demo Dapp](https://github.com/ton-connect/demo-dapp-with-wallet) with Wallet: This repository provides a starting point for setting up a demo environment to test wallet integration.
116+
- [TON Proof Demo App](https://github.com/liketurbo/demo-dapp-with-backend/tree/js-demo): This app allows you to verify TON proof functionality in a practical setting.
117+
118+
For real-world testing and examples, try the following platforms:
68119

69120
- **[TON Stakers](https://app.tonstakers.com):** Test wallet connection, stake, and unstake TON.
70121
- **[STON.fi](https://app.ston.fi):** Test wallet connection, swap TON for USDT, and manage liquidity.
71122
- **[GetGems](https://getgems.io):** Test wallet connection, mint, list, and purchase NFTs.
72123

73124
### Emulating Transactions
74-
Use the `/v2/wallet/emulate` method from [tonapi.io](https://tonapi.io/api-v2) to emulate transaction chains. This helps in testing and verifying the transaction flow without using real assets.
125+
#### Handling Messages from TON Connect
126+
127+
When using TON Connect, you will receive multiple messages, each containing a `body` and `init`. Simply displaying these messages as they are might be acceptable for basic functionality, but it is not sufficient for ensuring security.
128+
129+
#### Initial Implementation
130+
131+
For the first version, displaying the messages as they are may be sufficient. However, in future updates, it would be beneficial to parse these messages or emulate a transaction chain to provide the user with more detailed and useful information.
132+
133+
#### Recommended Approaches
134+
135+
You can enhance your implementation by using the following methods:
136+
137+
- **TON API**: Utilize the `/v2/wallet/emulate` method from [TON API v2](https://tonapi.io/api-v2).
138+
139+
:::warning
140+
141+
When emulating transactions, it's essential to keep the following points in mind:
142+
143+
1. **Do Not Use the Real Wallet’s Secret Key**: Always avoid using the actual wallet's secret key during emulation. Instead, sign the transaction with a fake key, such as an empty buffer, to ensure security.
144+
145+
2. **Ensure the Real Wallet Balance is Used for Emulation**: For accurate emulation, the real wallet balance must be provided. If the balance is empty, the emulation process will fail and return an error. During testing, you may uncomment the line to specify a larger balance than what actually exists, but remember to revert to the real balance in production.
146+
147+
:::
148+
149+
<details>
150+
<summary>Example</summary>
151+
152+
```ts
153+
154+
import { Address, beginCell, external, internal, SendMode, storeMessage, toNano, TonClient4, WalletContractV4 } from '@ton/ton';
155+
import { mnemonicToWalletKey } from '@ton/crypto';
156+
import fetch from 'node-fetch';
157+
158+
// place your mnemonic here
159+
const mnemonic = [
160+
'hill', 'silly', 'large', 'favorite', 'bottom', 'embody',
161+
'entry', 'blame', 'timber', 'garden', 'humor', 'copper',
162+
'advance', 'cargo', 'unveil', 'clock', 'narrow', 'conduct',
163+
'begin', 'price', 'receive', 'nose', 'public', 'fury'
164+
];
165+
166+
async function main() {
167+
// get ton client
168+
const client = new TonClient4({
169+
endpoint: 'https://mainnet-v4.tonhubapi.com'
170+
});
171+
172+
// create key pair from mnemonic and open wallet
173+
const keyPair = await mnemonicToWalletKey(mnemonic);
174+
const wallet = client.open(WalletContractV4.create({
175+
workchain: 0,
176+
publicKey: keyPair.publicKey
177+
}));
178+
179+
// log wallet address
180+
const friendlyAddress = wallet.address.toString({ urlSafe: true, bounceable: false });
181+
console.log(friendlyAddress);
182+
183+
// get seqno
184+
const seqno = await wallet.getSeqno();
185+
// place recipient address here
186+
const recipient = Address.parse('EQCKWpx7cNMpvmcN5ObM5lLUZHZRFKqYA4xmw9jOry0ZsF9M');
187+
188+
/** DANGER ZONE */
189+
// ⚠️ FOR EMULATION PURPOSES USE EMPTY BUFFER
190+
// ⚠️ DON'T USE THE REAL SECRET KEY FOR EMULATION!!!!
191+
const fakeSecretKey = Buffer.alloc(64);
192+
/** DANGER ZONE */
193+
194+
// build transfer body for external message
195+
const body = wallet.createTransfer({
196+
seqno: seqno,
197+
secretKey: fakeSecretKey,
198+
sendMode: SendMode.IGNORE_ERRORS + SendMode.PAY_GAS_SEPARATELY,
199+
messages: [internal({
200+
to: recipient,
201+
value: toNano('0.01')
202+
})]
203+
});
204+
// build external message
205+
const extMsg = beginCell()
206+
.store(storeMessage(external({
207+
to: wallet.address,
208+
body: body,
209+
init: seqno === 0 ? wallet.init : null
210+
})))
211+
.endCell();
212+
// base64 encode external message
213+
const extMsgBocBase64 = extMsg.toBoc().toString('base64');
214+
215+
// get wallet balance for emulation, must be not empty
216+
let walletBalance = Number(await wallet.getBalance());
217+
// you can uncomment this line for testing purposes, BUT DON'T FORGET TO COMMENT IT BACK FOR REAL USAGE
218+
// walletBalance = 1_000_000_000;
219+
const result = await fetch(`https://tonapi.io/v2/wallet/emulate`, {
220+
method: 'POST',
221+
headers: {
222+
Accept: 'application/json',
223+
'Content-Type': 'application/json'
224+
},
225+
body: JSON.stringify({
226+
boc: extMsgBocBase64,
227+
params: [
228+
{
229+
address: wallet.address.toRawString(),
230+
balance: walletBalance
231+
}
232+
]
233+
})
234+
}).then(p => p.json());
235+
// log emulation result
236+
console.log(result);
237+
}
238+
239+
main().catch();
240+
241+
```
242+
</details>
243+
244+
- **Tongo Library**: Explore the [Tongo library on GitHub](https://github.com/tonkeeper/tongo).
245+
- **Custom Parser**: Consider implementing your own parser, similar to the one in [tlb-abi](https://github.com/TrueCarry/tlb-abi) (please note that this version is not stable).
246+
- **Transaction Emulation**: Look at the emulation example in [this GitHub repository](https://github.com/thekiba/multisig/tree/main/apps/ui) (primarily for research purposes).
75247

76248
### Step 7: Get an Audit
77249
To add your wallet to the wallets-list repository, please submit a pull request and ensure that all the necessary metadata is filled out. Additionally, applications can integrate wallets directly through the SDK.
@@ -81,6 +253,6 @@ To add your wallet to the wallets-list repository, please submit a pull request
81253
- [Protocol Package](https://github.com/ton-connect/sdk/tree/main/packages/protocol)
82254
- [Encrypted Communication Channels](https://github.com/ton-blockchain/ton-connect/blob/main/session.md)
83255
- [Bridge Specification](https://github.com/ton-blockchain/ton-connect/blob)
84-
- [Ton Proof](https://github.com/ton-blockchain/ton-connect/blob/main/requests-responses.md#address-proof-signature-ton_proof)
256+
- [Ton Proof](https://github.com/ton-blockchain/ton-connect/blob/main/requests-responses.md#address-proof-signature-ton_proof)
85257
- [Wallet Smart Contracts Tutorial](https://docs.ton.org/develop/smart-contracts/tutorials/wallet)
86258

0 commit comments

Comments
 (0)