@tonappchain/sdk 0.7.0-rc14 → 0.7.0-rc16

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.
Files changed (56) hide show
  1. package/README.md +7 -7
  2. package/dist/adapters/retryableContractOpener.js +1 -1
  3. package/dist/assets/AssetFactory.js +1 -1
  4. package/dist/assets/FT.d.ts +8 -12
  5. package/dist/assets/FT.js +69 -36
  6. package/dist/assets/NFT.d.ts +4 -2
  7. package/dist/assets/NFT.js +14 -2
  8. package/dist/assets/TON.d.ts +4 -10
  9. package/dist/assets/TON.js +17 -15
  10. package/dist/errors/index.d.ts +1 -1
  11. package/dist/errors/index.js +7 -2
  12. package/dist/errors/instances.d.ts +8 -1
  13. package/dist/errors/instances.js +22 -16
  14. package/dist/index.d.ts +2 -1
  15. package/dist/index.js +5 -3
  16. package/dist/interfaces/Asset.d.ts +22 -17
  17. package/dist/interfaces/ILiteSequencerClient.d.ts +14 -1
  18. package/dist/interfaces/IOperationTracker.d.ts +16 -1
  19. package/dist/interfaces/ISimulator.d.ts +7 -36
  20. package/dist/interfaces/ITACTransactionManager.d.ts +15 -0
  21. package/dist/interfaces/ITONTransactionManager.d.ts +21 -0
  22. package/dist/interfaces/ITONTransactionManager.js +2 -0
  23. package/dist/interfaces/ITacSDK.d.ts +51 -13
  24. package/dist/interfaces/index.d.ts +2 -1
  25. package/dist/interfaces/index.js +2 -1
  26. package/dist/sdk/Configuration.d.ts +1 -0
  27. package/dist/sdk/Configuration.js +52 -4
  28. package/dist/sdk/Consts.d.ts +1 -0
  29. package/dist/sdk/Consts.js +5 -4
  30. package/dist/sdk/LiteSequencerClient.d.ts +5 -3
  31. package/dist/sdk/LiteSequencerClient.js +27 -4
  32. package/dist/sdk/OperationTracker.d.ts +3 -1
  33. package/dist/sdk/OperationTracker.js +51 -11
  34. package/dist/sdk/Simulator.d.ts +6 -12
  35. package/dist/sdk/Simulator.js +30 -124
  36. package/dist/sdk/TACTransactionManager.d.ts +10 -0
  37. package/dist/sdk/TACTransactionManager.js +92 -0
  38. package/dist/sdk/TONTransactionManager.d.ts +17 -0
  39. package/dist/sdk/TONTransactionManager.js +209 -0
  40. package/dist/sdk/TacSdk.d.ts +16 -10
  41. package/dist/sdk/TacSdk.js +52 -19
  42. package/dist/sdk/TxFinalizer.d.ts +3 -2
  43. package/dist/sdk/TxFinalizer.js +8 -8
  44. package/dist/sdk/Utils.d.ts +8 -4
  45. package/dist/sdk/Utils.js +80 -12
  46. package/dist/sdk/Validator.d.ts +2 -2
  47. package/dist/sdk/Validator.js +1 -1
  48. package/dist/structs/InternalStruct.d.ts +6 -2
  49. package/dist/structs/Struct.d.ts +70 -16
  50. package/dist/wrappers/JettonMaster.d.ts +1 -1
  51. package/dist/wrappers/JettonMaster.js +1 -1
  52. package/package.json +4 -3
  53. package/dist/interfaces/ITransactionManager.d.ts +0 -35
  54. package/dist/sdk/TransactionManager.d.ts +0 -22
  55. package/dist/sdk/TransactionManager.js +0 -272
  56. /package/dist/interfaces/{ITransactionManager.js → ITACTransactionManager.js} +0 -0
@@ -1,35 +0,0 @@
1
- import { Wallet } from 'ethers';
2
- import type { SenderAbstraction } from '../sender';
3
- import { CrossChainTransactionOptions, CrosschainTx, EvmProxyMsg, OperationIdsByShardsKey, TransactionLinkerWithOperationId, WaitOptions } from '../structs/Struct';
4
- import { Asset } from './Asset';
5
- export interface ITransactionManager {
6
- /**
7
- * Sends a single cross-chain transaction.
8
- * @param evmProxyMsg Encoded EVM proxy message to bridge.
9
- * @param sender Sender abstraction for TVM message sending.
10
- * @param assets Optional assets to attach to the cross-chain message.
11
- * @param options Optional cross-chain execution options (fees, executors, extra data).
12
- * @param waitOptions Optional policy to wait for operation id resolution.
13
- * @returns Transaction linker with operation id for tracking.
14
- */
15
- sendCrossChainTransaction(evmProxyMsg: EvmProxyMsg, sender: SenderAbstraction, assets?: Asset[], options?: CrossChainTransactionOptions, waitOptions?: WaitOptions<string>): Promise<TransactionLinkerWithOperationId>;
16
- /**
17
- * Sends multiple cross-chain transactions in a batch.
18
- * @param sender Sender abstraction for TVM message sending.
19
- * @param txs List of cross-chain transactions to broadcast.
20
- * @param waitOptions Optional policy for waiting on operation ids by shard keys.
21
- * @returns Array of transaction linkers, one per submitted transaction.
22
- */
23
- sendCrossChainTransactions(sender: SenderAbstraction, txs: CrosschainTx[], waitOptions?: WaitOptions<OperationIdsByShardsKey>): Promise<TransactionLinkerWithOperationId[]>;
24
- /**
25
- * Bridges native EVM value and optional assets to TON chain via executor.
26
- * @param signer Ethers Wallet used to sign EVM transaction.
27
- * @param value Amount of native EVM currency (wei as bigint).
28
- * @param tonTarget Recipient TVM address on TON.
29
- * @param assets Optional list of TAC assets to include.
30
- * @param tvmExecutorFee Optional explicit TON-side executor fee.
31
- * @param tvmValidExecutors Optional whitelist of allowed TVM executors.
32
- * @returns EVM transaction hash or bridge identifier.
33
- */
34
- bridgeTokensToTON(signer: Wallet, value: bigint, tonTarget: string, assets?: Asset[], tvmExecutorFee?: bigint, tvmValidExecutors?: string[]): Promise<string>;
35
- }
@@ -1,22 +0,0 @@
1
- import { Cell } from '@ton/ton';
2
- import { Wallet } from 'ethers';
3
- import { Asset, IConfiguration, ILogger, IOperationTracker, ISimulator, ITransactionManager } from '../interfaces';
4
- import type { SenderAbstraction } from '../sender';
5
- import { CrossChainTransactionOptions, CrosschainTx, EvmProxyMsg, OperationIdsByShardsKey, TransactionLinker, TransactionLinkerWithOperationId, ValidExecutors, WaitOptions } from '../structs/Struct';
6
- export declare class TransactionManager implements ITransactionManager {
7
- private readonly config;
8
- private readonly simulator;
9
- private readonly operationTracker;
10
- private readonly logger;
11
- private readonly evmDataCellBuilder;
12
- constructor(config: IConfiguration, simulator: ISimulator, operationTracker: IOperationTracker, logger?: ILogger, options?: {
13
- evmDataCellBuilder?: (transactionLinker: TransactionLinker, evmProxyMsg: EvmProxyMsg, validExecutors: ValidExecutors) => Cell;
14
- });
15
- private prepareCrossChainTransaction;
16
- private generateCrossChainMessages;
17
- sendCrossChainTransaction(evmProxyMsg: EvmProxyMsg, sender: SenderAbstraction, assets?: Asset[], options?: CrossChainTransactionOptions, waitOptions?: WaitOptions<string>): Promise<TransactionLinkerWithOperationId>;
18
- sendCrossChainTransactions(sender: SenderAbstraction, txs: CrosschainTx[], waitOptions?: WaitOptions<OperationIdsByShardsKey>): Promise<TransactionLinkerWithOperationId[]>;
19
- private prepareCrossChainTransactions;
20
- private waitForOperationIds;
21
- bridgeTokensToTON(signer: Wallet, value: bigint, tonTarget: string, assets?: Asset[], tvmExecutorFee?: bigint, tvmValidExecutors?: string[]): Promise<string>;
22
- }
@@ -1,272 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TransactionManager = void 0;
4
- const assets_1 = require("../assets");
5
- const Struct_1 = require("../structs/Struct");
6
- const Consts_1 = require("./Consts");
7
- const Logger_1 = require("./Logger");
8
- const Utils_1 = require("./Utils");
9
- const Validator_1 = require("./Validator");
10
- class TransactionManager {
11
- constructor(config, simulator, operationTracker, logger = new Logger_1.NoopLogger(), options) {
12
- this.config = config;
13
- this.simulator = simulator;
14
- this.operationTracker = operationTracker;
15
- this.logger = logger;
16
- this.evmDataCellBuilder = options?.evmDataCellBuilder ?? Utils_1.buildEvmDataCell;
17
- }
18
- async prepareCrossChainTransaction(evmProxyMsg, caller, assets, options) {
19
- this.logger.debug('Preparing cross-chain transaction');
20
- const { allowSimulationError = false, isRoundTrip = undefined, protocolFee = undefined, evmExecutorFee = undefined, tvmExecutorFee = undefined, calculateRollbackFee = true, } = options || {};
21
- let { evmValidExecutors = [], tvmValidExecutors = [] } = options || {};
22
- Validator_1.Validator.validateEVMAddress(evmProxyMsg.evmTargetAddress);
23
- Validator_1.Validator.validateEVMAddresses(options?.evmValidExecutors);
24
- Validator_1.Validator.validateTVMAddresses(options?.tvmValidExecutors);
25
- const aggregatedData = await (0, Utils_1.aggregateTokens)(assets);
26
- await Promise.all(aggregatedData.jettons.map((jetton) => jetton.checkCanBeTransferredBy(caller)));
27
- await Promise.all(aggregatedData.nfts.map((nft) => nft.checkCanBeTransferredBy(caller)));
28
- await aggregatedData.ton?.checkCanBeTransferredBy(caller);
29
- const tokensLength = aggregatedData.jettons.length + aggregatedData.nfts.length;
30
- this.logger.debug(`Tokens length: ${tokensLength}`);
31
- const transactionLinkerShardCount = tokensLength == 0 ? 1 : tokensLength;
32
- this.logger.debug(`Transaction linker shard count: ${transactionLinkerShardCount}`);
33
- const transactionLinker = (0, Utils_1.generateTransactionLinker)(caller, transactionLinkerShardCount);
34
- this.logger.debug(`Generated transaction linker: ${(0, Utils_1.formatObjectForLogging)(transactionLinker)}`);
35
- if (evmValidExecutors.length == 0) {
36
- evmValidExecutors = this.config.getTrustedTACExecutors;
37
- }
38
- if (tvmValidExecutors.length == 0) {
39
- tvmValidExecutors = this.config.getTrustedTONExecutors;
40
- }
41
- const { feeParams } = await this.simulator.getSimulationInfoForTransaction(evmProxyMsg, transactionLinker, assets ?? [], allowSimulationError, isRoundTrip, evmValidExecutors, tvmValidExecutors, calculateRollbackFee);
42
- if (evmProxyMsg.gasLimit == undefined) {
43
- evmProxyMsg.gasLimit = feeParams.gasLimit;
44
- }
45
- if (evmExecutorFee != undefined) {
46
- feeParams.evmExecutorFee = evmExecutorFee;
47
- }
48
- if (feeParams.isRoundTrip && tvmExecutorFee != undefined) {
49
- feeParams.tvmExecutorFee = tvmExecutorFee;
50
- }
51
- if (protocolFee != undefined) {
52
- feeParams.protocolFee = protocolFee;
53
- }
54
- this.logger.debug(`Resulting fee params: ${(0, Utils_1.formatObjectForLogging)(feeParams)}`);
55
- const validExecutors = {
56
- tac: evmValidExecutors,
57
- ton: tvmValidExecutors,
58
- };
59
- this.logger.debug(`Valid executors: ${(0, Utils_1.formatObjectForLogging)(validExecutors)}`);
60
- const evmData = this.evmDataCellBuilder(transactionLinker, evmProxyMsg, validExecutors);
61
- const messages = await this.generateCrossChainMessages(caller, evmData, aggregatedData, feeParams);
62
- const transaction = {
63
- validUntil: +new Date() + 15 * 60 * 1000,
64
- messages,
65
- network: this.config.network,
66
- };
67
- this.logger.debug('Transaction prepared');
68
- return { transaction, transactionLinker };
69
- }
70
- async generateCrossChainMessages(caller, evmData, aggregatedData, feeParams) {
71
- this.logger.debug(`Generating cross-chain messages`);
72
- const { jettons, nfts, ton = assets_1.TON.create(this.config) } = aggregatedData;
73
- let crossChainTonAmount = ton.rawAmount;
74
- let feeTonAmount = feeParams.protocolFee + feeParams.evmExecutorFee + feeParams.tvmExecutorFee;
75
- this.logger.debug(`Crosschain ton amount: ${crossChainTonAmount}`);
76
- this.logger.debug(`Fee ton amount: ${feeTonAmount}`);
77
- if (jettons.length == 0 && nfts.length == 0) {
78
- return [
79
- {
80
- address: this.config.TONParams.crossChainLayerAddress,
81
- value: crossChainTonAmount + feeTonAmount + Consts_1.TRANSACTION_TON_AMOUNT,
82
- payload: await ton.generatePayload({
83
- excessReceiver: caller,
84
- evmData,
85
- feeParams,
86
- }),
87
- },
88
- ];
89
- }
90
- const messages = [];
91
- let currentFeeParams = feeParams;
92
- for (const jetton of aggregatedData.jettons) {
93
- const payload = await jetton.generatePayload({
94
- excessReceiver: caller,
95
- evmData,
96
- crossChainTonAmount,
97
- forwardFeeTonAmount: feeTonAmount,
98
- feeParams: currentFeeParams,
99
- });
100
- const jettonWalletAddress = await jetton.getUserWalletAddress(caller);
101
- messages.push({
102
- address: jettonWalletAddress,
103
- value: crossChainTonAmount + feeTonAmount + Consts_1.TRANSACTION_TON_AMOUNT,
104
- payload,
105
- });
106
- crossChainTonAmount = 0n;
107
- feeTonAmount = 0n;
108
- currentFeeParams = undefined;
109
- }
110
- for (const nft of aggregatedData.nfts) {
111
- const payload = await nft.generatePayload({
112
- excessReceiver: caller,
113
- evmData,
114
- crossChainTonAmount,
115
- forwardFeeTonAmount: feeTonAmount,
116
- feeParams: currentFeeParams,
117
- });
118
- messages.push({
119
- address: nft.address,
120
- value: crossChainTonAmount + feeTonAmount + Consts_1.TRANSACTION_TON_AMOUNT,
121
- payload,
122
- });
123
- crossChainTonAmount = 0n;
124
- feeTonAmount = 0n;
125
- currentFeeParams = undefined;
126
- }
127
- this.logger.debug('Generating cross-chain messages success');
128
- return messages;
129
- }
130
- async sendCrossChainTransaction(evmProxyMsg, sender, assets, options, waitOptions) {
131
- const caller = sender.getSenderAddress();
132
- this.logger.debug(`Caller: ${caller}`);
133
- const { transaction, transactionLinker } = await this.prepareCrossChainTransaction(evmProxyMsg, caller, assets, options);
134
- await assets_1.TON.checkBalance(sender, this.config, [transaction]);
135
- this.logger.debug(`*****Sending transaction: ${(0, Utils_1.formatObjectForLogging)(transaction)}`);
136
- const sendTransactionResult = await sender.sendShardTransaction(transaction, this.config.network, this.config.TONParams.contractOpener);
137
- return waitOptions
138
- ? {
139
- sendTransactionResult,
140
- operationId: await this.operationTracker
141
- .getOperationId(transactionLinker, {
142
- ...waitOptions,
143
- successCheck: (operationId) => !!operationId,
144
- logger: this.logger,
145
- })
146
- .catch((error) => {
147
- this.logger.error(`Error while waiting for operation ID: ${error}`);
148
- return undefined;
149
- }),
150
- ...transactionLinker,
151
- }
152
- : { sendTransactionResult, ...transactionLinker };
153
- }
154
- async sendCrossChainTransactions(sender, txs, waitOptions) {
155
- const caller = sender.getSenderAddress();
156
- this.logger.debug(`Caller: ${caller}`);
157
- this.logger.debug('Preparing multiple cross-chain transactions');
158
- const { transactions, transactionLinkers } = await this.prepareCrossChainTransactions(txs, caller);
159
- await assets_1.TON.checkBalance(sender, this.config, transactions);
160
- this.logger.debug(`*****Sending transactions: ${(0, Utils_1.formatObjectForLogging)(transactions)}`);
161
- await sender.sendShardTransactions(transactions, this.config.network, this.config.TONParams.contractOpener);
162
- if (!waitOptions) {
163
- return transactionLinkers;
164
- }
165
- return await this.waitForOperationIds(transactionLinkers, caller, waitOptions);
166
- }
167
- async prepareCrossChainTransactions(txs, caller) {
168
- const transactions = [];
169
- const transactionLinkers = [];
170
- for (const { options, assets, evmProxyMsg } of txs) {
171
- const { transaction, transactionLinker } = await this.prepareCrossChainTransaction(evmProxyMsg, caller, assets, options);
172
- transactions.push(transaction);
173
- transactionLinkers.push(transactionLinker);
174
- }
175
- return { transactions, transactionLinkers };
176
- }
177
- async waitForOperationIds(transactionLinkers, caller, waitOptions) {
178
- this.logger.debug(`Waiting for operation IDs`);
179
- try {
180
- const operationIds = await this.operationTracker.getOperationIdsByShardsKeys(transactionLinkers.map((linker) => linker.shardsKey), caller, {
181
- ...waitOptions,
182
- logger: this.logger,
183
- successCheck: (operationIds) => Object.keys(operationIds).length == transactionLinkers.length &&
184
- Object.values(operationIds).every((ids) => ids.operationIds.length > 0),
185
- });
186
- this.logger.debug(`Operation IDs: ${(0, Utils_1.formatObjectForLogging)(operationIds)}`);
187
- return transactionLinkers.map((linker) => ({
188
- ...linker,
189
- operationId: operationIds[linker.shardsKey].operationIds.at(0),
190
- }));
191
- }
192
- catch (error) {
193
- this.logger.error(`Error while waiting for operation IDs: ${error}`);
194
- return transactionLinkers;
195
- }
196
- }
197
- async bridgeTokensToTON(signer, value, tonTarget, assets, tvmExecutorFee, tvmValidExecutors) {
198
- this.logger.debug('Bridging tokens to TON');
199
- if (assets == undefined) {
200
- assets = [];
201
- }
202
- const tonAssets = [...assets];
203
- if (value > 0n) {
204
- tonAssets.push(await (await assets_1.AssetFactory.from(this.config, {
205
- address: await this.config.nativeTACAddress(),
206
- tokenType: Struct_1.AssetType.FT,
207
- })).withAmount({ rawAmount: value }));
208
- }
209
- Validator_1.Validator.validateTVMAddress(tonTarget);
210
- if (tvmExecutorFee == undefined) {
211
- const suggestedTONExecutorFee = await this.simulator.getTVMExecutorFeeInfo(tonAssets, Consts_1.TAC_SYMBOL, tvmValidExecutors);
212
- this.logger.debug(`Suggested TON executor fee: ${(0, Utils_1.formatObjectForLogging)(suggestedTONExecutorFee)}`);
213
- tvmExecutorFee = BigInt(suggestedTONExecutorFee.inTAC);
214
- }
215
- const crossChainLayerAddress = await this.config.TACParams.crossChainLayer.getAddress();
216
- for (const asset of assets) {
217
- const evmAddress = await asset.getEVMAddress();
218
- if (asset.type == Struct_1.AssetType.FT) {
219
- this.logger.debug(`Approving token ${evmAddress} for ${crossChainLayerAddress}`);
220
- const tokenContract = this.config.artifacts.tac.wrappers.ERC20FactoryTAC.connect(evmAddress, this.config.TACParams.provider);
221
- const tx = await tokenContract.connect(signer).approve(crossChainLayerAddress, asset.rawAmount);
222
- await tx.wait();
223
- this.logger.debug(`Approved ${evmAddress} for ${crossChainLayerAddress}`);
224
- }
225
- if (asset.type == Struct_1.AssetType.NFT) {
226
- this.logger.debug(`Approving collection ${evmAddress} for ${crossChainLayerAddress}`);
227
- const tokenContract = this.config.artifacts.tac.wrappers.ERC721FactoryTAC.connect(evmAddress, this.config.TACParams.provider);
228
- const tx = await tokenContract
229
- .connect(signer)
230
- .approve(crossChainLayerAddress, asset.addresses.index);
231
- await tx.wait();
232
- this.logger.debug(`Approved ${asset.address} for ${crossChainLayerAddress}`);
233
- }
234
- }
235
- const shardsKey = BigInt(Math.round(Math.random() * 1e18));
236
- this.logger.debug(`Shards key: ${shardsKey}`);
237
- const protocolFee = await this.config.TACParams.crossChainLayer.getProtocolFee();
238
- this.logger.debug(`Protocol fee: ${protocolFee}`);
239
- const outMessage = {
240
- shardsKey: shardsKey,
241
- tvmTarget: tonTarget,
242
- tvmPayload: '',
243
- tvmProtocolFee: protocolFee,
244
- tvmExecutorFee: tvmExecutorFee,
245
- tvmValidExecutors: this.config.getTrustedTONExecutors,
246
- toBridge: await Promise.all(assets
247
- .filter((asset) => asset.type === Struct_1.AssetType.FT)
248
- .map(async (asset) => ({
249
- evmAddress: await asset.getEVMAddress(),
250
- amount: asset.rawAmount,
251
- }))),
252
- toBridgeNFT: await Promise.all(assets
253
- .filter((asset) => asset.type === Struct_1.AssetType.NFT)
254
- .map(async (asset) => ({
255
- evmAddress: await asset.getEVMAddress(),
256
- amount: 1n,
257
- tokenId: asset.addresses.index,
258
- }))),
259
- };
260
- const encodedOutMessage = this.config.artifacts.tac.utils.encodeOutMessageV1(outMessage);
261
- const outMsgVersion = 1n;
262
- const totalValue = value + BigInt(outMessage.tvmProtocolFee) + BigInt(outMessage.tvmExecutorFee);
263
- this.logger.debug(`Total value: ${totalValue}`);
264
- const tx = await this.config.TACParams.crossChainLayer
265
- .connect(signer)
266
- .sendMessage(outMsgVersion, encodedOutMessage, { value: totalValue });
267
- await tx.wait();
268
- this.logger.debug(`Transaction hash: ${tx.hash}`);
269
- return tx.hash;
270
- }
271
- }
272
- exports.TransactionManager = TransactionManager;