@tonappchain/sdk 0.7.2-scaled-ui-support-2 → 0.7.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.
Files changed (171) hide show
  1. package/LICENSE +20 -20
  2. package/README.md +198 -198
  3. package/dist/artifacts/dev/index.d.ts +2 -2
  4. package/dist/artifacts/dev/index.js +2 -1
  5. package/dist/artifacts/dev/tac/endpoints.d.ts +1 -0
  6. package/dist/artifacts/dev/tac/endpoints.js +2 -1
  7. package/dist/artifacts/dev/ton/internal/build/CrossChainLayer.compiled.json +1 -1
  8. package/dist/artifacts/dev/ton/internal/build/Executor.compiled.json +1 -1
  9. package/dist/artifacts/dev/ton/internal/build/JettonProxy.compiled.json +1 -1
  10. package/dist/artifacts/dev/ton/internal/build/JettonWallet.compiled.json +1 -1
  11. package/dist/artifacts/dev/ton/internal/build/NFTItem.compiled.json +1 -1
  12. package/dist/artifacts/dev/ton/internal/build/NFTProxy.compiled.json +1 -1
  13. package/dist/artifacts/dev/ton/internal/build/Settings.compiled.json +1 -1
  14. package/dist/artifacts/dev/ton/internal/wrappers/CrossChainLayer.d.ts +53 -6
  15. package/dist/artifacts/dev/ton/internal/wrappers/CrossChainLayer.js +130 -17
  16. package/dist/artifacts/dev/ton/internal/wrappers/JettonMinter.d.ts +2 -0
  17. package/dist/artifacts/dev/ton/internal/wrappers/JettonMinter.js +3 -1
  18. package/dist/artifacts/dev/ton/internal/wrappers/JettonProxy.d.ts +9 -0
  19. package/dist/artifacts/dev/ton/internal/wrappers/JettonProxy.js +10 -1
  20. package/dist/artifacts/dev/ton/internal/wrappers/JettonWallet.d.ts +7 -0
  21. package/dist/artifacts/dev/ton/internal/wrappers/JettonWallet.js +9 -2
  22. package/dist/artifacts/dev/ton/internal/wrappers/NFTCollection.d.ts +9 -0
  23. package/dist/artifacts/dev/ton/internal/wrappers/NFTCollection.js +9 -0
  24. package/dist/artifacts/dev/ton/internal/wrappers/NFTItem.d.ts +7 -0
  25. package/dist/artifacts/dev/ton/internal/wrappers/NFTItem.js +7 -0
  26. package/dist/artifacts/dev/ton/internal/wrappers/NFTProxy.d.ts +7 -0
  27. package/dist/artifacts/dev/ton/internal/wrappers/NFTProxy.js +8 -1
  28. package/dist/artifacts/dev/ton/internal/wrappers/Settings.d.ts +1 -0
  29. package/dist/artifacts/dev/ton/internal/wrappers/Settings.js +1 -0
  30. package/dist/artifacts/dev/ton/internal/wrappers/utils/CrossChainLayerPayload.d.ts +10 -0
  31. package/dist/artifacts/dev/ton/internal/wrappers/utils/CrossChainLayerPayload.js +24 -0
  32. package/dist/artifacts/dev/ton/internal/wrappers/utils/MerkleRoots.d.ts +2 -1
  33. package/dist/artifacts/dev/ton/internal/wrappers/utils/MerkleRoots.js +9 -1
  34. package/dist/artifacts/mainnet/index.d.ts +2 -2
  35. package/dist/artifacts/mainnet/index.js +2 -1
  36. package/dist/artifacts/mainnet/tac/endpoints.d.ts +1 -0
  37. package/dist/artifacts/mainnet/tac/endpoints.js +2 -1
  38. package/dist/artifacts/mainnet/ton/endpoints.d.ts +1 -1
  39. package/dist/artifacts/mainnet/ton/endpoints.js +1 -1
  40. package/dist/artifacts/mainnet/ton/internal/build/CrossChainLayer.compiled.json +1 -1
  41. package/dist/artifacts/mainnet/ton/internal/build/Executor.compiled.json +1 -1
  42. package/dist/artifacts/mainnet/ton/internal/build/JettonMinter.compiled.json +1 -1
  43. package/dist/artifacts/mainnet/ton/internal/build/JettonProxy.compiled.json +1 -1
  44. package/dist/artifacts/mainnet/ton/internal/build/JettonWallet.compiled.json +1 -1
  45. package/dist/artifacts/mainnet/ton/internal/build/NFTItem.compiled.json +1 -1
  46. package/dist/artifacts/mainnet/ton/internal/build/NFTProxy.compiled.json +1 -1
  47. package/dist/artifacts/mainnet/ton/internal/wrappers/CrossChainLayer.d.ts +1 -13
  48. package/dist/artifacts/mainnet/ton/internal/wrappers/CrossChainLayer.js +7 -45
  49. package/dist/artifacts/mainnet/ton/internal/wrappers/JettonMinter.d.ts +2 -2
  50. package/dist/artifacts/mainnet/ton/internal/wrappers/JettonMinter.js +2 -2
  51. package/dist/artifacts/testnet/index.d.ts +2 -2
  52. package/dist/artifacts/testnet/index.js +2 -1
  53. package/dist/artifacts/testnet/tac/endpoints.d.ts +1 -0
  54. package/dist/artifacts/testnet/tac/endpoints.js +2 -1
  55. package/dist/artifacts/testnet/ton/endpoints.d.ts +1 -1
  56. package/dist/artifacts/testnet/ton/endpoints.js +1 -1
  57. package/dist/artifacts/testnet/ton/internal/build/CrossChainLayer.compiled.json +1 -1
  58. package/dist/artifacts/testnet/ton/internal/build/Executor.compiled.json +1 -1
  59. package/dist/artifacts/testnet/ton/internal/build/JettonProxy.compiled.json +1 -1
  60. package/dist/artifacts/testnet/ton/internal/build/JettonWallet.compiled.json +1 -1
  61. package/dist/artifacts/testnet/ton/internal/build/NFTItem.compiled.json +1 -1
  62. package/dist/artifacts/testnet/ton/internal/build/NFTProxy.compiled.json +1 -1
  63. package/dist/artifacts/testnet/ton/internal/build/Settings.compiled.json +1 -1
  64. package/dist/artifacts/testnet/ton/internal/wrappers/CrossChainLayer.d.ts +53 -6
  65. package/dist/artifacts/testnet/ton/internal/wrappers/CrossChainLayer.js +130 -17
  66. package/dist/artifacts/testnet/ton/internal/wrappers/JettonMinter.d.ts +2 -0
  67. package/dist/artifacts/testnet/ton/internal/wrappers/JettonMinter.js +3 -1
  68. package/dist/artifacts/testnet/ton/internal/wrappers/JettonProxy.d.ts +9 -0
  69. package/dist/artifacts/testnet/ton/internal/wrappers/JettonProxy.js +10 -1
  70. package/dist/artifacts/testnet/ton/internal/wrappers/JettonWallet.d.ts +7 -0
  71. package/dist/artifacts/testnet/ton/internal/wrappers/JettonWallet.js +9 -2
  72. package/dist/artifacts/testnet/ton/internal/wrappers/NFTCollection.d.ts +9 -0
  73. package/dist/artifacts/testnet/ton/internal/wrappers/NFTCollection.js +9 -0
  74. package/dist/artifacts/testnet/ton/internal/wrappers/NFTItem.d.ts +7 -0
  75. package/dist/artifacts/testnet/ton/internal/wrappers/NFTItem.js +7 -0
  76. package/dist/artifacts/testnet/ton/internal/wrappers/NFTProxy.d.ts +7 -0
  77. package/dist/artifacts/testnet/ton/internal/wrappers/NFTProxy.js +8 -1
  78. package/dist/artifacts/testnet/ton/internal/wrappers/Settings.d.ts +1 -0
  79. package/dist/artifacts/testnet/ton/internal/wrappers/Settings.js +1 -0
  80. package/dist/artifacts/testnet/ton/internal/wrappers/utils/CrossChainLayerPayload.d.ts +10 -0
  81. package/dist/artifacts/testnet/ton/internal/wrappers/utils/CrossChainLayerPayload.js +24 -0
  82. package/dist/artifacts/testnet/ton/internal/wrappers/utils/MerkleRoots.d.ts +2 -1
  83. package/dist/artifacts/testnet/ton/internal/wrappers/utils/MerkleRoots.js +9 -1
  84. package/dist/src/adapters/BaseContractOpener.d.ts +76 -0
  85. package/dist/src/adapters/BaseContractOpener.js +440 -0
  86. package/dist/src/adapters/LiteClientOpener.d.ts +38 -0
  87. package/dist/src/adapters/LiteClientOpener.js +141 -0
  88. package/dist/src/adapters/OpenerUtils.d.ts +3 -0
  89. package/dist/src/adapters/OpenerUtils.js +40 -0
  90. package/dist/src/adapters/RetryableContractOpener.d.ts +40 -0
  91. package/dist/src/adapters/RetryableContractOpener.js +290 -0
  92. package/dist/src/adapters/SandboxOpener.d.ts +15 -0
  93. package/dist/src/adapters/SandboxOpener.js +35 -0
  94. package/dist/src/adapters/TonClient4Opener.d.ts +24 -0
  95. package/dist/src/adapters/TonClient4Opener.js +95 -0
  96. package/dist/src/adapters/TonClientOpener.d.ts +19 -0
  97. package/dist/src/adapters/TonClientOpener.js +82 -0
  98. package/dist/src/adapters/index.d.ts +7 -2
  99. package/dist/src/adapters/index.js +7 -2
  100. package/dist/src/assets/AssetCache.d.ts +8 -8
  101. package/dist/src/assets/AssetCache.js +3 -0
  102. package/dist/src/assets/AssetFactory.js +8 -2
  103. package/dist/src/assets/FT.d.ts +2 -3
  104. package/dist/src/assets/FT.js +4 -7
  105. package/dist/src/assets/NFT.d.ts +1 -1
  106. package/dist/src/assets/NFT.js +1 -1
  107. package/dist/src/assets/TON.d.ts +3 -2
  108. package/dist/src/assets/TON.js +2 -1
  109. package/dist/src/errors/errors.d.ts +12 -1
  110. package/dist/src/errors/errors.js +66 -2
  111. package/dist/src/errors/index.d.ts +2 -2
  112. package/dist/src/errors/index.js +4 -1
  113. package/dist/src/errors/instances.d.ts +7 -2
  114. package/dist/src/errors/instances.js +67 -2
  115. package/dist/src/index.d.ts +3 -1
  116. package/dist/src/index.js +6 -4
  117. package/dist/src/interfaces/Asset.d.ts +4 -9
  118. package/dist/src/interfaces/ContractOpener.d.ts +76 -2
  119. package/dist/src/interfaces/IOperationTracker.d.ts +22 -22
  120. package/dist/src/interfaces/ISimulator.d.ts +9 -1
  121. package/dist/src/interfaces/ITONTransactionManager.d.ts +20 -1
  122. package/dist/src/interfaces/ITacExplorerClient.d.ts +8 -0
  123. package/dist/src/interfaces/ITacExplorerClient.js +2 -0
  124. package/dist/src/interfaces/ITacSDK.d.ts +25 -1
  125. package/dist/src/interfaces/ITxFinalizer.d.ts +4 -0
  126. package/dist/src/interfaces/ITxFinalizer.js +2 -0
  127. package/dist/src/interfaces/WalletInstanse.d.ts +4 -8
  128. package/dist/src/interfaces/index.d.ts +1 -0
  129. package/dist/src/interfaces/index.js +1 -0
  130. package/dist/src/sdk/Configuration.d.ts +5 -3
  131. package/dist/src/sdk/Configuration.js +54 -7
  132. package/dist/src/sdk/Consts.d.ts +18 -1
  133. package/dist/src/sdk/Consts.js +21 -2
  134. package/dist/src/sdk/Fees.d.ts +21 -0
  135. package/dist/src/sdk/Fees.js +201 -0
  136. package/dist/src/sdk/LiteSequencerClient.d.ts +1 -0
  137. package/dist/src/sdk/LiteSequencerClient.js +39 -17
  138. package/dist/src/sdk/OperationTracker.d.ts +11 -11
  139. package/dist/src/sdk/OperationTracker.js +46 -94
  140. package/dist/src/sdk/Simulator.d.ts +10 -2
  141. package/dist/src/sdk/Simulator.js +102 -0
  142. package/dist/src/sdk/StartTracking.d.ts +12 -7
  143. package/dist/src/sdk/StartTracking.js +75 -49
  144. package/dist/src/sdk/TONTransactionManager.d.ts +5 -4
  145. package/dist/src/sdk/TONTransactionManager.js +63 -8
  146. package/dist/src/sdk/TacExplorerClient.d.ts +8 -0
  147. package/dist/src/sdk/TacExplorerClient.js +22 -0
  148. package/dist/src/sdk/TacSdk.d.ts +8 -2
  149. package/dist/src/sdk/TacSdk.js +27 -4
  150. package/dist/src/sdk/TxFinalizer.d.ts +4 -3
  151. package/dist/src/sdk/TxFinalizer.js +41 -41
  152. package/dist/src/sdk/Utils.d.ts +20 -1
  153. package/dist/src/sdk/Utils.js +158 -10
  154. package/dist/src/sender/BatchSender.js +19 -0
  155. package/dist/src/sender/MockSender.d.ts +2 -0
  156. package/dist/src/sender/MockSender.js +13 -0
  157. package/dist/src/sender/RawSender.js +34 -1
  158. package/dist/src/sender/SenderFactory.js +1 -1
  159. package/dist/src/sender/TonConnectSender.js +2 -0
  160. package/dist/src/sender/index.d.ts +1 -0
  161. package/dist/src/sender/index.js +1 -0
  162. package/dist/src/structs/InternalStruct.d.ts +98 -4
  163. package/dist/src/structs/Struct.d.ts +183 -7
  164. package/dist/src/structs/Struct.js +4 -3
  165. package/dist/src/wrappers/HighloadWalletV3.d.ts +5 -3
  166. package/dist/src/wrappers/HighloadWalletV3.js +14 -3
  167. package/package.json +121 -117
  168. package/dist/src/adapters/contractOpener.d.ts +0 -20
  169. package/dist/src/adapters/contractOpener.js +0 -126
  170. package/dist/src/adapters/retryableContractOpener.d.ts +0 -24
  171. package/dist/src/adapters/retryableContractOpener.js +0 -111
@@ -1,4 +1,5 @@
1
1
  import { Address, Cell, Contract, ContractProvider, Sender } from '@ton/core';
2
+ import { StorageStats } from './utils/GasUtils';
2
3
  export declare const NFTItemTransferOperation = 2332633442;
3
4
  export declare const NFTProxyOpCodes: {
4
5
  admin_changeAdmin: number;
@@ -32,6 +33,12 @@ export declare class NFTProxy implements Contract {
32
33
  code: Cell;
33
34
  data: Cell;
34
35
  } | undefined;
36
+ static estimatedNftItemCells: bigint;
37
+ static estimatedNftItemBits: bigint;
38
+ static storageStats: StorageStats;
39
+ static ownershipAssignedGasConsumption: bigint;
40
+ static errorNotificationGasConsumption: bigint;
41
+ static msgToTvmGasConsumption: bigint;
35
42
  constructor(address: Address, init?: {
36
43
  code: Cell;
37
44
  data: Cell;
@@ -4,10 +4,11 @@ exports.NFTProxy = exports.NFTProxyErrors = exports.NFTProxyOpCodes = exports.NF
4
4
  exports.nftProxyConfigToCell = nftProxyConfigToCell;
5
5
  const core_1 = require("@ton/core");
6
6
  const Constants_1 = require("./Constants");
7
+ const GasUtils_1 = require("./utils/GasUtils");
7
8
  exports.NFTItemTransferOperation = 0x8b092962;
8
9
  exports.NFTProxyOpCodes = {
9
10
  admin_changeAdmin: 0x581879bc,
10
- admin_updateCode: 0x20faec53,
11
+ admin_updateCode: 0x6e7145f9,
11
12
  ccl_evmMsgToTVMProxy: 0x7817b330,
12
13
  ccl_errorNotification: 0xae7df95b,
13
14
  ccl_tvmMsgToEVM: 0x6c582059,
@@ -155,3 +156,9 @@ class NFTProxy {
155
156
  }
156
157
  }
157
158
  exports.NFTProxy = NFTProxy;
159
+ NFTProxy.estimatedNftItemCells = 25n;
160
+ NFTProxy.estimatedNftItemBits = 9877n;
161
+ NFTProxy.storageStats = new GasUtils_1.StorageStats(7512n, 15n);
162
+ NFTProxy.ownershipAssignedGasConsumption = 7688n;
163
+ NFTProxy.errorNotificationGasConsumption = 4737n;
164
+ NFTProxy.msgToTvmGasConsumption = 5348n;
@@ -52,6 +52,7 @@ export declare class Settings implements Contract {
52
52
  data: Cell;
53
53
  } | undefined;
54
54
  readonly configuration?: SettingsConfig | undefined;
55
+ static storageStats: StorageStats;
55
56
  constructor(address: Address, init?: {
56
57
  code: Cell;
57
58
  data: Cell;
@@ -148,5 +148,6 @@ class Settings {
148
148
  }
149
149
  }
150
150
  exports.Settings = Settings;
151
+ Settings.storageStats = new GasUtils_1.StorageStats(38743n, 118n);
151
152
  Settings.minStorageDuration = 10 * 365 * 24 * 3600; // 10 years
152
153
  Settings.minStorageStats = new GasUtils_1.StorageStats(29557n, 104n);
@@ -0,0 +1,10 @@
1
+ import { Address, Cell } from '@ton/core';
2
+ export type CrossChainLayerPayload = {
3
+ operationId: bigint;
4
+ destinationAddress: Address;
5
+ destinationMsgValue: bigint;
6
+ payload: Cell;
7
+ maybeStateInit?: Cell;
8
+ };
9
+ export declare function CrossChainLayerPayloadToCell(payload: CrossChainLayerPayload): Cell;
10
+ export declare function CrossChainLayerPayloadFromCell(cell: Cell): CrossChainLayerPayload;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CrossChainLayerPayloadToCell = CrossChainLayerPayloadToCell;
4
+ exports.CrossChainLayerPayloadFromCell = CrossChainLayerPayloadFromCell;
5
+ const core_1 = require("@ton/core");
6
+ function CrossChainLayerPayloadToCell(payload) {
7
+ return (0, core_1.beginCell)()
8
+ .storeUint(payload.operationId, 256)
9
+ .storeAddress(payload.destinationAddress)
10
+ .storeCoins(payload.destinationMsgValue)
11
+ .storeRef(payload.payload)
12
+ .storeMaybeRef(payload.maybeStateInit)
13
+ .endCell();
14
+ }
15
+ function CrossChainLayerPayloadFromCell(cell) {
16
+ const slice = cell.beginParse();
17
+ return {
18
+ operationId: slice.loadUintBig(256),
19
+ destinationAddress: slice.loadAddress(),
20
+ destinationMsgValue: slice.loadCoins(),
21
+ payload: slice.loadRef(),
22
+ maybeStateInit: slice.loadMaybeRef() ?? undefined,
23
+ };
24
+ }
@@ -4,4 +4,5 @@ export type MerkleRoot = {
4
4
  validTimestamp: number;
5
5
  };
6
6
  export declare function cellToArray(addrDict: Cell | null): Array<MerkleRoot>;
7
- export declare function arrayToCell(arr: Array<MerkleRoot>): Dictionary<bigint, number>;
7
+ export declare function arrayToDict(arr: Array<MerkleRoot>): Dictionary<bigint, number>;
8
+ export declare function arrayToCell(arr: Array<MerkleRoot>): Cell;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.cellToArray = cellToArray;
4
+ exports.arrayToDict = arrayToDict;
4
5
  exports.arrayToCell = arrayToCell;
5
6
  const core_1 = require("@ton/core");
6
7
  const Constants_1 = require("../Constants");
@@ -18,10 +19,17 @@ function cellToArray(addrDict) {
18
19
  }
19
20
  return resArr;
20
21
  }
21
- function arrayToCell(arr) {
22
+ function arrayToDict(arr) {
22
23
  let dict = core_1.Dictionary.empty(core_1.Dictionary.Keys.BigUint(Constants_1.Params.bitsize.hash), core_1.Dictionary.Values.Uint(Constants_1.Params.bitsize.time));
23
24
  for (let i = 0; i < arr.length; i++) {
24
25
  dict.set(arr[i].root, arr[i].validTimestamp);
25
26
  }
26
27
  return dict;
27
28
  }
29
+ function arrayToCell(arr) {
30
+ let dict = core_1.Dictionary.empty(core_1.Dictionary.Keys.BigUint(Constants_1.Params.bitsize.hash), core_1.Dictionary.Values.Uint(Constants_1.Params.bitsize.time));
31
+ for (let i = 0; i < arr.length; i++) {
32
+ dict.set(arr[i].root, arr[i].validTimestamp);
33
+ }
34
+ return (0, core_1.beginCell)().storeDictDirect(dict).endCell();
35
+ }
@@ -0,0 +1,76 @@
1
+ import { SandboxContract } from '@ton/sandbox';
2
+ import { Address, Contract, OpenedContract, Transaction } from '@ton/ton';
3
+ import { ContractOpener, ILogger } from '../interfaces';
4
+ import { AddressInformation, GetTransactionsOptions } from '../structs/Struct';
5
+ import { ContractState, TrackTransactionTreeParams, TrackTransactionTreeResult } from '../structs/Struct';
6
+ /**
7
+ * Base class for ContractOpener implementations with common functionality
8
+ */
9
+ export declare abstract class BaseContractOpener implements ContractOpener {
10
+ protected logger?: ILogger;
11
+ protected constructor(logger?: ILogger);
12
+ setLogger(logger: ILogger): void;
13
+ abstract open<T extends Contract>(contract: T): OpenedContract<T> | SandboxContract<T>;
14
+ abstract getContractState(address: Address): Promise<ContractState>;
15
+ abstract getTransactions(address: Address, opts: GetTransactionsOptions): Promise<Transaction[]>;
16
+ abstract getAddressInformation(address: Address): Promise<AddressInformation>;
17
+ abstract getConfig(): Promise<string>;
18
+ closeConnections?(): void;
19
+ /**
20
+ * Common pagination logic for scanning transaction history
21
+ * @param addr Account address
22
+ * @param opts Search options
23
+ * @param predicate Function to check if transaction matches search criteria
24
+ * @returns Found transaction or null
25
+ */
26
+ private scanTransactionHistory;
27
+ /**
28
+ * Find transaction by hash with pagination through account history
29
+ * @param addr Account address
30
+ * @param hash Transaction hash in any format (base64, hex)
31
+ * @param opts Search options
32
+ */
33
+ getTransactionByHash(addr: Address, hash: string, opts?: GetTransactionsOptions): Promise<Transaction | null>;
34
+ /**
35
+ * Find transaction by its transaction hash only.
36
+ * More efficient than getTransactionByHash when you know it's a transaction hash.
37
+ */
38
+ getTransactionByTxHash(addr: Address, txHash: string, opts?: GetTransactionsOptions): Promise<Transaction | null>;
39
+ /**
40
+ * Find transaction by its incoming message hash.
41
+ * Useful for finding the transaction that processed a specific message.
42
+ */
43
+ getTransactionByInMsgHash(addr: Address, msgHash: string, opts?: GetTransactionsOptions): Promise<Transaction | null>;
44
+ /**
45
+ * Find transaction by its outgoing message hash.
46
+ * Useful for finding the parent transaction that sent a specific message.
47
+ */
48
+ getTransactionByOutMsgHash(addr: Address, msgHash: string, opts?: GetTransactionsOptions): Promise<Transaction | null>;
49
+ /**
50
+ * Get adjacent transactions (children and parent)
51
+ * @param addr Account address
52
+ * @param hash Transaction hash in any format (base64, hex)
53
+ * @param opts Search options
54
+ */
55
+ getAdjacentTransactions(addr: Address, hash: string, opts?: GetTransactionsOptions): Promise<Transaction[]>;
56
+ /**
57
+ * Validate transaction phases and return error details
58
+ */
59
+ private validateTransactionWithResult;
60
+ /**
61
+ * Find transaction by hash type
62
+ */
63
+ private findTransactionByHashType;
64
+ /**
65
+ * Find transaction with retry logic
66
+ */
67
+ private findTransactionWithRetry;
68
+ /**
69
+ * Track transaction tree and validate all transactions
70
+ */
71
+ trackTransactionTree(address: string, hash: string, params?: TrackTransactionTreeParams): Promise<void>;
72
+ /**
73
+ * Track transaction tree and validate all transactions (returns result instead of throwing)
74
+ */
75
+ trackTransactionTreeWithResult(address: string, hash: string, params?: TrackTransactionTreeParams): Promise<TrackTransactionTreeResult>;
76
+ }
@@ -0,0 +1,440 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BaseContractOpener = void 0;
4
+ const ton_1 = require("@ton/ton");
5
+ const errors_1 = require("../errors");
6
+ const Consts_1 = require("../sdk/Consts");
7
+ const Utils_1 = require("../sdk/Utils");
8
+ /**
9
+ * Base class for ContractOpener implementations with common functionality
10
+ */
11
+ class BaseContractOpener {
12
+ constructor(logger) {
13
+ this.logger = logger;
14
+ }
15
+ setLogger(logger) {
16
+ if (!this.logger) {
17
+ this.logger = logger;
18
+ }
19
+ }
20
+ /**
21
+ * Common pagination logic for scanning transaction history
22
+ * @param addr Account address
23
+ * @param opts Search options
24
+ * @param predicate Function to check if transaction matches search criteria
25
+ * @returns Found transaction or null
26
+ */
27
+ async scanTransactionHistory(addr, opts, predicate) {
28
+ const limit = opts?.limit ?? Consts_1.DEFAULT_FIND_TX_LIMIT;
29
+ const inclusive = opts?.inclusive ?? true;
30
+ const toLt = opts?.to_lt ? BigInt(opts.to_lt) : undefined;
31
+ let currentLt = opts?.lt;
32
+ let currentHash = opts?.hash ? (0, Utils_1.normalizeHashToBase64)(opts.hash) : undefined;
33
+ const seenCursors = new Set();
34
+ let scannedTransactions = 0;
35
+ const maxScannedTransactions = opts?.maxScannedTransactions ?? Consts_1.DEFAULT_MAX_SCANNED_TRANSACTIONS;
36
+ while (true) {
37
+ const list = await this.getTransactions(addr, {
38
+ limit,
39
+ lt: currentLt,
40
+ hash: currentHash,
41
+ to_lt: opts?.to_lt,
42
+ inclusive,
43
+ archival: opts?.archival ?? Consts_1.DEFAULT_FIND_TX_ARCHIVAL,
44
+ timeoutMs: opts?.timeoutMs,
45
+ retryDelayMs: opts?.retryDelayMs,
46
+ });
47
+ if (list.length === 0) {
48
+ break;
49
+ }
50
+ let startIndex = 0;
51
+ const firstTx = list[0];
52
+ const firstTxMatchesCursor = currentLt &&
53
+ currentHash &&
54
+ firstTx.lt.toString() === currentLt &&
55
+ firstTx.hash().toString('base64') === currentHash;
56
+ if (firstTxMatchesCursor) {
57
+ startIndex = 1;
58
+ if (list.length === 1) {
59
+ if (firstTx.prevTransactionLt === 0n) {
60
+ break;
61
+ }
62
+ const nextLt = firstTx.prevTransactionLt.toString();
63
+ const nextHash = Buffer.from(firstTx.prevTransactionHash.toString(16).padStart(64, '0'), 'hex').toString('base64');
64
+ if (currentLt && BigInt(nextLt) >= BigInt(currentLt)) {
65
+ break;
66
+ }
67
+ const cursorKey = `${nextLt}:${nextHash}`;
68
+ if (seenCursors.has(cursorKey)) {
69
+ break;
70
+ }
71
+ seenCursors.add(cursorKey);
72
+ currentLt = nextLt;
73
+ currentHash = nextHash;
74
+ continue;
75
+ }
76
+ }
77
+ for (let i = startIndex; i < list.length; i++) {
78
+ const tx = list[i];
79
+ scannedTransactions += 1;
80
+ if (scannedTransactions > maxScannedTransactions) {
81
+ this.logger?.debug(`Scan limit reached (${maxScannedTransactions} transactions), stopping history scan`);
82
+ return null;
83
+ }
84
+ if (predicate(tx)) {
85
+ return tx;
86
+ }
87
+ }
88
+ const oldestTx = list[list.length - 1];
89
+ if (oldestTx.prevTransactionLt === 0n)
90
+ break;
91
+ if (toLt !== undefined) {
92
+ if (inclusive ? oldestTx.lt <= toLt : oldestTx.lt < toLt)
93
+ break;
94
+ }
95
+ const nextLt = oldestTx.lt.toString();
96
+ const nextHash = oldestTx.hash().toString('base64');
97
+ if (currentLt && BigInt(nextLt) >= BigInt(currentLt)) {
98
+ break;
99
+ }
100
+ const cursorKey = `${nextLt}:${nextHash}`;
101
+ if (seenCursors.has(cursorKey)) {
102
+ break;
103
+ }
104
+ seenCursors.add(cursorKey);
105
+ currentLt = nextLt;
106
+ currentHash = nextHash;
107
+ }
108
+ return null;
109
+ }
110
+ /**
111
+ * Find transaction by hash with pagination through account history
112
+ * @param addr Account address
113
+ * @param hash Transaction hash in any format (base64, hex)
114
+ * @param opts Search options
115
+ */
116
+ async getTransactionByHash(addr, hash, opts) {
117
+ const targetHashB64 = (0, Utils_1.normalizeHashToBase64)(hash);
118
+ return this.scanTransactionHistory(addr, opts, (tx) => {
119
+ // 1. check tx itself
120
+ if (tx.hash().toString('base64') === targetHashB64) {
121
+ return true;
122
+ }
123
+ // 2. check incoming message(external-in)
124
+ if (tx.inMessage && tx.inMessage.info.type === 'external-in') {
125
+ const msgHash = (0, Utils_1.getNormalizedExtMessageHash)(tx.inMessage);
126
+ if (msgHash === targetHashB64) {
127
+ return true;
128
+ }
129
+ const rawMsgHash = (0, ton_1.beginCell)().store((0, ton_1.storeMessage)(tx.inMessage)).endCell().hash().toString('base64');
130
+ if (rawMsgHash === targetHashB64) {
131
+ return true;
132
+ }
133
+ }
134
+ // 3. check incoming message(internal)
135
+ if (tx.inMessage && tx.inMessage.info.type === 'internal') {
136
+ const messageCell = (0, ton_1.beginCell)().store((0, ton_1.storeMessage)(tx.inMessage)).endCell();
137
+ const msgHash = messageCell.hash();
138
+ if (msgHash.toString('base64') === targetHashB64) {
139
+ return true;
140
+ }
141
+ }
142
+ // 4. check outcoming message
143
+ for (const outMsg of tx.outMessages.values()) {
144
+ const messageCell = (0, ton_1.beginCell)().store((0, ton_1.storeMessage)(outMsg)).endCell();
145
+ const hash = messageCell.hash();
146
+ if (hash.toString('base64') === targetHashB64) {
147
+ return true;
148
+ }
149
+ }
150
+ return false;
151
+ });
152
+ }
153
+ /**
154
+ * Find transaction by its transaction hash only.
155
+ * More efficient than getTransactionByHash when you know it's a transaction hash.
156
+ */
157
+ async getTransactionByTxHash(addr, txHash, opts) {
158
+ const targetHashB64 = (0, Utils_1.normalizeHashToBase64)(txHash);
159
+ return this.scanTransactionHistory(addr, opts, (tx) => {
160
+ return tx.hash().toString('base64') === targetHashB64;
161
+ });
162
+ }
163
+ /**
164
+ * Find transaction by its incoming message hash.
165
+ * Useful for finding the transaction that processed a specific message.
166
+ */
167
+ async getTransactionByInMsgHash(addr, msgHash, opts) {
168
+ const targetHashB64 = (0, Utils_1.normalizeHashToBase64)(msgHash);
169
+ return this.scanTransactionHistory(addr, opts, (tx) => {
170
+ // Check incoming message(external-in) - uses normalized hash
171
+ if (tx.inMessage && tx.inMessage.info.type === 'external-in') {
172
+ const hash = (0, Utils_1.getNormalizedExtMessageHash)(tx.inMessage);
173
+ if (hash === targetHashB64) {
174
+ return true;
175
+ }
176
+ const rawHash = (0, ton_1.beginCell)().store((0, ton_1.storeMessage)(tx.inMessage)).endCell().hash().toString('base64');
177
+ if (rawHash === targetHashB64) {
178
+ return true;
179
+ }
180
+ }
181
+ // Check incoming message(internal) - uses full message cell hash
182
+ if (tx.inMessage && tx.inMessage.info.type === 'internal') {
183
+ const messageCell = (0, ton_1.beginCell)().store((0, ton_1.storeMessage)(tx.inMessage)).endCell();
184
+ const hash = messageCell.hash();
185
+ if (hash.toString('base64') === targetHashB64) {
186
+ return true;
187
+ }
188
+ }
189
+ return false;
190
+ });
191
+ }
192
+ /**
193
+ * Find transaction by its outgoing message hash.
194
+ * Useful for finding the parent transaction that sent a specific message.
195
+ */
196
+ async getTransactionByOutMsgHash(addr, msgHash, opts) {
197
+ const targetHashB64 = (0, Utils_1.normalizeHashToBase64)(msgHash);
198
+ return this.scanTransactionHistory(addr, opts, (tx) => {
199
+ for (const outMsg of tx.outMessages.values()) {
200
+ const messageCell = (0, ton_1.beginCell)().store((0, ton_1.storeMessage)(outMsg)).endCell();
201
+ const hash = messageCell.hash();
202
+ if (hash.toString('base64') === targetHashB64) {
203
+ return true;
204
+ }
205
+ }
206
+ return false;
207
+ });
208
+ }
209
+ /**
210
+ * Get adjacent transactions (children and parent)
211
+ * @param addr Account address
212
+ * @param hash Transaction hash in any format (base64, hex)
213
+ * @param opts Search options
214
+ */
215
+ async getAdjacentTransactions(addr, hash, opts) {
216
+ // 1. Find the root transaction (hash will be normalized inside getTransactionByHash)
217
+ const rootTx = await this.getTransactionByHash(addr, hash, opts);
218
+ if (!rootTx)
219
+ return [];
220
+ const adjacent = [];
221
+ // 2. Follow every outgoing message to find child transactions
222
+ for (const msg of rootTx.outMessages.values()) {
223
+ const dst = msg.info.dest;
224
+ if (!dst || dst instanceof ton_1.ExternalAddress)
225
+ continue;
226
+ const msgHashB64 = (0, ton_1.beginCell)().store((0, ton_1.storeMessage)(msg)).endCell().hash().toString('base64');
227
+ // The outgoing message becomes an incoming message at the destination
228
+ const tx = await this.getTransactionByInMsgHash(dst, msgHashB64, opts);
229
+ if (tx)
230
+ adjacent.push(tx);
231
+ }
232
+ // 3. Optional: follow the incoming message to find parent transaction
233
+ if (rootTx.inMessage?.info.type === 'internal') {
234
+ const msgHashB64 = (0, ton_1.beginCell)().store((0, ton_1.storeMessage)(rootTx.inMessage)).endCell().hash().toString('base64');
235
+ // The incoming message was an outgoing message at the source
236
+ const tx = await this.getTransactionByOutMsgHash(rootTx.inMessage.info.src, msgHashB64, opts);
237
+ if (tx)
238
+ adjacent.push(tx);
239
+ }
240
+ return adjacent;
241
+ }
242
+ /**
243
+ * Validate transaction phases and return error details
244
+ */
245
+ validateTransactionWithResult(tx, ignoreOpcodeList) {
246
+ if (tx.description.type !== 'generic')
247
+ return null;
248
+ const { aborted, computePhase, actionPhase } = tx.description;
249
+ const txHash = tx.hash().toString('base64');
250
+ const exitCode = computePhase && computePhase.type !== 'skipped' ? computePhase.exitCode : 'N/A';
251
+ const resultCode = actionPhase ? actionPhase.resultCode : 'N/A';
252
+ if (aborted) {
253
+ return { txHash, exitCode, resultCode, reason: 'aborted' };
254
+ }
255
+ if (!computePhase) {
256
+ return { txHash, exitCode, resultCode, reason: 'compute_phase_missing' };
257
+ }
258
+ if (computePhase.type !== 'skipped' && (!computePhase.success || computePhase.exitCode !== 0)) {
259
+ return { txHash, exitCode, resultCode, reason: 'compute_phase_failed' };
260
+ }
261
+ if (actionPhase && (!actionPhase.success || actionPhase.resultCode !== 0)) {
262
+ return { txHash, exitCode, resultCode, reason: 'action_phase_failed' };
263
+ }
264
+ if (!tx.inMessage)
265
+ return null;
266
+ // Log optional skip hints (does not bypass phase validation)
267
+ if (tx.inMessage.info.type === 'internal' && tx.inMessage.info.value.coins === Consts_1.IGNORE_MSG_VALUE_1_NANO) {
268
+ this.logger?.debug(`Skipping extra checks for tx: ${txHash} (1 nano message)`);
269
+ return null;
270
+ }
271
+ const bodySlice = tx.inMessage.body.beginParse();
272
+ if (bodySlice.remainingBits >= 32) {
273
+ const opcode = bodySlice.loadUint(32);
274
+ if (ignoreOpcodeList.includes(opcode)) {
275
+ this.logger?.debug(`Skipping extra checks for tx: ${txHash} (opcode in ignore list)`);
276
+ }
277
+ }
278
+ return null;
279
+ }
280
+ /**
281
+ * Find transaction by hash type
282
+ */
283
+ async findTransactionByHashType(address, hash, hashType, opts) {
284
+ const searchOpts = { archival: true, ...opts };
285
+ if (hashType === 'in') {
286
+ return this.getTransactionByInMsgHash(address, hash, searchOpts);
287
+ }
288
+ else if (hashType === 'out') {
289
+ return this.getTransactionByOutMsgHash(address, hash, searchOpts);
290
+ }
291
+ else {
292
+ return this.getTransactionByHash(address, hash, searchOpts);
293
+ }
294
+ }
295
+ /**
296
+ * Find transaction with retry logic
297
+ */
298
+ async findTransactionWithRetry(address, hash, hashType, opts, depth) {
299
+ const retryDelayMs = opts.retryDelayMs ?? Consts_1.DEFAULT_RETRY_ON_NOT_FOUND_DELAY_MS;
300
+ const maxRetries = opts.retries ?? Consts_1.DEFAULT_RETRY_ON_NOT_FOUND_RETRIES;
301
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
302
+ let errorMsg;
303
+ try {
304
+ const tx = await this.findTransactionByHashType(address, hash, hashType, opts);
305
+ if (tx) {
306
+ return tx;
307
+ }
308
+ }
309
+ catch (error) {
310
+ errorMsg = error instanceof Error ? error.message : String(error);
311
+ }
312
+ const isLastAttempt = attempt >= maxRetries;
313
+ const reason = errorMsg ?? 'not found';
314
+ const retryInfo = isLastAttempt ? '' : `, retrying in ${retryDelayMs}ms`;
315
+ this.logger?.debug(`Transaction not found at depth ${depth} (attempt ${attempt + 1}/${maxRetries + 1}): ${reason}${retryInfo}`);
316
+ if (isLastAttempt) {
317
+ return null;
318
+ }
319
+ await (0, Utils_1.sleep)(retryDelayMs);
320
+ }
321
+ return null;
322
+ }
323
+ /**
324
+ * Track transaction tree and validate all transactions
325
+ */
326
+ async trackTransactionTree(address, hash, params = {
327
+ maxDepth: Consts_1.DEFAULT_FIND_TX_MAX_DEPTH,
328
+ ignoreOpcodeList: Consts_1.IGNORE_OPCODE,
329
+ limit: Consts_1.DEFAULT_FIND_TX_LIMIT,
330
+ direction: 'both',
331
+ retryOnNotFound: Consts_1.DEFAULT_RETRY_ON_NOT_FOUND,
332
+ }) {
333
+ const result = await this.trackTransactionTreeWithResult(address, hash, params);
334
+ if (this.logger && typeof result.checkedCount === 'number') {
335
+ this.logger.debug(`Transaction tree checked: ${result.checkedCount} unique transaction(s)`);
336
+ }
337
+ if (!result.success && result.error) {
338
+ const { txHash, exitCode, resultCode, reason, address: errorAddress, hashType } = result.error;
339
+ const context = reason === 'not_found' ? ` address=${errorAddress ?? 'unknown'} hashType=${hashType ?? 'unknown'}` : '';
340
+ const message = `${txHash}: reason=${reason} (exitCode=${exitCode}, resultCode=${resultCode})${context}`;
341
+ if (reason === 'not_found') {
342
+ throw new Error(message);
343
+ }
344
+ else {
345
+ throw (0, errors_1.txFinalizationError)(message);
346
+ }
347
+ }
348
+ }
349
+ /**
350
+ * Track transaction tree and validate all transactions (returns result instead of throwing)
351
+ */
352
+ async trackTransactionTreeWithResult(address, hash, params = {
353
+ maxDepth: Consts_1.DEFAULT_FIND_TX_MAX_DEPTH,
354
+ ignoreOpcodeList: Consts_1.IGNORE_OPCODE,
355
+ limit: Consts_1.DEFAULT_FIND_TX_LIMIT,
356
+ direction: 'both',
357
+ retryOnNotFound: Consts_1.DEFAULT_RETRY_ON_NOT_FOUND,
358
+ }) {
359
+ const { maxDepth = Consts_1.DEFAULT_FIND_TX_MAX_DEPTH, ignoreOpcodeList = Consts_1.IGNORE_OPCODE, limit = Consts_1.DEFAULT_FIND_TX_LIMIT, maxScannedTransactions = Consts_1.DEFAULT_MAX_SCANNED_TRANSACTIONS, direction = 'both', retryOnNotFound = Consts_1.DEFAULT_RETRY_ON_NOT_FOUND, retryDelayMs, retries, } = params;
360
+ const parsedAddress = ton_1.Address.parse(address);
361
+ const normalizedRootHash = (0, Utils_1.normalizeHashToBase64)(hash);
362
+ const visitedSearchKeys = new Set();
363
+ const processedTxHashes = new Set();
364
+ let checkedCount = 0;
365
+ const searchOpts = {
366
+ limit,
367
+ archival: true,
368
+ maxScannedTransactions,
369
+ retryDelayMs,
370
+ retries,
371
+ };
372
+ const queue = [
373
+ { address: parsedAddress, hash: normalizedRootHash, depth: 0, hashType: 'unknown' },
374
+ ];
375
+ while (queue.length > 0) {
376
+ const { hash: currentHash, depth: currentDepth, address: currentAddress, hashType } = queue.shift();
377
+ const visitedKey = `${currentAddress.toString()}:${currentHash}:${hashType}`;
378
+ if (visitedSearchKeys.has(visitedKey))
379
+ continue;
380
+ visitedSearchKeys.add(visitedKey);
381
+ const tx = retryOnNotFound
382
+ ? await this.findTransactionWithRetry(currentAddress, currentHash, hashType, searchOpts, currentDepth)
383
+ : await this.findTransactionByHashType(currentAddress, currentHash, hashType, searchOpts);
384
+ if (!tx) {
385
+ this.logger?.debug(`Transaction not found for hash: ${currentHash} (address=${currentAddress?.toString()}, hashType=${hashType ?? 'unknown'})`);
386
+ return {
387
+ success: false,
388
+ checkedCount,
389
+ error: {
390
+ txHash: currentHash,
391
+ exitCode: 'N/A',
392
+ resultCode: 'N/A',
393
+ reason: 'not_found',
394
+ address: currentAddress?.toString(),
395
+ hashType: hashType ?? 'unknown',
396
+ },
397
+ };
398
+ }
399
+ const txHash = tx.hash().toString('base64');
400
+ if (processedTxHashes.has(txHash)) {
401
+ continue;
402
+ }
403
+ processedTxHashes.add(txHash);
404
+ checkedCount += 1;
405
+ this.logger?.debug(`Checking tx (depth ${currentDepth}): ${txHash}`);
406
+ // Validate transaction and return error if found
407
+ const validationError = this.validateTransactionWithResult(tx, ignoreOpcodeList);
408
+ if (validationError) {
409
+ return { success: false, checkedCount, error: validationError };
410
+ }
411
+ // Add adjacent transactions to queue
412
+ if (currentDepth < maxDepth) {
413
+ if ((direction === 'forward' || direction === 'both') && tx.outMessages.size > 0) {
414
+ for (const msg of tx.outMessages.values()) {
415
+ const dst = msg.info.dest;
416
+ if (!dst || dst instanceof ton_1.ExternalAddress)
417
+ continue;
418
+ queue.push({
419
+ hash: (0, ton_1.beginCell)().store((0, ton_1.storeMessage)(msg)).endCell().hash().toString('base64'),
420
+ address: dst,
421
+ depth: currentDepth + 1,
422
+ hashType: 'in',
423
+ });
424
+ }
425
+ }
426
+ // Backward: add parent (incoming message source)
427
+ if ((direction === 'backward' || direction === 'both') && tx.inMessage?.info.type === 'internal') {
428
+ queue.push({
429
+ hash: (0, ton_1.beginCell)().store((0, ton_1.storeMessage)(tx.inMessage)).endCell().hash().toString('base64'),
430
+ address: tx.inMessage.info.src,
431
+ depth: currentDepth + 1,
432
+ hashType: 'out',
433
+ });
434
+ }
435
+ }
436
+ }
437
+ return { success: true, checkedCount };
438
+ }
439
+ }
440
+ exports.BaseContractOpener = BaseContractOpener;