@tonappchain/sdk 0.5.7 → 0.6.1-v3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,1276 +1,189 @@
1
- # TAC SDK
2
-
3
- [![Version npm](https://img.shields.io/npm/v/@tonappchain/sdk.svg?logo=npm)](https://www.npmjs.com/package/@tonappchain/sdk)
4
-
5
- **TAC-SDK** is an SDK for facilitating crosschain operations from TVM (TON Virtual Machine) to EVM-compatible blockchains. It is designed to simplify crosschain interactions for EVM developers by enabling transactions from TVM to EVM with minimal configuration.
6
-
7
- ## Overview
8
-
9
- This SDK allows EVM developers to perform crosschain operations without needing an in-depth understanding of TON. By specifying the following details, the SDK will generate the necessary transactions:
10
-
11
- **For EVM:**
12
- 1. The ProxyDapp address to interact with.
13
- 2. The method to call on the contract.
14
- 3. Any encoded parameters required for the contract method.
15
-
16
- **For TVM:**
17
- 1. Addresses of TVM Jettons corresponding to EVM tokens.
18
-
19
- Using these inputs, the SDK builds a TON transaction payload and enables further signature processing through TON-Connect or directly via mnemonic.
20
-
21
- ---
22
-
23
- ## Features
24
-
25
- **TON:**
26
- - Get user jetton balance
27
- - Generate TON transaction payloads for crosschain operations and transfer jettons
28
- - Get `operationId` with `transactionLinker` struct
29
- - Track operation status using `operationId`
30
-
31
- ---
32
-
33
- ## Sharded Messages
34
-
35
- Due to the specific architecture of TVM, it’s not possible to send multiple tokens in a single transaction. Therefore, transactions are handled using a sharded messaging system, where each message is linked on the validator side using a unique triplet: `(caller, ShardsKey, ShardCount)`. This system is particularly useful for complex operations like liquidity providing, where multiple tokens need to be transferred on the TON side.
36
-
37
- **Example:**
38
- - **Liquidity Providing:** To add liquidity, two tokens need to be transferred on the TON side. Each token transfer is sent as an individual sharded message, which validators process and link together.
39
-
40
- ---
41
-
42
- ## How to Track the Status of an Operation
43
-
44
- To track an operation, you first need to obtain its `operationId`. The `operationId` can be retrieved using the `transactionLinker` structure, which is generated within the SDK and returned by the `sendCrossChainTransaction` function. Once you have the `transactionLinker`, call `OperationTracker.getOperationId(transactionLinker: TransactionLinker)`.
45
-
46
- > **Note:** An empty response string indicates that validators have not yet received your messages. Continue making requests until you receive a non-empty `operationId`.
47
-
48
- After obtaining the `operationId`, you can check the operation’s status by using `OperationTracker.getOperationStatus(operationId: string)`. The following statuses may be returned:
49
-
50
- 1. **COLLECTED_IN_TAC:** The sequencer has collected all events for a single sharded message. For simple transfers (e.g., a token swap), this status indicates that the message is fully gathered.
51
- 2. **INCLUDED_IN_TAC_CONSENSUS:** The EVM message has been added to the Merkle tree, and subsequent roots will reflect this addition.
52
- 3. **EXECUTED_IN_TAC:** The collected message has been executed on the EVM side.
53
- 4. **COLLECTED_IN_TON:** After execution on EVM, a return message event is generated, which will then be executed on the TVM side.
54
- 5. **INCLUDED_IN_TON_CONSENSUS:** The TVM message has been added to the Merkle tree, updating future roots accordingly.
55
- 6. **EXECUTED_IN_TON:** The TVM Merkle message has been successfully executed on the TVM CrossChainLayer.
56
-
57
- If an issue occurs, the error message will also be included in response.
58
-
59
- ### Terminal State
60
- - **EXECUTED_IN_TON**: Indicates that the operation has completed its full cycle from TVM to EVM and back.
61
-
62
- ---
63
-
64
- ## Install
65
-
66
- ```bash
67
- npm install @tonappchain/sdk
68
- ```
69
-
70
- ---
71
-
72
- ## Functionality description
73
- The `TacSdk` class is designed for performing crosschain operations, particularly bridging Jetton tokens for interaction with the TAC.
74
-
75
- ### Creating an Instance of `TacSdk`
76
-
77
- To use the `TacSdk` class, create it with the required parameters encapsulated in the `SDKParams` object (you can also specify custom params for TAC and TON by `TACParams` and `TONParams`):
78
-
79
- ```typescript
80
- import { TacSdk } from '@tonappchain/sdk';
81
- import { Network } from '@tonappchain/sdk';
82
-
83
- const sdkParams: SDKParams = {
84
- network: Network.TESTNET
85
- // you can also customize TAC and TON params here
86
- };
87
- const tacSdk = await TacSdk.create(sdkParams);
88
- ```
89
- > **Note:** By default Orbs Network is used as TON provider
90
-
91
- Optionally, only in NodeJS you can provide custom liteservers client for TON blockchain in `contractOpener` argument:
92
-
93
- ```typescript
94
- import { TacSdk, Network, liteClientOpener } from '@tonappchain/sdk';
95
-
96
- // Ex.: your own lite clients for TON
97
- const liteClientServers = [<liteClientServer1>, <liteClientServer1>, ...];
98
-
99
- const sdkParams: SDKParams = {
100
- network: Network.TESTNET,
101
- TONParams: {
102
- contractOpener: await liteClientOpener({ liteservers : liteClientServers }),
103
- },
104
- };
105
-
106
- const tacSdk = await TacSdk.create(sdkParams);
107
- ```
108
-
109
- *ATTENTION:* don't forget to close the connections after all the work is done, otherwise the script will hang:
110
-
111
- ```typescript
112
- tacSdk.closeConnections();
113
- ```
114
-
115
- Optionally, you can provide @ton/ton TonClient (public endpoints will be used by default):
116
-
117
- - **MAINNET**: https://toncenter.com/api/v2/jsonRPC
118
- - **TESTNET**: https://testnet.toncenter.com/api/v2/jsonRPC
119
-
120
- ```typescript
121
- import { TacSdk, Network } from '@tonappchain/sdk';
122
- import { TonClient } from '@ton/ton';
123
-
124
- const sdk = await TacSdk.create({
125
- network: Network.TESTNET,
126
- delay: 1,
127
- TONParams: {
128
- contractOpener: new TonClient({
129
- endpoint: "https://testnet.toncenter.com/api/v2/jsonRPC",
130
- // apiKey: "your_api_key"
131
- })
132
- }
133
- });
134
-
135
- const tacSdk = await TacSdk.create(sdkParams);
136
- ```
137
-
138
- #### Possible exceptions
139
-
140
- - **`SettingError`**: settings contract at provided address does not contain required setting key.
141
-
142
- ---
143
-
144
- ### Function: `closeConnections`
145
-
146
- This function stops all connections to the network, such as Ton Liteservers, and should be called after all operations are completed. Can be used if you use custom contract opener and need to close connections manually.
147
-
148
- ### Function: `sendCrossChainTransaction`
149
-
150
- This function facilitates crosschain operations by bridging data and assets from TON for interaction with TAC. Creates a transaction on the TON side that is sent to the TAC protocol address. This starts the crosschain operation. Works with TON native coin transfer and/or it handles the required logic for burning or transferring jettons based on the Jetton type(wrapped by our s-c CrossChainLayer or not).
151
-
152
- #### **Purpose**
153
-
154
- The `sendCrossChainTransaction` method is the core functionality of the `TacSdk` class, enabling the bridging of assets (or just data) to execute crosschain operations seamlessly.
155
-
156
- #### **Parameters**
157
-
158
- - **`evmProxyMsg`**: An `EvmProxyMsg` object defining the EVM-specific logic:
159
- - **`evmTargetAddress`**: Target address on the EVM network.
160
- - **`methodName`** *(optional)*: Method name to execute on the target contract. Either method name `MethodName` or signature `MethodName(bytes,bytes)` must be specified (strictly (bytes,bytes)).
161
- - **`encodedParameters`** *(optional)*: Encoded parameters for the EVM method. You need to specify all arguments except the first one (TACHeader bytes). The TACHeader logic will be specified below
162
- - **`forceSend`** *(optional)*: Parameter indicates that the transaction should be sent even if simulation returned an error. Default `false`
163
-
164
- - **`sender`**: A `SenderAbstraction` object, such as:
165
- - **`TonConnectSender`**: For TonConnect integration.
166
- - **`RawSender`**: For raw wallet transactions using a mnemonic.
167
-
168
- - **`assets`** *(optional)*: An array of `AssetBridgingData` objects, each specifying the Assets details:
169
- - **`address`** *(optional)*: Address of the Asset.
170
- - **`rawAmount`** *(required if `amount` is not specified): Amount of Assets to be transferred taking into account the number of decimals.
171
- - **`amount`** *(required if `rawAmount` is not specified): Amount of Assets to be transferred.
172
- - **`decimals`** *(optional)*: Number of decimals for the asset. If not specified, the SDK will attempt to extract the decimals from the chain.
173
-
174
- > **Note:** If you specify methodName and encodedParameters and don't specify assets this will mean sending any data (contract call) to evmTargetAddress.
175
-
176
- > **Note:** If you don't specify methodName and encodedParameters and specify assets this will mean bridge any assets to evmTargetAddress (be sure to specify assets when doing this).
177
-
178
- #### **Returns**
179
-
180
- - **`Promise<TransactionLinker>`**:
181
- - A `TransactionLinker` object for linking TON transaction and crosschain operation as well as for tracking crosschain operation status
182
-
183
- #### **Possible exceptions**
184
-
185
- - **`ContractError`**: contract for given jetton is not deployed on TVM side.
186
- - **`AddressError`**: invalid token address provided.
187
-
188
- #### **Functionality**
189
-
190
- 1. Determines whether each Jetton requires a **burn** or **transfer** operation based on its type.
191
- 2. Prepares shard messages and encodes the necessary payloads.
192
- 3. Bridges Jettons by sending shard transactions to the appropriate smart contracts.
193
- 4. Incorporates EVM logic into the payload for interaction with the TAC.
194
-
195
- ---
196
- ### TACHeader
197
- > **Note:** The TAC protocol only knows how to send data to contracts that inherit from a TacProxy (TacProxyV1) contract. Such a contract must have a strictly defined signature of its methods. It is specified below:
198
-
199
- ```
200
- function myProxyFunction(bytes calldata tacHeader, bytes calldata arguments) external onlyTacCCL {
201
- // Function implementation
202
- }
203
- ```
204
-
205
- > **Note:** methodName in `evmProxyMsg` must be either a simple method name or a signature of the form MethodName(bytes,bytes)
206
-
207
- The first argument of methods must always be TACHeader. It is sent by protocol, augmented with data from executor.
208
- - **`bytes tacHeader`**: Encoded structure TacHeaderV1, containing:
209
- - **`uint64 shardsKey`**: ID you can specify for yourself an inside message to the TVM contract on the TON network.
210
- - **`uint256 timestamp`**: The block timestamp on TON where the user's message was created.
211
- - **`bytes32 operationId`**: Unique identifier for the message created by the TAC infrastructure.
212
- - **`string tvmCaller`**: The TON user's wallet address that sent the message.
213
- - **`bytes extraData`**: Untrusted extra data, provided by executor with the current message if needed. Otherwise, it's an empty bytes array.
214
-
215
- You need to specify all the remaining data you need in tuple (bytes) in arguments. For example this is how arguments for addLiquidity method in UniswapV2 (a special proxy contract for it) will look like:
216
-
217
- ```
218
- const abi = new ethers.AbiCoder();
219
- const encodedParameters = abi.encode(
220
- ['tuple(address,address,uint256,uint256,uint256,uint256,address,uint256)'],
221
- [
222
- [
223
- EVM_TOKEN_A_ADDRESS,
224
- EVM_TOKEN_B_ADDRESS,
225
- amountA,
226
- amountB,
227
- amountAMin,
228
- amountBMin,
229
- UNISWAPV2_PROXY_ADDRESS,
230
- deadline
231
- ]
232
- ]
233
- );
234
- ```
235
- More details in [sendAddLiquidity.ts](tests/uniswap_v2/sendAddLiquidity.ts) and in other tests.
236
-
237
- ---
238
-
239
- ### Getter: `nativeTONAddress`
240
-
241
- This getter returns address(better to say "indicator") of native TON Coin.
242
-
243
- #### **Purpose**
244
-
245
- The indicator should only be used in *getEVMTokenAddress* to calculate address of TON wrapper on TAC Chain.
246
-
247
- #### **Returns**
248
-
249
- - **`string`**:
250
- - A string that indicates the native TON Coin.
251
-
252
-
253
- ### Getter: `nativeTACAddress`
254
-
255
- This getter returns address of TAC Coin on TAC Chain.
256
-
257
- #### **Purpose**
258
-
259
- The address could be used in *getTVMTokenAddress* to calculate address of TAC wrapper on TON Chain.
260
-
261
- #### **Returns**
262
-
263
- - **`Promise<string>`**:
264
- - A promise that resolves to the computed EVM token address as a string.
265
-
266
-
267
- ### Function: `getEVMTokenAddress`
268
-
269
- This function will get the EVM paired address for a TVM token.
270
-
271
- #### **Purpose**
272
-
273
- The ability to compute the EVM address is crucial, in evmProxyMsg you almost always requires the token addresses on the EVM network as parameters. By precomputing the corresponding EVM addresses for TVM tokens, users can ensure that the transaction parameters are correctly configured before executing crosschain operations.
274
-
275
- For example, when adding liquidity, you need to specify the addresses of the tokens on the EVM network that you intend to add. Without the ability to compute these addresses in advance, configuring the transaction would be error-prone and could lead to failures. This function will bridge this gap, making the process seamless and reliable.
276
-
277
- #### **Parameters**
278
-
279
- - **`tvmTokenAddress(string)`**: The address of the token on the TON blockchain (TVM format), including support for native TON. Address of native TON can be retreieved using *nativeTONAddress* getter in TacSDK.
280
-
281
- #### **Returns**
282
-
283
- - **`Promise<string>`**:
284
- - A promise that resolves to the computed EVM token address as a string.
285
-
286
- #### **Possible exceptions**
287
-
288
- - **`AddressError`**: invalid token address provided.
289
-
290
-
291
- ### Function: `getTVMTokenAddress`
292
-
293
- This function gets the TVM paired address for a EVM token.
294
-
295
- #### **Purpose**
296
-
297
- This function provides the address of the wrapper for any EVM token at a specific address.
298
-
299
- #### **Parameters**
300
-
301
- - **`evmTokenAddress(string)`**: The address of the token on the TAC blockchain (EVM format), including support for native TAC. Address of native TAC can be retreieved using *nativeTACAddress* getter in TacSDK.
302
-
303
- #### **Returns**
304
-
305
- - **`Promise<string>`**:
306
- - A promise that resolves to the computed TVM token address as a string.
307
-
308
- #### **Possible exceptions**
309
-
310
- - **`AddressError`**: invalid token address provided.
311
-
312
-
313
- ### Function: `getUserJettonWalletAddress`
314
-
315
- This function retrieves the address of a user's Jetton wallet for a specific token.
316
-
317
- #### **Purpose**
318
-
319
- This function is useful for obtaining the address of a user's Jetton wallet, which is necessary for interacting with Jetton tokens on the TON blockchain.
320
-
321
- #### **Parameters**
322
-
323
- - **`userAddress(string)`**: The address of the user's wallet on the TON blockchain.
324
- - **`tokenAddress(string)`**: The address of the Jetton token.
325
-
326
- #### **Returns**
327
-
328
- - **`Promise<string>`**:
329
- - A promise that resolves to the address of the user's Jetton wallet as a string.
330
-
331
- #### **Possible exceptions**
332
-
333
- - **`AddressError`**: invalid token address provided.
334
-
335
-
336
- ### Function: `getUserJettonBalance`
337
-
338
- This function retrieves the balance of a specific Jetton token in a user's wallet.
339
-
340
- #### **Purpose**
341
-
342
- This function allows users to check their balance of a specific Jetton token, which is essential for managing assets on the TON blockchain.
343
-
344
- #### **Parameters**
345
-
346
- - **`userAddress(string)`**: The address of the user's wallet on the TON blockchain.
347
- - **`tokenAddress(string)`**: The address of the Jetton token.
348
-
349
- #### **Returns**
350
-
351
- - **`Promise<bigint>`**:
352
- - A promise that resolves to the balance of the Jetton token in the user's wallet as a `bigint`.
353
-
354
- #### **Possible exceptions**
355
-
356
- - **`AddressError`**: invalid token address provided.
357
-
358
-
359
- ### Function: `getUserJettonBalanceExtended`
360
-
361
- This function retrieves detailed information about a user's Jetton balance, including the raw amount, decimals, and formatted amount.
362
-
363
- #### **Purpose**
364
-
365
- This function provides a more detailed view of a user's Jetton balance, including the raw amount, the number of decimals, and the formatted amount, which is useful for displaying balances in a user-friendly format.
366
-
367
- #### **Parameters**
368
-
369
- - **`userAddress(string)`**: The address of the user's wallet on the TON blockchain.
370
- - **`tokenAddress(string)`**: The address of the Jetton token.
371
-
372
- #### **Returns**
373
-
374
- - **`Promise<UserWalletBalanceExtended>`**:
375
- - A promise that resolves to an object with one of the following structures:
376
- - If the Jetton wallet exists:
377
- - **`exists`**: A boolean indicating whether the Jetton wallet exists (`true`).
378
- - **`rawAmount`**: The raw balance of the Jetton token as a `bigint`.
379
- - **`decimals`**: The number of decimals for the Jetton token.
380
- - **`amount`**: The formatted balance of the Jetton token as a number.
381
- - If the Jetton wallet does not exist:
382
- - **`exists`**: A boolean indicating whether the Jetton wallet exists (`false`).
383
- #### **Possible exceptions**
384
-
385
- - **`AddressError`**: invalid token address provided.
386
-
387
-
388
- ### Function: `simulateTACMessage`
389
-
390
- This function will simulate the EVM message on the TAC side.
391
-
392
- #### **Purpose**
393
-
394
- The ability to simulate the EVM message is crucial for testing and debugging crosschain operations. By simulating the message, developers can verify that the transaction parameters are correctly configured and that the operation will execute.
395
-
396
- #### **Parameters**
397
-
398
- - **`tacCallParams`**: An object defining the EVM-specific logic:
399
- - **`target`**: Target address on the EVM network.
400
- - **`methodName`**: Method name to execute on the target contract. Either method name `MethodName` or signature `MethodName(bytes,bytes)` must be specified (strictly (bytes,bytes)).
401
- - **`arguments`**: Encoded parameters for the EVM method.
402
- - **`extraData`**: Unstrusted Extra Data provided by executor.
403
- - **`feeAssetAddress`**: TVM Fee Asset Address, empty string for native TON.
404
- - **`shardedId`**: Sharded ID.
405
- - **`tonAssets`**: An array of objects, each specifying the Assets details:
406
- - **`tokenAddress`**: Address of the Asset.
407
- - **`amount`**: Amount of Assets to be transferred.
408
- - **`tonCaller`**: TVM Caller wallet address.
409
-
410
- #### **Returns**
411
-
412
- - **`Promise<TACSimulationResults>`**:
413
- - A promise that resolves to detailed information about the execution of the given message, including:
414
- - **`estimatedGas`**: The estimated gas required for the message.
415
- - **`estimatedJettonFeeAmount`**: The estimated fee amount in Jettons.
416
- - **`feeParams`**: The parameters related to the fee.
417
- - **`currentBaseFee`**: The current base fee.
418
- - **`isEip1559`**: Indicates if EIP-1559 is applied.
419
- - **`suggestedGasPrice`**: The suggested gas price.
420
- - **`suggestedGasTip`**: The suggested gas tip.
421
- - **`message`**: The message details.
422
- - **`outMessages`**: The outgoing messages.
423
- - **`callerAddress`**: The address of the caller.
424
- - **`operationId`**: The operation ID.
425
- - **`payload`**: The payload.
426
- - **`queryId`**: The query ID.
427
- - **`targetAddress`**: The target address.
428
- - **`tokensBurned`**: The tokens burned.
429
- - **`amount`**: The amount of tokens burned.
430
- - **`tokenAddress`**: The address of the token.
431
- - **`tokensLocked`**: The tokens locked.
432
- - **`simulationError`**: Any error encountered during the simulation.
433
- - **`simulationStatus`**: The status of the simulation.
434
- - **`debugInfo`**: Debugging information.
435
- - **`from`**: The sender address.
436
- - **`to`**: The recipient address.
437
- - **`callData`**: The call data.
438
- - **`blockNumber`**: The block number.
439
-
440
- ---
441
-
442
- ## Sending TON Transactions: Two Approaches
443
-
444
- The SDK provides two approaches for sending TON transactions: using **TonConnect** or a **raw wallet via mnemonic**. Below is an explanation of both options.
445
-
446
- Look at example below or in tests folder(better in tests folder)
447
-
448
-
449
- ### 1. Using TonConnect
450
-
451
- The `TonConnectSender` class enables sending transactions via the TonConnect.
452
- - **Example dirty, better look at uniswap example**:
453
- ```typescript
454
- tonConnect: TonConnectUI
455
- const sender = await SenderFactory.getSender({
456
- tonConnect,
457
- });
458
- ```
459
-
460
- ### 2. Using a Raw Wallet via Mnemonic
461
-
462
- The `RawSender` class allows direct interaction with the blockchain using a raw wallet created from a mnemonic phrase.
463
-
464
- - **Example**:
465
- ```typescript
466
- const walletVersion = 'v4';
467
- const mnemonic = process.env.TVM_MNEMONICS || ''; // 24 words mnemonic
468
- const network = Network.TESTNET; // or Network.MAINNET
469
- const sender = await SenderFactory.getSender({
470
- version: walletVersion,
471
- mnemonic,
472
- network,
473
- });
474
- ```
475
-
476
- - **Supported wallet versions**:
477
- ```
478
- export type WalletVersion =
479
- | "V2R1"
480
- | "V2R2"
481
- | "V3R1"
482
- | "V3R2"
483
- | "V4"
484
- | "V5R1"
485
- | "HIGHLOAD_V3";
486
- ```
487
-
488
- - **Possible exceptions**:
489
- - **`WalletError`**: invalid wallet version provided.
490
-
491
- ---
492
-
493
- ## Tracking operation
494
- The `OperationTracker` class is designed to track the status of crosschain operations by interacting with public or custom Lite Sequencer endpoints. It provides methods to fetch and interpret transaction statuses, enabling smooth monitoring of transaction lifecycles.
495
-
496
- ### Purpose
497
-
498
- This class facilitates tracking crosschain operation statuses by:
499
- 1. Fetching the `operationId` for a TON transaction using the `transactionLinker` returned from `sendCrossChainTransaction` function in `TacSDK`.
500
- 2. Retrieving the current status of an operation using the `operationId`.
501
- 3. Returning a simplified status for easier operation monitoring.
502
-
503
- To track an operation, follow these steps:
504
-
505
- ### 0. Create an Instance of OperationTracker
506
-
507
- To use the `OperationTracker` class, initialize it with the required parameters (you can specify `customLiteSequencerEndpoints` for sending requests there):
508
-
509
- ```typescript
510
- import { OperationTracker, Network } from '@tonappchain/sdk';
511
-
512
- const tracker = new OperationTracker(
513
- network: Network.TESTNET,
514
- // customLiteSequencerEndpoints: ["custom.com"]
515
- );
516
- ```
517
-
518
- ### 1. Get the `operationId`
519
-
520
- Use the `getOperationId(transactionLinker)` method with the `transactionLinker` structure returned from `sendCrossChainTransaction` after sending TON transaction.
521
-
522
- > **Note:** An empty response string indicates that validators have not yet received your messages. Continue retrying until you receive a non-empty `operationId`.
523
-
524
-
525
- #### **Method: `getOperationId(transactionLinker: TransactionLinker): Promise<string>`**
526
-
527
- #### **Parameters**:
528
- - `transactionLinker`: A `TransactionLinker` object containing TON transaction linkers.
529
-
530
- #### **Returns**:
531
- - **`Promise<string>`**:
532
- - A string representing the `operationId`.
533
-
534
- #### **Usage**:
535
- ```typescript
536
- const tracker = new OperationTracker(
537
- network: Network.TESTNET
538
- );
539
- const operationId = await tracker.getOperationId(transactionLinker);
540
- console.log('Operation ID:', operationId);
541
- ```
542
-
543
- ### 2. Check the Operation Status
544
-
545
- Use the `getOperationStatus(operationId)` method to fetch the operation status.
546
-
547
- #### **Method: `getOperationStatus(operationId: string): Promise<StatusInfo>`**
548
-
549
- Retrieves the current status of an operation using its `operationId`.
550
-
551
- #### **Parameters**:
552
- - `operationId`: The identifier obtained from `getOperationId`.
553
-
554
- #### **Returns**:
555
- - **`Promise<StatusInfo>`**:
556
- A structure representing the operation's status, including:
557
- - **`stage`** A value of type `StageName` (enum) which can be one of:
558
- - `StageName.COLLECTED_IN_TAC` ('COLLECTED_IN_TAC')
559
- - `StageName.INCLUDED_IN_TAC_CONSENSUS` ('INCLUDED_IN_TAC_CONSENSUS')
560
- - `StageName.EXECUTED_IN_TAC` ('EXECUTED_IN_TAC')
561
- - `StageName.COLLECTED_IN_TON` ('COLLECTED_IN_TON')
562
- - `StageName.INCLUDED_IN_TON_CONSENSUS` ('INCLUDED_IN_TON_CONSENSUS')
563
- - `StageName.EXECUTED_IN_TON` ('EXECUTED_IN_TON')
564
- - **`success`** (`boolean`): Indicates if the stage completed successfully.
565
- - **`timestamp`** (`number`): UNIX timestamp of the stage’s completion.
566
- - **`transactions`**: An array of `TransactionData` objects or null. Each transaction contains:
567
- - **`hash`**: A string with the transaction hash.
568
- - **`blockchainType`**: A `BlockchainType` indicating the blockchain (`TAC`, `TON`).
569
- - **`note`**: An object of type `NoteInfo` or null containing error/debug information:
570
- - **`content`**: A string with additional details.
571
- - **`errorName`**: A string representing the error name.
572
- - **`internalMsg`**: A string with an internal message.
573
- - **`internalBytesError`**: A string with internal error details in bytes.
574
-
575
-
576
- #### **Usage**:
577
- ```typescript
578
- const tracker = new OperationTracker(
579
- network: Network.TESTNET
580
- );
581
- const status = await tracker.getOperationStatus(operationId);
582
- console.log('Stage:', status.stage)
583
- ```
584
-
585
- ---
586
-
587
- ### * Use Simplified Status (instead of 1 and 2 steps)
588
-
589
- Use the `getSimplifiedOperationStatus(transactionLinker)` method for an easy-to-interpret status.
590
-
591
- #### Method: `getSimplifiedOperationStatus(transactionLinker: TransactionLinker): Promise<SimplifiedStatuses>`
592
-
593
- Fetches a simplified operation status using the `transactionLinker`.
594
-
595
- #### **Parameters**:
596
- - `transactionLinker`: A `TransactionLinker` object returned from `sendCrossChainTransaction` function.
597
-
598
- #### **Returns**:
599
- - **`Promise<SimplifiedStatuses>`**:
600
- - A simplified status from the `SimplifiedStatuses` enum:
601
- - **`PENDING`**: The operation is still in progress.
602
- - **`SUCCESSFUL`**: The operation has successfully completed.
603
- - **`OPERATION_ID_NOT_FOUND`**: The operation ID could not be found.
604
- - **`FAILED`**: The operation failed.
605
-
606
- #### **Usage**
607
- Here operationId will be always requested(not optimal).
608
- ```typescript
609
- const tracker = new OperationTracker();
610
- const simplifiedStatus = await tracker.getSimpifiedOperationStatus(transactionLinker);
611
- console.log('Simplified Status:', simplifiedStatus);
612
- ```
613
-
614
- ### Other functions
615
- #### **Method: `getOperationType(operationId: string): Promise<OperationType>`**
616
-
617
- Retrieves the current type of operation using its `operationId`.
618
-
619
- #### **Parameters**:
620
- - `operationId`: The identifier obtained from `getOperationType`.
621
-
622
- #### **Returns**:
623
- - **`Promise<OperationType>`**:
624
- - A type from the `operationType` enum:
625
- - **`PENDING`**: The operation is still in progress.
626
- - **`TON_TAC_TON`**: The operation has successfully completed in TON-TAC-TON.
627
- - **`ROLLBACK`**: The operation failed and there was an asset rollback.
628
- - **`TON_TAC`**: The operation has successfully completed in TON-TAC.
629
- - **`TAC_TON`**: The operation has successfully completed in TAC-TON.
630
- - **`UNKNOWN`**: unknown operation type.
631
-
632
-
633
- #### Method: `getOperationIdsByShardsKeys(shardsKeys: string[], caller: string): Promise<OperationIdsByShardsKey>`
634
-
635
- Retrieves operation IDs associated with specific shard keys for a given caller. Shard keys uniquely identify shards within the TON network, and this method maps them to their corresponding operation IDs.
636
-
637
- ##### **Parameters**
638
-
639
- - **`shardsKeys`**: An array of shard keys for which operation IDs are to be fetched.
640
- - **`caller`**: The address of the caller initiating the request.
641
-
642
- ##### **Returns**
643
-
644
- - **`Promise<OperationIdsByShardsKey>`**: A promise that resolves to a mapping of shard keys to their corresponding operation IDs.
645
-
646
-
647
- #### Method: `getStageProfiling(operationId: string): Promise<ExecutionStages>`
648
-
649
- Fetches profiling information for all execution stages of operation identified by its operation ID.
650
-
651
- ##### **Parameters**
652
-
653
- - **`operationId`**: The unique identifier of the operation whose profiling data is to be retrieved.
654
-
655
- ##### **Returns**
656
-
657
- - **`Promise<ExecutionStages>`**: A promise that resolves to the profiling data of the operation's execution stages.
658
-
659
-
660
- #### Method: `getStageProfilings(operationIds: string[]): Promise<ExecutionStagesByOperationId>`
661
-
662
- Retrieves profiling information for multiple operations at once.
663
-
664
- ##### **Parameters**
665
-
666
- - **`operationIds`**: An array of operation IDs for which profiling data is to be fetched.
667
-
668
- ##### **Returns**
669
-
670
- - **`Promise<ExecutionStagesByOperationId>`**: A promise that resolves to a mapping of operation IDs to their corresponding execution stages profiling data.
671
-
672
-
673
- #### Method: `getOperationStatuses(operationIds: string[]): Promise<StatusInfosByOperationId>`
674
-
675
- Fetches the current status information for multiple operations based on their operation IDs.
676
-
677
- ##### **Parameters**
678
-
679
- - **`operationIds: string[]`**: An array of operation IDs whose statuses need to be retrieved.
680
-
681
- ##### **Returns**
682
-
683
- - **`Promise<StatusInfosByOperationId>`**: A promise that resolves to a mapping of operation IDs to their respective status information.
684
-
685
-
686
- ---
687
- ### startTracking
688
-
689
- Track the execution of crosschain operation with `startTracking` method
690
-
691
- #### Method: `async function startTracking(transactionLinker: TransactionLinker, network: Network, options?: { customLiteSequencerEndpoints?: string[]; delay?: number; maxIterationCount?: number; returnValue?: boolean; tableView?: boolean; }): Promise<void | ExecutionStages>`
692
-
693
- #### **Parameters**:
694
- - `transactionLinker`: A `TransactionLinker` object returned from `sendCrossChainTransaction` function.
695
- - `network`: TON network (`Network` type).
696
- - `options` *(optional)*:
697
- - `customLiteSequencerEndpoints` *(optional)*: specify custom lite sequencer API URL for sending requests there. Default is `undefined`
698
- - `delay` *(optional)*: specify custom delay after requests there. Default is `10`
699
- - `maxIterationCount` *(optional)*: specify custom max iteration count there. Default is `120`
700
- - `returnValue` *(optional)*: specify whether to return the data to you after tracking. When `false` will write to the console. Default is `false`
701
- - `tableView` *(optional)*: specify data display in the table. Default is `true`
702
-
703
- #### **Returns**:
704
- - Will stop requesting status once the final status of crosschain operation has been reached.
705
- - if returnValue is `false` return `Promise<void>`
706
- - if `true` return `Promise<ExecutionStages>` - execution stages profiling data.
707
-
708
- #### **Possible exceptions**
709
-
710
- - **`FetchError`**: failed to fetch operation id or status of operation from lite sequencer.
711
-
712
- #### **Usage**
713
- Here operationId will be always requested(not optimal).
714
- ```typescript
715
- await startTracking(transactionLinker, network.TESTNET);
716
- ```
717
-
718
- ---
719
-
720
- ## Structures Description
721
-
722
- ### `Network (Enum)`
723
- Represents TON network type you want to use.
724
- ```typescript
725
- export enum Network {
726
- TESTNET = 'TESTNET',
727
- MAINNET = 'MAINNET'
728
- }
729
- ```
730
-
731
- - **`TESTNET`**: Represents the testnet TON network.
732
- - **`MAINNET`**: Represents the mainnet TON network.
733
-
734
-
735
- ### `SDKParams (Type)`
736
- ```typescript
737
- export type SDKParams = {
738
- network: Network;
739
- delay?: number;
740
- TACParams?: TACParams;
741
- TONParams?: TONParams;
742
- customLiteSequencerEndpoints?: string[];
743
- }
744
- ```
745
-
746
- Parameters for SDK:
747
- - **`network`**: Specifies TON network (`Network` type).
748
- - **`delay`** *(optional)*: Delay (in seconds) for requests to the TON client. Default is *0*.
749
- - **`TACParams`** *(optional)*: Custom parameters for TAC side
750
- - **`TONParams`** *(optional)*: Custom parameters for TON side
751
- - **`customLiteSequencerEndpoints`** *(optional)*: Custom lite sequencer endpoints for API access.
752
-
753
-
754
- ### `TONParams (Type)`
755
- ```typescript
756
- export type TONParams = {
757
- contractOpener?: ContractOpener;
758
- settingsAddress?: string;
759
- }
760
- ```
761
- TON Parameters for SDK:
762
- - **`contractOpener`** *(optional)*: Client used for TON smart contract interaction. Default is `orbsOpener4`. Set for tests only
763
- - **`settingsAddress`** *(optional)*: TON settings contract address. Needed to retrieve protocol data. Set for tests only
764
-
765
-
766
- ### `TACParams (Type)`
767
- ```typescript
768
- export type TACParams = {
769
- provider?: AbstractProvider;
770
- settingsAddress?: string | Addressable;
771
- settingsABI?: Interface | InterfaceAbi;
772
- crossChainLayerABI?: Interface | InterfaceAbi;
773
- crossChainLayerTokenABI?: Interface | InterfaceAbi;
774
- crossChainLayerTokenBytecode?: string;
775
- }
776
- ```
777
-
778
- TAC Parameters for SDK:
779
- - **`provider`** *(optional)*: Provider used for TAC smart contract interaction. Set for increasing rate limit or tests only
780
- - **`settingsAddress`** *(optional)*: TAC settings contract address. Needed to retrieve protocol data. Set for tests only
781
- - **`settingsABI`** *(optional)*: TAC settings contract ABI. Set for tests only
782
- - **`crossChainLayerABI`** *(optional)*: TAC CCL contract ABI. Set for tests only
783
- - **`crossChainLayerTokenABI`** *(optional)*: TAC CCL Token contract ABI. Set for tests only
784
- - **`crossChainLayerTokenBytecode`** *(optional)*: TAC CCL Token contract bytecode. Set for tests only
785
-
786
-
787
- ### `EvmProxyMsg (Type)`
788
- ```typescript
789
- export type EvmProxyMsg = {
790
- evmTargetAddress: string,
791
- methodName?: string,
792
- encodedParameters?: string,
793
- gasLimit?: bigint,
794
- }
795
- ```
796
- Represents a proxy message to a TAC.
797
- - **`evmTargetAddress`**: Target address on the EVM network.
798
- - **`methodName`** *(optional)*: Method name to be called on the target contract. Either method name `MethodName` or signature `MethodName(bytes,bytes)` must be specified (strictly (bytes,bytes)).
799
- - **`encodedParameters`** *(optional)*: Parameters for the method, encoded as a string.
800
- - **`gasLimit`** *(optional)*: `gasLimit` is a parameter that will be passed on the TAC side. The executor must allocate at least gasLimit gas for executing the transaction on the TAC side. If this parameter is not specified, it will be calculated using the `simulateTACMessage` method(prefered).
801
-
802
- This structure defines the logic you want to execute on the TAC side. This message is sent along with all the sharded messages related to the jetton bridging, enabling the TAC to process the intended logic on the TAC side during the crosschain transaction.
803
-
804
-
805
- ### `AssetBridgingData (Type)`
806
-
807
- This structure is used to specify the details of the Assets you want to bridge for your operation. This allows you to precisely control the tokens and amounts involved in your crosschain transaction.
808
-
809
- ```typescript
810
- export type WithAddress = {
811
- /**
812
- * Address of TAC or TON token.
813
- * Empty if sending native TON coin.
814
- */
815
- address?: string;
816
- };
817
-
818
- export type RawAssetBridgingData = {
819
- /** Raw format, e.g. 12340000000 (=12.34 tokens if decimals is 9) */
820
- rawAmount: bigint;
821
- } & WithAddress;
822
-
823
- export type UserFriendlyAssetBridgingData = {
824
- /**
825
- * User friendly format, e.g. 12.34 tokens
826
- * Specified value will be converted automatically to raw format: 12.34 * (10^decimals).
827
- * No decimals should be specified.
828
- */
829
- amount: number;
830
- /**
831
- * Decimals may be specified manually.
832
- * Otherwise, SDK tries to extract them from chain.
833
- */
834
- decimals?: number;
835
- } & WithAddress;
836
-
837
- export type AssetBridgingData = RawAssetBridgingData | UserFriendlyAssetBridgingData;
838
- ```
839
-
840
- Represents general data for Asset operations.
841
- - **`rawAmount`** *(required if `amount` is not specified): Amount of Assets to be transferred taking into account the number of decimals.
842
- - **`amount`** *(required if `rawAmount` is not specified): Amount of Assets to be transferred.
843
- - **`decimals`** *(optional)*: Number of decimals for the asset. If not specified, the SDK will attempt to extract the decimals from the chain.
844
- - **`address`** *(optional)*: TVM or EVM asset's address.
845
-
846
- > **Note:** If you need to transfer a native TON coin, do not specify address.
847
-
848
-
849
- ### `TransactionLinker (Type)`
850
- ```typescript
851
- export type TransactionLinker = {
852
- caller: string,
853
- shardCount: number,
854
- shardsKey: string,
855
- timestamp: number,
856
- sendTransactionResult?: unknown,
857
- }
858
- ```
859
- Linker to track TON transaction for crosschain operation.
860
- - **`caller`**: Address of the transaction initiator.
861
- - **`shardCount`**: Number of shards involved.
862
- - **`shardsKey`**: Identifier for the shard.
863
- - **`timestamp`**: Timestamp of the transaction.
864
- - **`sendTransactionResult`** *(optional)*: Result of sending transaction. May be used to check result of sending transaction. Default TonClient does NOT fill this field. However, in unit tests @ton/sandbox set transaction result object to this field.
865
-
866
- This structure is designed to help track the entire execution path of a operation across all levels. By using it, you can identify the `operationId` and subsequently monitor the operation status through a public API. This is particularly useful for ensuring visibility and transparency in the operation lifecycle, allowing you to verify its progress and outcome.
867
-
868
-
869
- ### `SimplifiedStatuses (Enum)`
870
- ```typescript
871
- export enum SimplifiedStatuses {
872
- PENDING = 'PENDING',
873
- FAILED = 'FAILED',
874
- SUCCESSFUL = 'SUCCESSFUL',
875
- OPERATION_ID_NOT_FOUND = 'OPERATION_ID_NOT_FOUND',
876
- }
877
- ```
878
- Represents the simplified operation statuses.
879
- - **`PENDING`**: The operation in progress.
880
- - **`FAILED`**: The operation has failed.
881
- - **`SUCCESSFUL`**: The operation was executed successfully.
882
- - **`OPERATION_ID_NOT_FOUND`**: The operation ID was not found.
883
-
884
-
885
- ### `ContractOpener (Interface)`
886
-
887
- The ContractOpener interface provides methods to interact with smart contracts on the TON network. It allows opening contracts for interaction and retrieving contract states.
888
- ```typescript
889
- export interface ContractOpener {
890
- open<T extends Contract>(src: T): OpenedContract<T> | SandboxContract<T>;
891
-
892
- getContractState(address: Address): Promise<{
893
- balance: bigint;
894
- state: 'active' | 'uninitialized' | 'frozen';
895
- code: Buffer | null;
896
- }>;
897
- }
898
- ```
899
-
900
-
901
- ### `TACSimulationRequest`
902
-
903
- ```typescript
904
- export type TACSimulationRequest = {
905
- tacCallParams: {
906
- arguments: string;
907
- methodName: string;
908
- target: string;
909
- };
910
- extraData: string;
911
- feeAssetAddress: string;
912
- shardsKey: number;
913
- tonAssets: {
914
- amount: string;
915
- tokenAddress: string;
916
- }[];
917
- tonCaller: string;
918
- };
919
- ```
920
-
921
- Represents a request to simulate an TAC message.
922
-
923
- - **`tacCallParams`**: An object containing parameters for the TAC call.
924
- - **`arguments`**: Encoded arguments for the TAC method.
925
- - **`methodName`**: Name of the method to be called on the target TAC contract.
926
- - **`target`**: The target address on the TAC network.
927
- - **`extraData`**: Additional non-root data to be included in TAC call.
928
- - **`feeAssetAddress`**: Address of the asset used to cover fees; empty string if using native TON.
929
- - **`shardsKey`**: Key identifying shards for the operation.
930
- - **`tonAssets`**: An array of assets involved in the transaction.
931
- - **`amount`**: Amount of the asset to be transferred.
932
- - **`tokenAddress`**: Address of the token.
933
- - **`tonCaller`**: Address of the caller in the TON.
934
-
935
-
936
- ### `BlockchainType`
937
-
938
- ```typescript
939
- export enum BlockchainType {
940
- TAC = 'TAC',
941
- TON = 'TON',
942
- }
943
- ```
944
-
945
- Represents blockchain type.
946
-
947
-
948
- ### `TransactionData`
949
-
950
- ```typescript
951
- export type TransactionData = {
952
- hash: string;
953
- blockchainType: BlockchainType;
954
- };
955
- ```
956
-
957
- Represents transaction details.
958
- - **`hash`**: The hash of the transaction.
959
- - **`blockchainType`**: The type of the blockchain (`TON` or `TAC`).
960
-
961
-
962
- ### `NoteInfo`
963
-
964
- ```typescript
965
- export type NoteInfo = {
966
- content: string;
967
- errorName: string;
968
- internalMsg: string;
969
- internalBytesError: string;
970
- };
971
- ```
972
-
973
- Provides detailed information about any notes or errors encountered during operation processing.
974
-
975
- - **`content`**: Content of the note.
976
- - **`errorName`**: Name of the error.
977
- - **`internalMsg`**: Internal message related to the note or error.
978
- - **`internalBytesError`**: Detailed bytes error information.
979
-
980
-
981
- ### `StageName`
982
-
983
- ```typescript
984
- export enum StageName {
985
- COLLECTED_IN_TAC = 'collectedInTAC',
986
- INCLUDED_IN_TAC_CONSENSUS = 'includedInTACConsensus',
987
- EXECUTED_IN_TAC = 'executedInTAC',
988
- COLLECTED_IN_TON = 'collectedInTON',
989
- INCLUDED_IN_TON_CONSENSUS = 'includedInTONConsensus',
990
- EXECUTED_IN_TON = 'executedInTON',
991
- }
992
- ```
993
-
994
- Represents stage in TAC protocol.
995
-
996
-
997
- ### `StageData`
998
-
999
- ```typescript
1000
- export type StageData = {
1001
- success: boolean;
1002
- timestamp: number;
1003
- transactions: TransactionData[] | null;
1004
- note: NoteInfo | null;
1005
- };
1006
- ```
1007
-
1008
- Represents data for a specific stage of operation execution.
1009
-
1010
- #### **Properties**
1011
-
1012
- - **`success`**: Indicates whether the stage was successful.
1013
- - **`timestamp`**: Timestamp of when the stage was executed.
1014
- - **`transactions`** *(optional)*: Array of transaction data related to the stage. `null` if none.
1015
- - **`note`** *(optional)*: Additional notes or errors related to the stage. `null` if none.
1016
-
1017
-
1018
- ### `StatusInfo`
1019
-
1020
- ```typescript
1021
- export type StatusInfo = StageData & {
1022
- stage: StageName;
1023
- };
1024
- ```
1025
-
1026
- Combines `StageData` with an additional stage identifier.
1027
-
1028
- - **`stage`**: Current stage in `StageName` enum.
1029
- - **Other Properties from `StageData`**
1030
-
1031
-
1032
- ### `OperationType`
1033
-
1034
- ```typescript
1035
- export enum OperationType {
1036
- PENDING = "PENDING",
1037
- TON_TAC_TON = "TON-TAC-TON",
1038
- ROLLBACK = "ROLLBACK",
1039
- TON_TAC = "TON-TAC",
1040
- TAC_TON = "TAC-TON",
1041
- UNKNOWN = "UNKNOWN",
1042
- }
1043
- ```
1044
-
1045
- Provides information about transaction.
1046
-
1047
- - **`PENDING`**: The transaction is still processing and has not yet reached a final state.
1048
- - **`TON_TAC_TON`**:
1049
- The transaction succeeded fully:
1050
- - Executed on **TAC** (successfully interacted with dapp)
1051
- - Processed a `roundTrip` message (e.g., a cross-chain callback - bridging back received assets).
1052
- - **`ROLLBACK`**: The transaction failed on TAC, and funds were rolled back to their original on TON (e.g., tokens returned to the sender).
1053
- - **`TON_TAC`**: The transaction was fully executed on TAC. (successfully interacted with dapp or assets were bridged)
1054
- - **`TAC_TON`**: The cross-chain bridge operation from TAC to TON has completed successfully (e.g., tokens bridged to TON).
1055
- - **`UNKNOWN`**: The status could not be determined (e.g., due to network errors, invalid operation ID, or outdated data).
1056
-
1057
-
1058
- ### `ProfilingStageData`
1059
-
1060
- ```typescript
1061
- export type ProfilingStageData = {
1062
- exists: boolean;
1063
- stageData: StageData | null;
1064
- };
1065
-
1066
- ```
1067
-
1068
- Provides profiling information for a specific stage.
1069
-
1070
- - **`exists`**: Indicates whether profiling data exists for the stage.
1071
- - **`stageData`** *(optional)*: Detailed data of the stage. `null` if none.
1072
-
1073
-
1074
- ### `ExecutionStages`
1075
-
1076
- ```typescript
1077
- export type ExecutionStages = {
1078
- operationType: OperationType;
1079
- } & Record<StageName, ProfilingStageData>;
1080
-
1081
- ```
1082
-
1083
- Represents the profiling data for all execution stages within an operation.
1084
- - **`operationType`**.
1085
- - **`collectedInTAC`**.
1086
- - **`includedInTACConsensus`**.
1087
- - **`executedInTAC`**.
1088
- - **`collectedInTON`**.
1089
- - **`includedInTONConsensus`**.
1090
- - **`executedInTON`**.
1091
-
1092
-
1093
- ### `ExecutionStagesByOperationId`
1094
-
1095
- ```typescript
1096
- export type ExecutionStagesByOperationId = Record<string, ExecutionStages>;
1097
- ```
1098
-
1099
- Maps each `operationId` to its respective `executionStages`.
1100
-
1101
-
1102
- ### `StatusInfosByOperationId`
1103
-
1104
- ```typescript
1105
- export type StatusInfosByOperationId = Record<string, StatusInfo>;
1106
- ```
1107
-
1108
- Maps each `operationId` to its respective `statusInfo`.
1109
-
1110
-
1111
- ### `OperationIdsByShardsKeyResponse`
1112
-
1113
- Maps each `operationId[]` to its respective `shardsKey`.
1114
-
1115
-
1116
- ### `UserWalletBalanceExtended`
1117
-
1118
- Provides extended information about a user's Jetton balance.
1119
-
1120
- #### **Union Types**
1121
-
1122
- - **If the Jetton wallet exists:**
1123
- ```typescript
1124
- {
1125
- exists: true;
1126
- amount: number; // The formatted balance of the Jetton token.
1127
- rawAmount: bigint; // The raw balance of the Jetton token.
1128
- decimals: number; // The number of decimals for the Jetton token.
1129
- }
1130
- ```
1131
-
1132
- - **If the Jetton wallet does not exist:**
1133
- ```typescript
1134
- {
1135
- exists: false;
1136
- }
1137
- ```
1138
-
1139
-
1140
- - **`exists`**: Indicates whether the Jetton wallet exists.
1141
- - **`amount`** *(optional)*: The formatted balance of the Jetton token. Present only if `exists` is `true`.
1142
- - **`rawAmount`** *(optional)*: The raw balance of the Jetton token. Present only if `exists` is `true`.
1143
- - **`decimals`** *(optional)*: The number of decimals for the Jetton token. Present only if `exists` is `true`.
1144
-
1145
-
1146
- ### `TACSimulationResults`
1147
-
1148
- ```typescript
1149
- export type TACSimulationResults = {
1150
- estimatedGas: bigint;
1151
- estimatedJettonFeeAmount: string;
1152
- feeParams: {
1153
- currentBaseFee: string;
1154
- isEip1559: boolean;
1155
- suggestedGasPrice: string;
1156
- suggestedGasTip: string;
1157
- };
1158
- message: string;
1159
- outMessages:
1160
- | {
1161
- callerAddress: string;
1162
- operationId: string;
1163
- payload: string;
1164
- queryId: number;
1165
- targetAddress: string;
1166
- tokensBurned: {
1167
- amount: string;
1168
- tokenAddress: string;
1169
- }[];
1170
- tokensLocked: {
1171
- amount: string;
1172
- tokenAddress: string;
1173
- }[];
1174
- }[]
1175
- | null;
1176
- simulationError: string;
1177
- simulationStatus: boolean;
1178
- debugInfo: {
1179
- from: string;
1180
- to: string;
1181
- callData: string;
1182
- blockNumber: number;
1183
- };
1184
- };
1185
- ```
1186
- Provides TAC simulation results.
1187
-
1188
- - **`estimatedGas`**: The estimated gas required for the message.
1189
- - **`estimatedJettonFeeAmount`**: The estimated fee amount in Jettons.
1190
- - **`feeParams`**: The parameters related to the fee.
1191
- - **`currentBaseFee`**: The current base fee.
1192
- - **`isEip1559`**: Indicates if EIP-1559 is applied.
1193
- - **`suggestedGasPrice`**: The suggested gas price.
1194
- - **`suggestedGasTip`**: The suggested gas tip.
1195
- - **`message`**: The message details.
1196
- - **`outMessages`** *(optional)*: The outgoing messages. Maybe `null` if there is a bridge operation.
1197
- - **`callerAddress`**: The address of the caller.
1198
- - **`operationId`**: The operation ID.
1199
- - **`payload`**: The payload.
1200
- - **`queryId`**: The query ID.
1201
- - **`targetAddress`**: The target address.
1202
- - **`tokensBurned`**: The tokens burned.
1203
- - **`amount`**: The amount of tokens burned.
1204
- - **`tokenAddress`**: The address of the token.
1205
- - **`tokensLocked`**: The tokens locked.
1206
- - **`simulationError`**: Any error encountered during the simulation.
1207
- - **`simulationStatus`**: The status of the simulation.
1208
- - **`debugInfo`**: Debugging information.
1209
- - **`from`**: The sender address.
1210
- - **`to`**: The recipient address.
1211
- - **`callData`**: The call data.
1212
- - **`blockNumber`**: The block number.
1213
- ---
1214
-
1215
- ## Usage
1216
-
1217
- ```typescript
1218
- import { TacSdk } from '@tonappchain/sdk';
1219
- import { TonConnectUI } from '@tonconnect/ui';
1220
- import { ethers } from 'ethers';
1221
-
1222
- // Create EVM payload for DappProxy
1223
- const abi = new ethers.AbiCoder();
1224
- const encodedParameters = abi.encode(
1225
- ['tuple(uint256,uint256,address[],address)'],
1226
- [
1227
- [
1228
- tokenAAmount,
1229
- tokenBAmount,
1230
- [EVMtokenAAddress, EVMtokenBAddress],
1231
- proxyDapp
1232
- ]
1233
- ]
1234
- );
1235
- const evmProxyMsg: EvmProxyMsg = {
1236
- evmTargetAddress: DappProxyAddress,
1237
- methodName: 'addLiquidity',
1238
- encodedParameters
1239
- };
1240
-
1241
- // Create jetton transfer messages corresponding to EVM tokens, e.g., two tokens for adding liquidity to a pool
1242
- const assets: AssetBridgingData[] = [
1243
- {
1244
- address: TVMtokenAAddress,
1245
- amount: tokenAAmount
1246
- },
1247
- {
1248
- address: TVMtokenBAddress,
1249
- amount: tokenBAmount
1250
- }
1251
- ];
1252
-
1253
- const sdkParams: SDKParams = {
1254
- network: Network.TESTNET
1255
- };
1256
- const tacSdk = await TacSdk.create(sdkParams);
1257
-
1258
- //Send transaction via tonConnect or mnemonic
1259
- const tonConnectUI = new TonConnectUI({
1260
- manifestUrl: config.tonconnectManifestUrl as string
1261
- });
1262
- const sender = await SenderFactory.getSender({
1263
- tonConnect: tonConnectUI
1264
- });
1265
-
1266
- await tacSdk.sendCrossChainTransaction(evmProxyMsg, sender, assets);
1267
-
1268
- tacSdk.closeConnections();
1269
- ```
1270
- For a detailed example, see `test/sendSwap.ts` or `test/sendRemoveLiquidity.ts`, which demonstrates swapping tokens and removing liquidity on Uniswap and tracking the transaction status.
1271
-
1272
- ---
1273
-
1274
- ## License
1275
-
1276
- MIT
1
+ # TacSdk
2
+
3
+ [![Version npm](https://img.shields.io/npm/v/@tonappchain/sdk.svg?logo=npm)](https://www.npmjs.com/package/@tonappchain/sdk)
4
+ [![Downloads](https://img.shields.io/npm/dm/@tonappchain/sdk.svg)](https://www.npmjs.com/package/@tonappchain/sdk)
5
+ [![Try on RunKit](https://badge.runkitcdn.com/@tonappchain/sdk.svg)](https://runkit.com/npm/@tonappchain/sdk)
6
+
7
+
8
+ The TAC SDK makes it possible to create hybrid dApps that let TON users interact directly with EVM smart contracts without needing to manage multiple wallets or understand the complexities of cross-chain messaging.
9
+
10
+ ### Documentation
11
+
12
+ For full documentation and examples, please visit [TAC SDK Documentation](https://docs.tac.build/build/sdk/introduction).
13
+
14
+ ### Installation
15
+
16
+ ```bash
17
+ npm install @tonappchain/sdk
18
+ ```
19
+
20
+ or
21
+
22
+ ```bash
23
+ yarn add @tonappchain/sdk
24
+ ```
25
+
26
+
27
+ ## Features
28
+
29
+ The TAC SDK enables you to create frontends that:
30
+
31
+ - Connect to TON wallets like Tonkeeper or Tonhub
32
+ - Send transactions from TON to your EVM contracts
33
+ - Track cross-chain transaction status in real-time
34
+ - Handle tokens across both chains
35
+ - Create a seamless user experience for TON users
36
+
37
+ ## Available Resources
38
+
39
+
40
+ ### SDK Components
41
+
42
+ - **[`TacSdk`](./docs/sdks/tac_sdk.md)**: The main class for interacting with the TAC protocol.
43
+ - [`create`](./docs/sdks/tac_sdk.md#create-static): Initializes the SDK instance.
44
+ - [`sendCrossChainTransaction`](./docs/sdks/tac_sdk.md#sendcrosschaintransaction): Sends a cross-chain transaction from TON to TAC.
45
+ - [`getEVMTokenAddress`](./docs/sdks/tac_sdk.md#getevmtokenaddress): Gets the TAC address for a TON token.
46
+ - [`getTVMTokenAddress`](./docs/sdks/tac_sdk.md#gettvmtokenaddress): Gets the TON address for a TAC token.
47
+ - [`getTransactionSimulationInfo`](./docs/sdks/tac_sdk.md#simulatetacmessage): Performs a complete simulation of a crosschain transaction to estimate fees and gather execution-related metadata.
48
+ - [`getUserJettonBalance`](./docs/sdks/tac_sdk.md#getuserjettonbalance): Gets a user's Jetton balance (raw).
49
+ - [`getUserJettonBalanceExtended`](./docs/sdks/tac_sdk.md#getuserjettonbalanceextended): Gets extended Jetton balance info (including decimals).
50
+ - [`getUserJettonWalletAddress`](./docs/sdks/tac_sdk.md#getuserjettonwalletaddress): Calculates a user's Jetton wallet address.
51
+ - [`nativeTONAddress (getter)`](./docs/sdks/tac_sdk.md#nativetonaddress-getter): Placeholder address for native TON.
52
+ - [`nativeTACAddress (getter)`](./docs/sdks/tac_sdk.md#nativetacaddress-getter): Gets the native asset address on the TAC chain.
53
+ - *(See file for more...)*
54
+
55
+ - **[`OperationTracker`](./docs/sdks/operation_tracker.md)**: Tools for monitoring cross-chain operation status.
56
+ - [`constructor`](./docs/sdks/operation_tracker.md#constructor): Creates a tracker instance.
57
+ - [`getOperationId`](./docs/sdks/operation_tracker.md#getoperationid): Retrieves the Operation ID from a `TransactionLinker`.
58
+ - [`getStageProfiling`](./docs/sdks/operation_tracker.md#getstageprofiling): Gets detailed timing and status for all stages of an operation.
59
+ - [`getSimplifiedOperationStatus`](./docs/sdks/operation_tracker.md#getsimplifiedoperationstatus): Gets a simplified overall status (Pending, Successful, Failed, Not Found).
60
+ - *(See file for more...)*
61
+
62
+ - **[`Senders`](./docs/sdks/senders.md)**: Handles signing and sending TON transactions.
63
+ - [`TonConnectSender`](./docs/sdks/senders.md#tonconnectsender): Implements sending via TonConnect UI.
64
+ - [`RawSender`](./docs/sdks/senders.md#rawsender): Implements sending using a raw private key.
65
+
66
+ - **[`Utilities`](./docs/sdks/utilities.md)**: Helper functions and interfaces.
67
+ - [`startTracking`](./docs/sdks/utilities.md#starttracking): Utility function to poll and log operation status to the console.
68
+
69
+ ### Data Models
70
+
71
+ - **[`Enums`](./docs/models/enums.md)**: Key enumerations used by the SDK.
72
+ - [`Network`](./docs/models/enums.md#network): `TESTNET` or `MAINNET`.
73
+ - [`SimplifiedStatuses`](./docs/models/enums.md#simplifiedstatuses): `PENDING`, `FAILED`, `SUCCESSFUL`, `OPERATION_ID_NOT_FOUND`.
74
+ - [`OperationType`](./docs/models/enums.md#operationtype): Detailed operation types (`PENDING`, `TON_TAC_TON`, `ROLLBACK`, etc.).
75
+ - [`StageName`](./docs/models/enums.md#stagename): Identifiers for tracking stages (`COLLECTED_IN_TAC`, `EXECUTED_IN_TAC`, etc.).
76
+
77
+ - **[`Structs`](./docs/models/structs.md)**: Core data structures.
78
+ - [`AssetBridgingData`](./docs/models/structs.md#assetbridgingdata): Specifies assets to bridge (TON or Jettons).
79
+ - [`EvmProxyMsg`](./docs/models/structs.md#evmproxymsg): Defines the target EVM call details.
80
+ - [`TransactionLinker`](./docs/models/structs.md#transactionlinker): Identifies a cross-chain operation.
81
+ - *(See file for more...)*
82
+
83
+ Navigate through the linked files for full details on parameters, return types, examples, and more.
84
+
85
+ ### TACHeader
86
+ > **Note:** The TAC protocol only knows how to send data to contracts that inherit from a TacProxy (TacProxyV1) contract. Such a contract must have a strictly defined signature of its methods. It is specified below:
87
+
88
+ ```
89
+ function myProxyFunction(bytes calldata tacHeader, bytes calldata arguments) external onlyTacCCL {
90
+ // Function implementation
91
+ }
92
+ ```
93
+
94
+ > **Note:** methodName in `evmProxyMsg` must be either a simple method name or a signature of the form MethodName(bytes,bytes)
95
+
96
+ The first argument of methods must always be TACHeader. It is sent by protocol, augmented with data from executor.
97
+ - **`bytes tacHeader`**: Encoded structure TacHeaderV1, containing:
98
+ - **`uint64 shardsKey`**: ID you can specify for yourself an inside message to the TVM contract on the TON network.
99
+ - **`uint256 timestamp`**: The block timestamp on TON where the user's message was created.
100
+ - **`bytes32 operationId`**: Unique identifier for the message created by the TAC infrastructure.
101
+ - **`string tvmCaller`**: The TON user's wallet address that sent the message.
102
+ - **`bytes extraData`**: Untrusted extra data, provided by executor with the current message if needed. Otherwise, it's an empty bytes array.
103
+
104
+ You need to specify all the remaining data you need in tuple (bytes) in arguments. For example this is how arguments for addLiquidity method in UniswapV2 (a special proxy contract for it) will look like:
105
+
106
+ ```
107
+ const abi = new ethers.AbiCoder();
108
+ const encodedParameters = abi.encode(
109
+ ['tuple(address,address,uint256,uint256,uint256,uint256,address,uint256)'],
110
+ [
111
+ [
112
+ EVM_TOKEN_A_ADDRESS,
113
+ EVM_TOKEN_B_ADDRESS,
114
+ amountA,
115
+ amountB,
116
+ amountAMin,
117
+ amountBMin,
118
+ UNISWAPV2_PROXY_ADDRESS,
119
+ deadline
120
+ ]
121
+ ]
122
+ );
123
+ ```
124
+ More details in [sendAddLiquidity.ts](tests/uniswap_v2/sendAddLiquidity.ts) and in other tests.
125
+
126
+ ---
127
+
128
+ ## Usage
129
+
130
+ ```typescript
131
+ import { TacSdk } from '@tonappchain/sdk';
132
+ import { TonConnectUI } from '@tonconnect/ui';
133
+ import { ethers } from 'ethers';
134
+
135
+ // Create EVM payload for DappProxy
136
+ const abi = new ethers.AbiCoder();
137
+ const encodedParameters = abi.encode(
138
+ ['tuple(uint256,uint256,address[],address)'],
139
+ [
140
+ [
141
+ tokenAAmount,
142
+ tokenBAmount,
143
+ [EVMtokenAAddress, EVMtokenBAddress],
144
+ proxyDapp
145
+ ]
146
+ ]
147
+ );
148
+ const evmProxyMsg: EvmProxyMsg = {
149
+ evmTargetAddress: DappProxyAddress,
150
+ methodName: 'addLiquidity',
151
+ encodedParameters
152
+ };
153
+
154
+ // Create jetton transfer messages corresponding to EVM tokens, e.g., two tokens for adding liquidity to a pool
155
+ const assets: AssetBridgingData[] = [
156
+ {
157
+ address: TVMtokenAAddress,
158
+ amount: tokenAAmount
159
+ },
160
+ {
161
+ address: TVMtokenBAddress,
162
+ amount: tokenBAmount
163
+ }
164
+ ];
165
+
166
+ const sdkParams: SDKParams = {
167
+ network: Network.TESTNET
168
+ };
169
+ const tacSdk = await TacSdk.create(sdkParams);
170
+
171
+ //Send transaction via tonConnect or mnemonic
172
+ const tonConnectUI = new TonConnectUI({
173
+ manifestUrl: config.tonconnectManifestUrl as string
174
+ });
175
+ const sender = await SenderFactory.getSender({
176
+ tonConnect: tonConnectUI
177
+ });
178
+
179
+ await tacSdk.sendCrossChainTransaction(evmProxyMsg, sender, assets);
180
+
181
+ tacSdk.closeConnections();
182
+ ```
183
+ For a detailed example, see `test/sendSwap.ts` or `test/sendRemoveLiquidity.ts`, which demonstrates swapping tokens and removing liquidity on Uniswap and tracking the transaction status.
184
+
185
+ ---
186
+
187
+ ## License
188
+
189
+ MIT