@chainlink/ccip-sdk 0.92.0 → 0.93.0

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 (223) hide show
  1. package/README.md +20 -18
  2. package/dist/api/index.d.ts +103 -0
  3. package/dist/api/index.d.ts.map +1 -0
  4. package/dist/api/index.js +141 -0
  5. package/dist/api/index.js.map +1 -0
  6. package/dist/api/types.d.ts +38 -0
  7. package/dist/api/types.d.ts.map +1 -0
  8. package/dist/api/types.js +2 -0
  9. package/dist/api/types.js.map +1 -0
  10. package/dist/aptos/index.d.ts +20 -33
  11. package/dist/aptos/index.d.ts.map +1 -1
  12. package/dist/aptos/index.js +34 -26
  13. package/dist/aptos/index.js.map +1 -1
  14. package/dist/aptos/logs.js +1 -1
  15. package/dist/aptos/logs.js.map +1 -1
  16. package/dist/aptos/token.js.map +1 -1
  17. package/dist/chain.d.ts +206 -71
  18. package/dist/chain.d.ts.map +1 -1
  19. package/dist/chain.js +89 -20
  20. package/dist/chain.js.map +1 -1
  21. package/dist/commits.d.ts +2 -2
  22. package/dist/commits.d.ts.map +1 -1
  23. package/dist/commits.js +4 -4
  24. package/dist/commits.js.map +1 -1
  25. package/dist/errors/CCIPError.d.ts.map +1 -1
  26. package/dist/errors/CCIPError.js +3 -2
  27. package/dist/errors/CCIPError.js.map +1 -1
  28. package/dist/errors/codes.d.ts +4 -1
  29. package/dist/errors/codes.d.ts.map +1 -1
  30. package/dist/errors/codes.js +6 -1
  31. package/dist/errors/codes.js.map +1 -1
  32. package/dist/errors/index.d.ts +5 -2
  33. package/dist/errors/index.d.ts.map +1 -1
  34. package/dist/errors/index.js +8 -2
  35. package/dist/errors/index.js.map +1 -1
  36. package/dist/errors/recovery.d.ts.map +1 -1
  37. package/dist/errors/recovery.js +4 -1
  38. package/dist/errors/recovery.js.map +1 -1
  39. package/dist/errors/specialized.d.ts +29 -4
  40. package/dist/errors/specialized.d.ts.map +1 -1
  41. package/dist/errors/specialized.js +48 -6
  42. package/dist/errors/specialized.js.map +1 -1
  43. package/dist/evm/errors.js.map +1 -1
  44. package/dist/evm/index.d.ts +24 -48
  45. package/dist/evm/index.d.ts.map +1 -1
  46. package/dist/evm/index.js +71 -59
  47. package/dist/evm/index.js.map +1 -1
  48. package/dist/evm/logs.js.map +1 -1
  49. package/dist/evm/offchain.js +3 -2
  50. package/dist/evm/offchain.js.map +1 -1
  51. package/dist/evm/viem/client-adapter.d.ts +68 -0
  52. package/dist/evm/viem/client-adapter.d.ts.map +1 -0
  53. package/dist/evm/viem/client-adapter.js +104 -0
  54. package/dist/evm/viem/client-adapter.js.map +1 -0
  55. package/dist/evm/viem/index.d.ts +29 -0
  56. package/dist/evm/viem/index.d.ts.map +1 -0
  57. package/dist/evm/viem/index.js +28 -0
  58. package/dist/evm/viem/index.js.map +1 -0
  59. package/dist/evm/viem/types.d.ts +13 -0
  60. package/dist/evm/viem/types.d.ts.map +1 -0
  61. package/dist/evm/viem/types.js +2 -0
  62. package/dist/evm/viem/types.js.map +1 -0
  63. package/dist/evm/viem/wallet-adapter.d.ts +58 -0
  64. package/dist/evm/viem/wallet-adapter.d.ts.map +1 -0
  65. package/dist/evm/viem/wallet-adapter.js +197 -0
  66. package/dist/evm/viem/wallet-adapter.js.map +1 -0
  67. package/dist/execution.d.ts +1 -1
  68. package/dist/execution.d.ts.map +1 -1
  69. package/dist/execution.js +2 -2
  70. package/dist/execution.js.map +1 -1
  71. package/dist/explorer.d.ts +74 -0
  72. package/dist/explorer.d.ts.map +1 -0
  73. package/dist/explorer.js +67 -0
  74. package/dist/explorer.js.map +1 -0
  75. package/dist/gas.js.map +1 -1
  76. package/dist/hasher/merklemulti.js.map +1 -1
  77. package/dist/http-status.d.ts +20 -0
  78. package/dist/http-status.d.ts.map +1 -0
  79. package/dist/http-status.js +25 -0
  80. package/dist/http-status.js.map +1 -0
  81. package/dist/index.d.ts +11 -4
  82. package/dist/index.d.ts.map +1 -1
  83. package/dist/index.js +5 -3
  84. package/dist/index.js.map +1 -1
  85. package/dist/offchain.js.map +1 -1
  86. package/dist/requests.d.ts +4 -4
  87. package/dist/requests.d.ts.map +1 -1
  88. package/dist/requests.js +6 -6
  89. package/dist/requests.js.map +1 -1
  90. package/dist/solana/cleanup.js +2 -2
  91. package/dist/solana/cleanup.js.map +1 -1
  92. package/dist/solana/exec.js +1 -5
  93. package/dist/solana/exec.js.map +1 -1
  94. package/dist/solana/index.d.ts +28 -57
  95. package/dist/solana/index.d.ts.map +1 -1
  96. package/dist/solana/index.js +66 -70
  97. package/dist/solana/index.js.map +1 -1
  98. package/dist/solana/logs.js +2 -2
  99. package/dist/solana/logs.js.map +1 -1
  100. package/dist/solana/offchain.js +3 -3
  101. package/dist/solana/offchain.js.map +1 -1
  102. package/dist/solana/send.js +1 -1
  103. package/dist/solana/send.js.map +1 -1
  104. package/dist/solana/utils.js +1 -1
  105. package/dist/solana/utils.js.map +1 -1
  106. package/dist/sui/discovery.d.ts.map +1 -1
  107. package/dist/sui/discovery.js +2 -5
  108. package/dist/sui/discovery.js.map +1 -1
  109. package/dist/sui/events.d.ts.map +1 -1
  110. package/dist/sui/events.js +2 -8
  111. package/dist/sui/events.js.map +1 -1
  112. package/dist/sui/index.d.ts +18 -29
  113. package/dist/sui/index.d.ts.map +1 -1
  114. package/dist/sui/index.js +24 -26
  115. package/dist/sui/index.js.map +1 -1
  116. package/dist/sui/manuallyExec/encoder.d.ts.map +1 -1
  117. package/dist/sui/manuallyExec/encoder.js +0 -3
  118. package/dist/sui/manuallyExec/encoder.js.map +1 -1
  119. package/dist/sui/manuallyExec/index.d.ts.map +1 -1
  120. package/dist/sui/manuallyExec/index.js +1 -2
  121. package/dist/sui/manuallyExec/index.js.map +1 -1
  122. package/dist/sui/objects.js +4 -4
  123. package/dist/sui/objects.js.map +1 -1
  124. package/dist/ton/exec.d.ts +2 -2
  125. package/dist/ton/exec.d.ts.map +1 -1
  126. package/dist/ton/exec.js.map +1 -1
  127. package/dist/ton/hasher.js +5 -5
  128. package/dist/ton/hasher.js.map +1 -1
  129. package/dist/ton/index.d.ts +54 -49
  130. package/dist/ton/index.d.ts.map +1 -1
  131. package/dist/ton/index.js +331 -236
  132. package/dist/ton/index.js.map +1 -1
  133. package/dist/ton/logs.d.ts +11 -22
  134. package/dist/ton/logs.d.ts.map +1 -1
  135. package/dist/ton/logs.js +95 -118
  136. package/dist/ton/logs.js.map +1 -1
  137. package/dist/ton/types.d.ts +9 -9
  138. package/dist/ton/types.d.ts.map +1 -1
  139. package/dist/ton/types.js +5 -9
  140. package/dist/ton/types.js.map +1 -1
  141. package/dist/ton/utils.d.ts +8 -27
  142. package/dist/ton/utils.d.ts.map +1 -1
  143. package/dist/ton/utils.js +31 -111
  144. package/dist/ton/utils.js.map +1 -1
  145. package/dist/types.d.ts +34 -0
  146. package/dist/types.d.ts.map +1 -1
  147. package/dist/types.js +30 -0
  148. package/dist/types.js.map +1 -1
  149. package/dist/utils.d.ts +6 -5
  150. package/dist/utils.d.ts.map +1 -1
  151. package/dist/utils.js +76 -52
  152. package/dist/utils.js.map +1 -1
  153. package/dist/viem.d.ts +6 -0
  154. package/dist/viem.d.ts.map +1 -0
  155. package/dist/viem.js +6 -0
  156. package/dist/viem.js.map +1 -0
  157. package/package.json +18 -3
  158. package/src/api/index.ts +167 -0
  159. package/src/api/types.ts +39 -0
  160. package/src/aptos/index.ts +57 -64
  161. package/src/aptos/logs.ts +10 -10
  162. package/src/aptos/token.ts +1 -1
  163. package/src/chain.ts +274 -97
  164. package/src/commits.ts +5 -5
  165. package/src/errors/CCIPError.ts +5 -2
  166. package/src/errors/codes.ts +8 -1
  167. package/src/errors/index.ts +15 -2
  168. package/src/errors/recovery.ts +9 -1
  169. package/src/errors/specialized.ts +61 -6
  170. package/src/evm/errors.ts +2 -2
  171. package/src/evm/index.ts +107 -120
  172. package/src/evm/logs.ts +4 -4
  173. package/src/evm/offchain.ts +5 -4
  174. package/src/evm/viem/client-adapter.ts +124 -0
  175. package/src/evm/viem/index.ts +29 -0
  176. package/src/evm/viem/types.ts +14 -0
  177. package/src/evm/viem/wallet-adapter.ts +233 -0
  178. package/src/execution.ts +9 -9
  179. package/src/explorer.ts +90 -0
  180. package/src/gas.ts +2 -2
  181. package/src/hasher/merklemulti.ts +7 -7
  182. package/src/http-status.ts +31 -0
  183. package/src/index.ts +19 -1
  184. package/src/offchain.ts +1 -1
  185. package/src/requests.ts +9 -12
  186. package/src/solana/cleanup.ts +4 -4
  187. package/src/solana/exec.ts +13 -18
  188. package/src/solana/index.ts +92 -117
  189. package/src/solana/logs.ts +8 -8
  190. package/src/solana/offchain.ts +3 -3
  191. package/src/solana/send.ts +20 -20
  192. package/src/solana/utils.ts +4 -4
  193. package/src/sui/discovery.ts +4 -10
  194. package/src/sui/events.ts +5 -12
  195. package/src/sui/index.ts +36 -48
  196. package/src/sui/manuallyExec/encoder.ts +0 -4
  197. package/src/sui/manuallyExec/index.ts +1 -3
  198. package/src/sui/objects.ts +14 -14
  199. package/src/ton/exec.ts +2 -5
  200. package/src/ton/hasher.ts +5 -5
  201. package/src/ton/index.ts +392 -316
  202. package/src/ton/logs.ts +122 -143
  203. package/src/ton/types.ts +17 -21
  204. package/src/ton/utils.ts +39 -145
  205. package/src/types.ts +36 -0
  206. package/src/utils.ts +96 -66
  207. package/src/viem.ts +5 -0
  208. package/tsconfig.json +3 -2
  209. package/dist/ton/bindings/offramp.d.ts +0 -48
  210. package/dist/ton/bindings/offramp.d.ts.map +0 -1
  211. package/dist/ton/bindings/offramp.js +0 -63
  212. package/dist/ton/bindings/offramp.js.map +0 -1
  213. package/dist/ton/bindings/onramp.d.ts +0 -40
  214. package/dist/ton/bindings/onramp.d.ts.map +0 -1
  215. package/dist/ton/bindings/onramp.js +0 -51
  216. package/dist/ton/bindings/onramp.js.map +0 -1
  217. package/dist/ton/bindings/router.d.ts +0 -47
  218. package/dist/ton/bindings/router.d.ts.map +0 -1
  219. package/dist/ton/bindings/router.js +0 -51
  220. package/dist/ton/bindings/router.js.map +0 -1
  221. package/src/ton/bindings/offramp.ts +0 -96
  222. package/src/ton/bindings/onramp.ts +0 -72
  223. package/src/ton/bindings/router.ts +0 -65
package/src/ton/logs.ts CHANGED
@@ -1,157 +1,136 @@
1
1
  import { Address } from '@ton/core'
2
- import type { TonClient4 } from '@ton/ton'
2
+ import type { TonClient, Transaction } from '@ton/ton'
3
3
 
4
4
  import type { LogFilter } from '../chain.ts'
5
- import { CCIPArgumentInvalidError } from '../errors/specialized.ts'
6
- import type { Log_ } from '../types.ts'
7
-
8
- /** Decoder functions passed to fetchLogs to identify and parse TON log events avoiding circular imports */
9
- export interface LogDecoders {
10
- /** Try to decode as CCIP message, returns messageId if successful */
11
- tryDecodeAsMessage: (log: Pick<Log_, 'data'>) => { messageId: string } | undefined
12
- /** Try to decode as commit report, returns truthy if successful */
13
- tryDecodeAsCommit: (log: Pick<Log_, 'data'>) => unknown[] | undefined
14
- }
15
-
16
- /**
17
- * Fetches logs from a TON address by iterating through account transactions.
18
- *
19
- * Note: For TON, `startBlock` and `endBlock` in opts represent logical time (lt),
20
- * not block sequence numbers. This is because TON transaction APIs are indexed by lt.
21
- * The lt is monotonically increasing per account and suitable for ordering.
22
- *
23
- * @param provider - TonClient4 instance
24
- * @param opts - Log filter options (startBlock/endBlock are lt values)
25
- * @param ltTimestampCache - Cache mapping lt to Unix timestamp
26
- * @param decoders - Message decoder functions
27
- */
28
- export async function* fetchLogs(
29
- provider: TonClient4,
30
- opts: LogFilter,
31
- ltTimestampCache: Map<number, number>,
32
- decoders: LogDecoders,
33
- ): AsyncIterableIterator<Log_> {
34
- if (!opts.address) {
35
- throw new CCIPArgumentInvalidError('address', 'Address is required for TON log filtering')
36
- }
5
+ import {
6
+ CCIPLogsWatchRequiresFinalityError,
7
+ CCIPLogsWatchRequiresStartError,
8
+ } from '../errors/index.ts'
9
+ import { CCIPLogsAddressRequiredError } from '../errors/specialized.ts'
10
+ import type { ChainTransaction } from '../types.ts'
11
+ import { sleep } from '../utils.ts'
12
+
13
+ const DEFAULT_POLL_INTERVAL = 5000
14
+
15
+ async function* fetchTxsForward(
16
+ opts: LogFilter & { pollInterval?: number },
17
+ { provider }: { provider: TonClient },
18
+ ) {
19
+ const limit = Math.min(opts.page || 99, 99)
20
+
21
+ // forward collect all matching txs in array
22
+ const allTxs = [] as Transaction[]
23
+ let batch: typeof allTxs, until: bigint | undefined
24
+ do {
25
+ batch = await provider.getTransactions(Address.parse(opts.address!), {
26
+ limit,
27
+ ...(!!allTxs.length && {
28
+ lt: allTxs[allTxs.length - 1]!.lt.toString(),
29
+ hash: allTxs[allTxs.length - 1]!.hash().toString('base64'),
30
+ to_lt: opts.startBlock?.toString(),
31
+ }),
32
+ })
33
+ until ??= batch[0]?.lt
34
+
35
+ while (batch.length > 0 && batch[batch.length - 1]!.now < (opts.startTime || 0)) {
36
+ batch.length-- // truncate tail of txs which are older than requested start
37
+ }
37
38
 
38
- const address = Address.parse(opts.address)
39
- const searchForward = !!(opts.startBlock || opts.startTime)
39
+ allTxs.push(...batch) // concat in descending order
40
+ } while (batch.length >= limit)
40
41
 
41
- // Get the latest block for account state lookup
42
- const lastBlock = await provider.getLastBlock()
42
+ allTxs.reverse() // forward
43
43
 
44
- // Get account state to find the last transaction
45
- const account = await provider.getAccountLite(lastBlock.last.seqno, address)
46
- if (!account.account.last) {
47
- return // No transactions
44
+ const notAfter =
45
+ typeof opts.endBlock !== 'number' || opts.endBlock < 0 ? undefined : BigInt(opts.endBlock)
46
+ while (notAfter && allTxs.length > 0 && allTxs[allTxs.length - 1]!.lt > notAfter) {
47
+ allTxs.length-- // truncate head (after reverse) of txs newer than requested end
48
+ }
49
+ yield* allTxs // all past logs
50
+
51
+ if (allTxs.length) until = allTxs[allTxs.length - 1]!.lt
52
+ let lastReq = performance.now()
53
+ // if not watch mode, returns
54
+ while (opts.watch) {
55
+ let break$ = sleep(
56
+ Math.max((opts.pollInterval || DEFAULT_POLL_INTERVAL) - (performance.now() - lastReq), 1),
57
+ ).then(() => false)
58
+ if (opts.watch instanceof Promise) break$ = Promise.race([break$, opts.watch.then(() => true)])
59
+ if (await break$) break
60
+
61
+ lastReq = performance.now()
62
+ batch = await provider.getTransactions(Address.parse(opts.address!), {
63
+ limit,
64
+ to_lt: until?.toString(),
65
+ })
66
+
67
+ batch.reverse() // forward
68
+
69
+ for (const tx of batch) {
70
+ until = tx.lt
71
+ yield tx
72
+ }
48
73
  }
74
+ }
49
75
 
50
- // Pagination cursor
51
- let cursorLt: bigint = BigInt(account.account.last.lt)
52
- let cursorHash: Buffer = Buffer.from(account.account.last.hash, 'base64')
53
-
54
- const collectedLogs: Log_[] = []
55
- let isFirstBatch = true
56
-
57
- while (true) {
58
- const txs = await provider.getAccountTransactions(address, cursorLt, cursorHash)
59
- if (!txs || txs.length === 0) break
60
-
61
- // Skip first tx when paginating (it's the same as last from previous batch)
62
- const startIdx = isFirstBatch ? 0 : 1
63
- isFirstBatch = false
64
-
65
- for (let i = startIdx; i < txs.length; i++) {
66
- const { tx } = txs[i]
67
- const txLt = Number(tx.lt)
68
- const timestamp = tx.now
69
-
70
- // Cache lt → timestamp
71
- ltTimestampCache.set(txLt, timestamp)
72
-
73
- // Range filters
74
- if (opts.startBlock && typeof opts.startBlock === 'number' && txLt < opts.startBlock) {
75
- if (searchForward) yield* collectedLogs.reverse()
76
- return
77
- }
78
- if (opts.startTime && timestamp < opts.startTime) {
79
- if (searchForward) yield* collectedLogs.reverse()
80
- return
81
- }
82
- if (opts.endBlock && typeof opts.endBlock === 'number' && txLt > opts.endBlock) {
83
- continue
84
- }
85
-
86
- // Extract logs from external-out messages
87
- const compositeHash = `${address.toRawString()}:${tx.lt}:${tx.hash().toString('hex')}`
88
- let index = 0
89
-
90
- for (const msg of tx.outMessages.values()) {
91
- if (msg.info.type !== 'external-out') {
92
- index++
93
- continue
94
- }
95
-
96
- const data = msg.body.toBoc().toString('base64')
97
- const topicFilter = opts.topics?.[0]
98
-
99
- // Try to identify log type and build topics array
100
- const topics: string[] = []
101
-
102
- if (topicFilter === 'CommitReportAccepted') {
103
- // Looking for commits - skip if not a valid commit
104
- if (!decoders.tryDecodeAsCommit({ data })) {
105
- index++
106
- continue
107
- }
108
- topics.push('CommitReportAccepted')
109
- } else {
110
- // Try to decode as CCIP message
111
- const message = decoders.tryDecodeAsMessage({ data })
112
- if (topicFilter && !message) {
113
- // Topic filter set but couldn't decode as message - skip
114
- index++
115
- continue
76
+ async function* fetchTxsBackwards(
77
+ opts: LogFilter & { pollInterval?: number },
78
+ { provider }: { provider: TonClient },
79
+ ) {
80
+ const limit = Math.min(opts.page || 100, 100)
81
+
82
+ if (typeof opts.endBlock === 'number' && opts.endBlock < 0) opts.endBlock = 'latest'
83
+
84
+ let batch: Transaction[] | undefined
85
+ do {
86
+ batch = await provider.getTransactions(Address.parse(opts.address!), {
87
+ limit,
88
+ ...(batch?.length
89
+ ? {
90
+ lt: batch[batch.length - 1]!.lt.toString(),
91
+ hash: batch[batch.length - 1]!.hash().toString('base64'),
116
92
  }
117
- if (message) {
118
- topics.push('CCIPMessageSent')
119
- }
120
- }
121
-
122
- const log: Log_ = {
123
- address: address.toRawString(),
124
- topics,
125
- data,
126
- blockNumber: txLt,
127
- transactionHash: compositeHash,
128
- index,
129
- }
130
-
131
- if (searchForward) {
132
- collectedLogs.push(log)
133
- } else {
134
- yield log
135
- }
136
- index++
137
- }
93
+ : opts.endBefore && opts.endBlock
94
+ ? { lt: opts.endBlock.toString(), hash: opts.endBefore }
95
+ : {}),
96
+ })
97
+ for (const tx of batch) {
98
+ if (typeof opts.endBlock === 'number' && tx.lt > BigInt(opts.endBlock)) continue
99
+ yield tx
138
100
  }
101
+ } while (batch.length >= limit)
102
+ }
139
103
 
140
- // Update pagination cursor
141
- if (txs.length < 2) break
142
- const lastTx = txs[txs.length - 1].tx
143
- cursorLt = lastTx.lt
144
- cursorHash = Buffer.from(lastTx.hash())
145
-
146
- // Early exit if past start boundary
147
- if (
148
- opts.startBlock &&
149
- typeof opts.startBlock === 'number' &&
150
- Number(cursorLt) < opts.startBlock
151
- )
152
- break
153
- if (opts.startTime && lastTx.now < opts.startTime) break
104
+ /**
105
+ * Internal method to get transactions for an address with pagination.
106
+ * @param opts - Log filter options.
107
+ * @returns Async generator of Solana transactions.
108
+ */
109
+ export async function* streamTransactionsForAddress(
110
+ opts: Omit<LogFilter, 'topics'> & { pollInterval?: number },
111
+ ctx: {
112
+ provider: TonClient
113
+ getTransaction: (tx: Transaction) => Promise<ChainTransaction>
114
+ },
115
+ ): AsyncGenerator<ChainTransaction> {
116
+ if (!opts.address) throw new CCIPLogsAddressRequiredError()
117
+
118
+ opts.endBlock ||= 'latest'
119
+
120
+ let allTransactions
121
+ if (opts.startBlock != null || opts.startTime != null) {
122
+ if (opts.watch && ((typeof opts.endBlock === 'number' && opts.endBlock > 0) || opts.endBefore))
123
+ throw new CCIPLogsWatchRequiresFinalityError(opts.endBlock)
124
+
125
+ allTransactions = fetchTxsForward(opts, ctx)
126
+ } else {
127
+ if (opts.watch) throw new CCIPLogsWatchRequiresStartError()
128
+
129
+ allTransactions = fetchTxsBackwards(opts, ctx) // generate backwards until depleting getSignaturesForAddress
154
130
  }
155
131
 
156
- if (searchForward) yield* collectedLogs.reverse()
132
+ // Process signatures
133
+ for await (const tx of allTransactions) {
134
+ yield await ctx.getTransaction(tx)
135
+ }
157
136
  }
package/src/ton/types.ts CHANGED
@@ -1,6 +1,4 @@
1
1
  import { type Builder, Address, Cell, beginCell } from '@ton/core'
2
- import type { KeyPair } from '@ton/crypto'
3
- import type { WalletContractV4 } from '@ton/ton'
4
2
  import { toBigInt } from 'ethers'
5
3
 
6
4
  import { CCIPDataFormatUnsupportedError } from '../errors/specialized.ts'
@@ -14,14 +12,6 @@ export type CCIPMessage_V1_6_TON = CCIPMessage_V1_6 & EVMExtraArgsV2
14
12
  /** Opcode for OffRamp_ManuallyExecute message on TON */
15
13
  export const MANUALLY_EXECUTE_OPCODE = 0xa00785cf
16
14
 
17
- /**
18
- * TON wallet with keypair for signing transactions
19
- */
20
- export interface TONWallet {
21
- contract: WalletContractV4
22
- keyPair: KeyPair
23
- }
24
-
25
15
  /**
26
16
  * Unsigned TON transaction data.
27
17
  * Contains the payload needed to construct a transaction.
@@ -33,6 +23,16 @@ export type UnsignedTONTx = {
33
23
  to: string
34
24
  /** Message payload as BOC-serialized Cell */
35
25
  body: Cell
26
+ /** Value to send with the transaction */
27
+ value?: bigint
28
+ }
29
+
30
+ /**
31
+ * TON wallet with keypair for signing transactions
32
+ */
33
+ export interface TONWallet {
34
+ getAddress(): string | Promise<string>
35
+ sendTransaction(unsignedTx: Omit<UnsignedTONTx, 'family'>): Promise<number>
36
36
  }
37
37
 
38
38
  /** Typeguard for TON Wallet */
@@ -40,14 +40,10 @@ export function isTONWallet(wallet: unknown): wallet is TONWallet {
40
40
  return (
41
41
  typeof wallet === 'object' &&
42
42
  wallet !== null &&
43
- 'contract' in wallet &&
44
- 'keyPair' in wallet &&
45
- typeof wallet.contract === 'object' &&
46
- wallet.contract !== null &&
47
- 'address' in wallet.contract &&
48
- typeof wallet.keyPair === 'object' &&
49
- wallet.keyPair !== null &&
50
- 'secretKey' in wallet.keyPair
43
+ 'sendTransaction' in wallet &&
44
+ typeof wallet.sendTransaction === 'function' &&
45
+ 'getAddress' in wallet &&
46
+ typeof wallet.getAddress === 'function'
51
47
  )
52
48
  }
53
49
 
@@ -72,9 +68,9 @@ function asSnakeData<T>(array: T[], builderFn: (item: T) => Builder): Cell {
72
68
  cells.push(builder)
73
69
 
74
70
  // Build the linked structure from the end
75
- let current = cells[cells.length - 1].endCell()
71
+ let current = cells[cells.length - 1]!.endCell()
76
72
  for (let i = cells.length - 2; i >= 0; i--) {
77
- const b = cells[i]
73
+ const b = cells[i]!
78
74
  b.storeRef(current)
79
75
  current = b.endCell()
80
76
  }
@@ -118,7 +114,7 @@ function serializeMessage(message: CCIPMessage_V1_6_TON): Builder {
118
114
  .storeAddress(Address.parse(message.receiver))
119
115
  .storeCoins(message.gasLimit)
120
116
  .storeMaybeRef(
121
- message.tokenAmounts?.length > 0 ? serializeTokenAmounts(message.tokenAmounts) : null,
117
+ message.tokenAmounts.length > 0 ? serializeTokenAmounts(message.tokenAmounts) : null,
122
118
  )
123
119
  }
124
120
 
package/src/ton/utils.ts CHANGED
@@ -1,30 +1,9 @@
1
- import { type Address, Cell, Dictionary, beginCell } from '@ton/core'
2
- import type { TonClient4 } from '@ton/ton'
1
+ import { Cell, Dictionary, beginCell } from '@ton/core'
2
+ import { hexlify, toBeHex } from 'ethers'
3
3
 
4
- import {
5
- CCIPTransactionNotFinalizedError,
6
- CCIPTransactionNotFoundError,
7
- } from '../errors/specialized.ts'
4
+ import { CCIPTransactionNotFoundError } from '../errors/specialized.ts'
8
5
  import type { WithLogger } from '../types.ts'
9
- import { bytesToBuffer, sleep } from '../utils.ts'
10
-
11
- /**
12
- * Converts hex string to Buffer, handling 0x prefix normalization
13
- * Returns empty buffer for empty input
14
- */
15
- export const hexToBuffer = (value: string): Buffer => {
16
- if (!value || value === '0x' || value === '0X') return Buffer.alloc(0)
17
- // Normalize to lowercase 0x prefix for bytesToBuffer/getDataBytes
18
- let normalized: string
19
- if (value.startsWith('0x')) {
20
- normalized = value
21
- } else if (value.startsWith('0X')) {
22
- normalized = `0x${value.slice(2)}`
23
- } else {
24
- normalized = `0x${value}`
25
- }
26
- return bytesToBuffer(normalized)
27
- }
6
+ import { bytesToBuffer } from '../utils.ts'
28
7
 
29
8
  /**
30
9
  * Attempts to parse hex string as TON BOC (Bag of Cells) format
@@ -32,10 +11,10 @@ export const hexToBuffer = (value: string): Buffer => {
32
11
  * Used for parsing message data, extra data, and other hex-encoded fields
33
12
  */
34
13
  export const tryParseCell = (hex: string): Cell => {
35
- const bytes = hexToBuffer(hex)
14
+ const bytes = bytesToBuffer(hex)
36
15
  if (bytes.length === 0) return beginCell().endCell()
37
16
  try {
38
- return Cell.fromBoc(bytes)[0]
17
+ return Cell.fromBoc(bytes)[0]!
39
18
  } catch {
40
19
  return beginCell().storeBuffer(bytes).endCell()
41
20
  }
@@ -47,109 +26,10 @@ export const tryParseCell = (hex: string): Cell => {
47
26
  * Used for type detection and validation when decoding CCIP extra args
48
27
  * Returns tag as 0x-prefixed hex string for easy comparison
49
28
  */
50
- export function extractMagicTag(bocHex: string): string {
51
- const cell = Cell.fromBoc(hexToBuffer(bocHex))[0]
52
- const tag = cell.beginParse().loadUint(32)
53
- return `0x${tag.toString(16).padStart(8, '0')}`
54
- }
55
-
56
- /**
57
- * Waits for a transaction to be confirmed by polling until the wallet's seqno advances.
58
- * Once seqno advances past expectedSeqno, fetches the latest transaction details.
59
- *
60
- * @param client - TON V4 client
61
- * @param walletAddress - Address of the wallet that sent the transaction
62
- * @param expectedSeqno - The seqno used when sending the transaction
63
- * @param expectedDestination - Optional destination address to verify (e.g., offRamp)
64
- * @param maxAttempts - Maximum polling attempts (default: 25)
65
- * @param intervalMs - Polling interval in ms (default: 1000)
66
- * @returns Transaction info with lt and hash
67
- */
68
- export async function waitForTransaction(
69
- client: TonClient4,
70
- walletAddress: Address,
71
- expectedSeqno: number,
72
- expectedDestination?: Address,
73
- maxAttempts = 25,
74
- intervalMs = 1000,
75
- ): Promise<{ lt: string; hash: string; timestamp: number }> {
76
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
77
- try {
78
- // Get latest block for state lookup (V4 API requires block seqno)
79
- const lastBlock = await client.getLastBlock()
80
-
81
- // Check current seqno by running the getter
82
- const seqnoResult = await client.runMethod(lastBlock.last.seqno, walletAddress, 'seqno')
83
- const currentSeqno = seqnoResult.reader.readNumber()
84
-
85
- const seqnoAdvanced = currentSeqno > expectedSeqno
86
-
87
- if (seqnoAdvanced) {
88
- // Get account state to find latest transaction
89
- const account = await client.getAccountLite(lastBlock.last.seqno, walletAddress)
90
- if (!account.account.last) {
91
- await sleep(intervalMs)
92
- continue
93
- }
94
-
95
- // Get recent transactions using V4 API
96
- const txs = await client.getAccountTransactions(
97
- walletAddress,
98
- BigInt(account.account.last.lt),
99
- Buffer.from(account.account.last.hash, 'base64'),
100
- )
101
-
102
- for (const { tx } of txs) {
103
- // If destination verification requested, check outgoing messages
104
- if (expectedDestination) {
105
- const outMessages = tx.outMessages.values()
106
- let destinationMatch = false
107
-
108
- for (const msg of outMessages) {
109
- if (msg.info.type === 'internal' && msg.info.dest.equals(expectedDestination)) {
110
- destinationMatch = true
111
- break
112
- }
113
- }
114
-
115
- if (!destinationMatch) continue
116
- }
117
-
118
- return {
119
- lt: tx.lt.toString(),
120
- hash: tx.hash().toString('hex'),
121
- timestamp: tx.now,
122
- }
123
- }
124
- }
125
-
126
- // Handle case where contract was just deployed (seqno 0 -> 1)
127
- if (expectedSeqno === 0 && attempt > 0) {
128
- const account = await client.getAccountLite(lastBlock.last.seqno, walletAddress)
129
- if (account.account.last) {
130
- const txs = await client.getAccountTransactions(
131
- walletAddress,
132
- BigInt(account.account.last.lt),
133
- Buffer.from(account.account.last.hash, 'base64'),
134
- )
135
- if (txs.length > 0) {
136
- const { tx } = txs[0]
137
- return {
138
- lt: tx.lt.toString(),
139
- hash: tx.hash().toString('hex'),
140
- timestamp: tx.now,
141
- }
142
- }
143
- }
144
- }
145
- } catch {
146
- // Contract might not be initialized yet, or network error - retry
147
- }
148
-
149
- await sleep(intervalMs)
150
- }
151
-
152
- throw new CCIPTransactionNotFinalizedError(String(expectedSeqno))
29
+ export function extractMagicTag(cell: string | Cell): string {
30
+ if (typeof cell === 'string') cell = Cell.fromBoc(bytesToBuffer(cell))[0]!
31
+ const tag = cell.beginParse().loadBuffer(4)
32
+ return hexlify(tag)
153
33
  }
154
34
 
155
35
  /**
@@ -373,7 +253,7 @@ export async function parseJettonContent(
373
253
  // If still no dict, try loading directly from first ref
374
254
  if (!dict && contentCell.refs.length > 0) {
375
255
  try {
376
- const refSlice = contentCell.refs[0].beginParse()
256
+ const refSlice = contentCell.refs[0]!.beginParse()
377
257
  dict = refSlice.loadDictDirect(Dictionary.Keys.BigUint(256), Dictionary.Values.Cell())
378
258
  } catch {
379
259
  logger?.debug?.('Onchain: failed to load dict directly from ref')
@@ -461,15 +341,15 @@ export async function parseJettonContent(
461
341
  *
462
342
  * @param hash - Raw 64-char hex transaction hash
463
343
  * @param isTestnet - Whether to use testnet API
464
- * @param rateLimitedFetch - Rate-limited fetch function
344
+ * @param fetch - Rate-limited fetch function
465
345
  * @param logger - Logger instance
466
346
  * @returns Transaction identifier components needed for V4 API lookup
467
347
  */
468
348
  export async function lookupTxByRawHash(
469
349
  hash: string,
470
350
  isTestnet: boolean,
471
- rateLimitedFetch: typeof fetch,
472
- logger: WithLogger['logger'],
351
+ fetch = globalThis.fetch,
352
+ { logger = console }: WithLogger = {},
473
353
  ): Promise<{
474
354
  account: string
475
355
  lt: string
@@ -480,35 +360,49 @@ export async function lookupTxByRawHash(
480
360
  : 'https://toncenter.com/api/v3/transactions'
481
361
 
482
362
  // TonCenter V3 accepts hex directly
483
- const cleanHash = hash.startsWith('0x') ? hash.slice(2) : hash
484
-
363
+ const cleanHash = bytesToBuffer(hash).toString('hex')
485
364
  const url = `${baseUrl}?hash=${cleanHash}`
486
- logger?.debug?.(`TonCenter V3 lookup: ${url}`)
487
365
 
488
366
  let response: Response
489
367
  try {
490
- response = await rateLimitedFetch(url, {
368
+ response = await fetch(url, {
491
369
  headers: { Accept: 'application/json' },
492
370
  })
493
371
  } catch (error) {
494
- logger?.error?.(`TonCenter V3 fetch failed:`, error)
372
+ logger.error(`TonCenter V3 fetch failed:`, error)
495
373
  throw new CCIPTransactionNotFoundError(hash, { cause: error as Error })
496
374
  }
497
375
 
498
- let data: { transactions?: Array<{ account: string; lt: string; hash: string }> }
376
+ let data: { transactions?: Array<{ account: string; lt: string; hash: string }> } | undefined
499
377
  try {
500
378
  data = (await response.json()) as typeof data
501
379
  } catch (error) {
502
- logger?.error?.(`TonCenter V3 JSON parse failed:`, error)
380
+ logger.error(`TonCenter V3 JSON parse failed:`, error)
503
381
  throw new CCIPTransactionNotFoundError(hash, { cause: error as Error })
504
382
  }
505
383
 
506
- logger?.debug?.(`TonCenter V3 response:`, data)
384
+ logger.debug(`TonCenter V3 response:`, data)
507
385
 
508
- if (!data.transactions || data.transactions.length === 0) {
509
- logger?.debug?.(`TonCenter V3: no transactions found for hash ${cleanHash}`)
386
+ if (!data?.transactions?.length) {
387
+ logger.debug(`TonCenter V3: no transactions found for hash ${cleanHash}`)
510
388
  throw new CCIPTransactionNotFoundError(hash)
511
389
  }
512
390
 
513
- return data.transactions[0]
391
+ return data.transactions[0]!
392
+ }
393
+
394
+ const crcTable =
395
+ '00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D'
396
+ .split(' ')
397
+ .map((s) => parseInt(s, 16))
398
+
399
+ /**
400
+ * Calculates the 4B (32bits, int4) crc32 of a given string
401
+ */
402
+ export function crc32(str: string) {
403
+ let crc = -1
404
+ for (let i = 0, iTop = str.length; i < iTop; i++) {
405
+ crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xff]!
406
+ }
407
+ return toBeHex((crc ^ -1) >>> 0, 4)
514
408
  }
package/src/types.ts CHANGED
@@ -199,6 +199,42 @@ export const ExecutionState = {
199
199
  /** Type representing an execution state value. */
200
200
  export type ExecutionState = (typeof ExecutionState)[keyof typeof ExecutionState]
201
201
 
202
+ /**
203
+ * CCIP message lifecycle status.
204
+ * Represents the current state of a cross-chain message.
205
+ */
206
+ export const MessageStatus = {
207
+ /** Message sent on source chain, pending finalization. */
208
+ Sent: 'SENT',
209
+ /** Source chain transaction finalized. */
210
+ SourceFinalized: 'SOURCE_FINALIZED',
211
+ /** Commit report accepted on destination chain. */
212
+ Committed: 'COMMITTED',
213
+ /** Commit blessed by Risk Management Network. */
214
+ Blessed: 'BLESSED',
215
+ /** Message executed successfully on destination. */
216
+ Success: 'SUCCESS',
217
+ /** Message execution failed on destination. */
218
+ Failed: 'FAILED',
219
+ } as const
220
+ /** Type representing a CCIP message lifecycle status. */
221
+ export type MessageStatus = (typeof MessageStatus)[keyof typeof MessageStatus]
222
+
223
+ /**
224
+ * Intent operation status for cross-chain swaps/bridges.
225
+ * Represents the current state of an intent.
226
+ */
227
+ export const IntentStatus = {
228
+ /** Intent created, awaiting fulfillment. */
229
+ Pending: 'PENDING',
230
+ /** Intent fulfilled successfully. */
231
+ Completed: 'COMPLETED',
232
+ /** Intent failed. */
233
+ Failed: 'FAILED',
234
+ } as const
235
+ /** Type representing an intent operation status. */
236
+ export type IntentStatus = (typeof IntentStatus)[keyof typeof IntentStatus]
237
+
202
238
  /**
203
239
  * Receipt of a CCIP message execution on the destination chain.
204
240
  */