@agirails/sdk 2.0.1-beta → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (405) hide show
  1. package/LICENSE +190 -0
  2. package/README.md +116 -108
  3. package/bin/actp +10 -0
  4. package/dist/ACTPClient.d.ts +456 -33
  5. package/dist/ACTPClient.d.ts.map +1 -1
  6. package/dist/ACTPClient.js +477 -93
  7. package/dist/ACTPClient.js.map +1 -1
  8. package/dist/abi/AgentRegistry.json +782 -0
  9. package/dist/abi/EscrowVault.json +106 -38
  10. package/dist/abi/IdentityRegistry.json +316 -0
  11. package/dist/adapters/BaseAdapter.d.ts +231 -0
  12. package/dist/adapters/BaseAdapter.d.ts.map +1 -0
  13. package/dist/adapters/BaseAdapter.js +393 -0
  14. package/dist/adapters/BaseAdapter.js.map +1 -0
  15. package/dist/adapters/BeginnerAdapter.d.ts +152 -0
  16. package/dist/adapters/BeginnerAdapter.d.ts.map +1 -0
  17. package/dist/adapters/BeginnerAdapter.js +168 -0
  18. package/dist/adapters/BeginnerAdapter.js.map +1 -0
  19. package/dist/adapters/IntermediateAdapter.d.ts +211 -0
  20. package/dist/adapters/IntermediateAdapter.d.ts.map +1 -0
  21. package/dist/adapters/IntermediateAdapter.js +260 -0
  22. package/dist/adapters/IntermediateAdapter.js.map +1 -0
  23. package/dist/adapters/index.d.ts +15 -0
  24. package/dist/adapters/index.d.ts.map +1 -0
  25. package/dist/adapters/index.js +26 -0
  26. package/dist/adapters/index.js.map +1 -0
  27. package/dist/builders/DeliveryProofBuilder.d.ts +60 -1
  28. package/dist/builders/DeliveryProofBuilder.d.ts.map +1 -1
  29. package/dist/builders/DeliveryProofBuilder.js +81 -5
  30. package/dist/builders/DeliveryProofBuilder.js.map +1 -1
  31. package/dist/builders/QuoteBuilder.d.ts +101 -0
  32. package/dist/builders/QuoteBuilder.d.ts.map +1 -1
  33. package/dist/builders/QuoteBuilder.js +120 -3
  34. package/dist/builders/QuoteBuilder.js.map +1 -1
  35. package/dist/builders/index.d.ts +4 -0
  36. package/dist/builders/index.d.ts.map +1 -1
  37. package/dist/builders/index.js +4 -0
  38. package/dist/builders/index.js.map +1 -1
  39. package/dist/cli/commands/balance.d.ts +13 -0
  40. package/dist/cli/commands/balance.d.ts.map +1 -0
  41. package/dist/cli/commands/balance.js +89 -0
  42. package/dist/cli/commands/balance.js.map +1 -0
  43. package/dist/cli/commands/batch.d.ts +24 -0
  44. package/dist/cli/commands/batch.d.ts.map +1 -0
  45. package/dist/cli/commands/batch.js +424 -0
  46. package/dist/cli/commands/batch.js.map +1 -0
  47. package/dist/cli/commands/config.d.ts +13 -0
  48. package/dist/cli/commands/config.d.ts.map +1 -0
  49. package/dist/cli/commands/config.js +192 -0
  50. package/dist/cli/commands/config.js.map +1 -0
  51. package/dist/cli/commands/init.d.ts +19 -0
  52. package/dist/cli/commands/init.d.ts.map +1 -0
  53. package/dist/cli/commands/init.js +143 -0
  54. package/dist/cli/commands/init.js.map +1 -0
  55. package/dist/cli/commands/mint.d.ts +13 -0
  56. package/dist/cli/commands/mint.d.ts.map +1 -0
  57. package/dist/cli/commands/mint.js +91 -0
  58. package/dist/cli/commands/mint.js.map +1 -0
  59. package/dist/cli/commands/pay.d.ts +18 -0
  60. package/dist/cli/commands/pay.d.ts.map +1 -0
  61. package/dist/cli/commands/pay.js +87 -0
  62. package/dist/cli/commands/pay.js.map +1 -0
  63. package/dist/cli/commands/simulate.d.ts +32 -0
  64. package/dist/cli/commands/simulate.d.ts.map +1 -0
  65. package/dist/cli/commands/simulate.js +290 -0
  66. package/dist/cli/commands/simulate.js.map +1 -0
  67. package/dist/cli/commands/time.d.ts +29 -0
  68. package/dist/cli/commands/time.d.ts.map +1 -0
  69. package/dist/cli/commands/time.js +252 -0
  70. package/dist/cli/commands/time.js.map +1 -0
  71. package/dist/cli/commands/tx.d.ts +16 -0
  72. package/dist/cli/commands/tx.d.ts.map +1 -0
  73. package/dist/cli/commands/tx.js +379 -0
  74. package/dist/cli/commands/tx.js.map +1 -0
  75. package/dist/cli/commands/watch.d.ts +20 -0
  76. package/dist/cli/commands/watch.d.ts.map +1 -0
  77. package/dist/cli/commands/watch.js +160 -0
  78. package/dist/cli/commands/watch.js.map +1 -0
  79. package/dist/cli/index.d.ts +17 -0
  80. package/dist/cli/index.d.ts.map +1 -0
  81. package/dist/cli/index.js +104 -0
  82. package/dist/cli/index.js.map +1 -0
  83. package/dist/cli/utils/client.d.ts +70 -0
  84. package/dist/cli/utils/client.d.ts.map +1 -0
  85. package/dist/cli/utils/client.js +240 -0
  86. package/dist/cli/utils/client.js.map +1 -0
  87. package/dist/cli/utils/config.d.ts +91 -0
  88. package/dist/cli/utils/config.d.ts.map +1 -0
  89. package/dist/cli/utils/config.js +240 -0
  90. package/dist/cli/utils/config.js.map +1 -0
  91. package/dist/cli/utils/output.d.ts +174 -0
  92. package/dist/cli/utils/output.d.ts.map +1 -0
  93. package/dist/cli/utils/output.js +380 -0
  94. package/dist/cli/utils/output.js.map +1 -0
  95. package/dist/config/networks.d.ts +28 -0
  96. package/dist/config/networks.d.ts.map +1 -1
  97. package/dist/config/networks.js +60 -12
  98. package/dist/config/networks.js.map +1 -1
  99. package/dist/errors/index.d.ts +165 -2
  100. package/dist/errors/index.d.ts.map +1 -1
  101. package/dist/errors/index.js +260 -2
  102. package/dist/errors/index.js.map +1 -1
  103. package/dist/index.d.ts +61 -13
  104. package/dist/index.d.ts.map +1 -1
  105. package/dist/index.js +141 -36
  106. package/dist/index.js.map +1 -1
  107. package/dist/level0/Provider.d.ts +106 -0
  108. package/dist/level0/Provider.d.ts.map +1 -0
  109. package/dist/level0/Provider.js +10 -0
  110. package/dist/level0/Provider.js.map +1 -0
  111. package/dist/level0/ServiceDirectory.d.ts +74 -0
  112. package/dist/level0/ServiceDirectory.d.ts.map +1 -0
  113. package/dist/level0/ServiceDirectory.js +122 -0
  114. package/dist/level0/ServiceDirectory.js.map +1 -0
  115. package/dist/level0/index.d.ts +10 -0
  116. package/dist/level0/index.d.ts.map +1 -0
  117. package/dist/level0/index.js +15 -0
  118. package/dist/level0/index.js.map +1 -0
  119. package/dist/level0/provide.d.ts +51 -0
  120. package/dist/level0/provide.d.ts.map +1 -0
  121. package/dist/level0/provide.js +113 -0
  122. package/dist/level0/provide.js.map +1 -0
  123. package/dist/level0/request.d.ts +53 -0
  124. package/dist/level0/request.d.ts.map +1 -0
  125. package/dist/level0/request.js +462 -0
  126. package/dist/level0/request.js.map +1 -0
  127. package/dist/level1/Agent.d.ts +472 -0
  128. package/dist/level1/Agent.d.ts.map +1 -0
  129. package/dist/level1/Agent.js +1091 -0
  130. package/dist/level1/Agent.js.map +1 -0
  131. package/dist/level1/index.d.ts +10 -0
  132. package/dist/level1/index.d.ts.map +1 -0
  133. package/dist/level1/index.js +30 -0
  134. package/dist/level1/index.js.map +1 -0
  135. package/dist/level1/pricing/PriceCalculator.d.ts +62 -0
  136. package/dist/level1/pricing/PriceCalculator.d.ts.map +1 -0
  137. package/dist/level1/pricing/PriceCalculator.js +237 -0
  138. package/dist/level1/pricing/PriceCalculator.js.map +1 -0
  139. package/dist/level1/pricing/PricingStrategy.d.ts +179 -0
  140. package/dist/level1/pricing/PricingStrategy.d.ts.map +1 -0
  141. package/dist/level1/pricing/PricingStrategy.js +11 -0
  142. package/dist/level1/pricing/PricingStrategy.js.map +1 -0
  143. package/dist/level1/types/Job.d.ts +166 -0
  144. package/dist/level1/types/Job.d.ts.map +1 -0
  145. package/dist/level1/types/Job.js +11 -0
  146. package/dist/level1/types/Job.js.map +1 -0
  147. package/dist/level1/types/Options.d.ts +258 -0
  148. package/dist/level1/types/Options.d.ts.map +1 -0
  149. package/dist/level1/types/Options.js +8 -0
  150. package/dist/level1/types/Options.js.map +1 -0
  151. package/dist/level1/types/index.d.ts +8 -0
  152. package/dist/level1/types/index.d.ts.map +1 -0
  153. package/dist/level1/types/index.js +8 -0
  154. package/dist/level1/types/index.js.map +1 -0
  155. package/dist/protocol/ACTPKernel.d.ts +229 -2
  156. package/dist/protocol/ACTPKernel.d.ts.map +1 -1
  157. package/dist/protocol/ACTPKernel.js +367 -33
  158. package/dist/protocol/ACTPKernel.js.map +1 -1
  159. package/dist/protocol/AgentRegistry.d.ts +177 -0
  160. package/dist/protocol/AgentRegistry.d.ts.map +1 -0
  161. package/dist/protocol/AgentRegistry.js +449 -0
  162. package/dist/protocol/AgentRegistry.js.map +1 -0
  163. package/dist/protocol/DIDManager.d.ts +289 -0
  164. package/dist/protocol/DIDManager.d.ts.map +1 -0
  165. package/dist/protocol/DIDManager.js +481 -0
  166. package/dist/protocol/DIDManager.js.map +1 -0
  167. package/dist/protocol/DIDResolver.d.ts +236 -0
  168. package/dist/protocol/DIDResolver.d.ts.map +1 -0
  169. package/dist/protocol/DIDResolver.js +495 -0
  170. package/dist/protocol/DIDResolver.js.map +1 -0
  171. package/dist/protocol/EASHelper.d.ts +57 -2
  172. package/dist/protocol/EASHelper.d.ts.map +1 -1
  173. package/dist/protocol/EASHelper.js +230 -37
  174. package/dist/protocol/EASHelper.js.map +1 -1
  175. package/dist/protocol/EscrowVault.d.ts +93 -2
  176. package/dist/protocol/EscrowVault.d.ts.map +1 -1
  177. package/dist/protocol/EscrowVault.js +122 -33
  178. package/dist/protocol/EscrowVault.js.map +1 -1
  179. package/dist/protocol/EventMonitor.d.ts +45 -1
  180. package/dist/protocol/EventMonitor.d.ts.map +1 -1
  181. package/dist/protocol/EventMonitor.js +64 -8
  182. package/dist/protocol/EventMonitor.js.map +1 -1
  183. package/dist/protocol/MessageSigner.d.ts +116 -2
  184. package/dist/protocol/MessageSigner.d.ts.map +1 -1
  185. package/dist/protocol/MessageSigner.js +215 -9
  186. package/dist/protocol/MessageSigner.js.map +1 -1
  187. package/dist/protocol/ProofGenerator.d.ts +93 -0
  188. package/dist/protocol/ProofGenerator.d.ts.map +1 -1
  189. package/dist/protocol/ProofGenerator.js +194 -9
  190. package/dist/protocol/ProofGenerator.js.map +1 -1
  191. package/dist/protocol/QuoteBuilder.d.ts +8 -0
  192. package/dist/protocol/QuoteBuilder.d.ts.map +1 -1
  193. package/dist/protocol/QuoteBuilder.js +8 -0
  194. package/dist/protocol/QuoteBuilder.js.map +1 -1
  195. package/dist/runtime/BlockchainRuntime.d.ts +360 -0
  196. package/dist/runtime/BlockchainRuntime.d.ts.map +1 -0
  197. package/dist/runtime/BlockchainRuntime.js +767 -0
  198. package/dist/runtime/BlockchainRuntime.js.map +1 -0
  199. package/dist/runtime/IACTPRuntime.d.ts +271 -0
  200. package/dist/runtime/IACTPRuntime.d.ts.map +1 -0
  201. package/dist/runtime/IACTPRuntime.js +15 -0
  202. package/dist/runtime/IACTPRuntime.js.map +1 -0
  203. package/dist/runtime/MockRuntime.d.ts +445 -0
  204. package/dist/runtime/MockRuntime.d.ts.map +1 -0
  205. package/dist/runtime/MockRuntime.js +1065 -0
  206. package/dist/runtime/MockRuntime.js.map +1 -0
  207. package/dist/runtime/MockStateManager.d.ts +233 -0
  208. package/dist/runtime/MockStateManager.d.ts.map +1 -0
  209. package/dist/runtime/MockStateManager.js +533 -0
  210. package/dist/runtime/MockStateManager.js.map +1 -0
  211. package/dist/runtime/index.d.ts +14 -0
  212. package/dist/runtime/index.d.ts.map +1 -0
  213. package/dist/runtime/index.js +42 -0
  214. package/dist/runtime/index.js.map +1 -0
  215. package/dist/runtime/types/MockState.d.ts +167 -0
  216. package/dist/runtime/types/MockState.d.ts.map +1 -0
  217. package/dist/runtime/types/MockState.js +43 -0
  218. package/dist/runtime/types/MockState.js.map +1 -0
  219. package/dist/types/agent.d.ts +76 -0
  220. package/dist/types/agent.d.ts.map +1 -0
  221. package/dist/types/agent.js +8 -0
  222. package/dist/types/agent.js.map +1 -0
  223. package/dist/types/did.d.ts +192 -0
  224. package/dist/types/did.d.ts.map +1 -0
  225. package/dist/types/did.js +38 -0
  226. package/dist/types/did.js.map +1 -0
  227. package/dist/types/eip712.d.ts +34 -0
  228. package/dist/types/eip712.d.ts.map +1 -1
  229. package/dist/types/eip712.js +31 -5
  230. package/dist/types/eip712.js.map +1 -1
  231. package/dist/types/escrow.d.ts +17 -10
  232. package/dist/types/escrow.d.ts.map +1 -1
  233. package/dist/types/index.d.ts +5 -0
  234. package/dist/types/index.d.ts.map +1 -1
  235. package/dist/types/index.js +8 -0
  236. package/dist/types/index.js.map +1 -1
  237. package/dist/types/message.d.ts +32 -0
  238. package/dist/types/message.d.ts.map +1 -1
  239. package/dist/types/message.js +4 -0
  240. package/dist/types/message.js.map +1 -1
  241. package/dist/types/state.d.ts +28 -0
  242. package/dist/types/state.d.ts.map +1 -1
  243. package/dist/types/state.js +37 -6
  244. package/dist/types/state.js.map +1 -1
  245. package/dist/types/transaction.d.ts +17 -0
  246. package/dist/types/transaction.d.ts.map +1 -1
  247. package/dist/utils/ErrorRecoveryGuide.d.ts +125 -0
  248. package/dist/utils/ErrorRecoveryGuide.d.ts.map +1 -0
  249. package/dist/utils/ErrorRecoveryGuide.js +579 -0
  250. package/dist/utils/ErrorRecoveryGuide.js.map +1 -0
  251. package/dist/utils/Helpers.d.ts +453 -0
  252. package/dist/utils/Helpers.d.ts.map +1 -0
  253. package/dist/utils/Helpers.js +623 -0
  254. package/dist/utils/Helpers.js.map +1 -0
  255. package/dist/utils/IPFSClient.d.ts +113 -0
  256. package/dist/utils/IPFSClient.d.ts.map +1 -1
  257. package/dist/utils/IPFSClient.js +128 -7
  258. package/dist/utils/IPFSClient.js.map +1 -1
  259. package/dist/utils/Logger.d.ts +195 -0
  260. package/dist/utils/Logger.d.ts.map +1 -0
  261. package/dist/utils/Logger.js +382 -0
  262. package/dist/utils/Logger.js.map +1 -0
  263. package/dist/utils/NonceManager.d.ts +234 -1
  264. package/dist/utils/NonceManager.d.ts.map +1 -1
  265. package/dist/utils/NonceManager.js +372 -7
  266. package/dist/utils/NonceManager.js.map +1 -1
  267. package/dist/utils/RateLimiter.d.ts +253 -0
  268. package/dist/utils/RateLimiter.d.ts.map +1 -0
  269. package/dist/utils/RateLimiter.js +424 -0
  270. package/dist/utils/RateLimiter.js.map +1 -0
  271. package/dist/utils/ReceivedNonceTracker.d.ts +175 -0
  272. package/dist/utils/ReceivedNonceTracker.d.ts.map +1 -1
  273. package/dist/utils/ReceivedNonceTracker.js +261 -5
  274. package/dist/utils/ReceivedNonceTracker.js.map +1 -1
  275. package/dist/utils/SDKLifecycle.d.ts +156 -0
  276. package/dist/utils/SDKLifecycle.d.ts.map +1 -0
  277. package/dist/utils/SDKLifecycle.js +347 -0
  278. package/dist/utils/SDKLifecycle.js.map +1 -0
  279. package/dist/utils/SecureNonce.d.ts +57 -0
  280. package/dist/utils/SecureNonce.d.ts.map +1 -0
  281. package/dist/utils/SecureNonce.js +80 -0
  282. package/dist/utils/SecureNonce.js.map +1 -0
  283. package/dist/utils/Semaphore.d.ts +123 -0
  284. package/dist/utils/Semaphore.d.ts.map +1 -0
  285. package/dist/utils/Semaphore.js +247 -0
  286. package/dist/utils/Semaphore.js.map +1 -0
  287. package/dist/utils/UsedAttestationTracker.d.ts +167 -0
  288. package/dist/utils/UsedAttestationTracker.d.ts.map +1 -0
  289. package/dist/utils/UsedAttestationTracker.js +309 -0
  290. package/dist/utils/UsedAttestationTracker.js.map +1 -0
  291. package/dist/utils/canonicalJson.d.ts +22 -0
  292. package/dist/utils/canonicalJson.d.ts.map +1 -1
  293. package/dist/utils/canonicalJson.js +26 -3
  294. package/dist/utils/canonicalJson.js.map +1 -1
  295. package/dist/utils/computeTypeHash.d.ts +14 -0
  296. package/dist/utils/computeTypeHash.d.ts.map +1 -1
  297. package/dist/utils/computeTypeHash.js +19 -2
  298. package/dist/utils/computeTypeHash.js.map +1 -1
  299. package/dist/utils/fsSafe.d.ts +14 -0
  300. package/dist/utils/fsSafe.d.ts.map +1 -0
  301. package/dist/utils/fsSafe.js +89 -0
  302. package/dist/utils/fsSafe.js.map +1 -0
  303. package/dist/utils/index.d.ts +15 -0
  304. package/dist/utils/index.d.ts.map +1 -0
  305. package/dist/utils/index.js +51 -0
  306. package/dist/utils/index.js.map +1 -0
  307. package/dist/utils/security.d.ts +147 -0
  308. package/dist/utils/security.d.ts.map +1 -0
  309. package/dist/utils/security.js +391 -0
  310. package/dist/utils/security.js.map +1 -0
  311. package/dist/utils/validation.d.ts +40 -0
  312. package/dist/utils/validation.d.ts.map +1 -1
  313. package/dist/utils/validation.js +184 -7
  314. package/dist/utils/validation.js.map +1 -1
  315. package/package.json +54 -37
  316. package/src/ACTPClient.ts +692 -178
  317. package/src/abi/AgentRegistry.json +782 -0
  318. package/src/abi/EscrowVault.json +106 -38
  319. package/src/abi/IdentityRegistry.json +316 -0
  320. package/src/adapters/BaseAdapter.ts +473 -0
  321. package/src/adapters/BeginnerAdapter.ts +232 -0
  322. package/src/adapters/IntermediateAdapter.ts +316 -0
  323. package/src/adapters/index.ts +25 -0
  324. package/src/builders/DeliveryProofBuilder.ts +3 -2
  325. package/src/cli/commands/balance.ts +110 -0
  326. package/src/cli/commands/batch.ts +487 -0
  327. package/src/cli/commands/config.ts +231 -0
  328. package/src/cli/commands/init.ts +161 -0
  329. package/src/cli/commands/mint.ts +116 -0
  330. package/src/cli/commands/pay.ts +113 -0
  331. package/src/cli/commands/simulate.ts +345 -0
  332. package/src/cli/commands/time.ts +303 -0
  333. package/src/cli/commands/tx.ts +448 -0
  334. package/src/cli/commands/watch.ts +211 -0
  335. package/src/cli/index.ts +116 -0
  336. package/src/cli/utils/client.ts +249 -0
  337. package/src/cli/utils/config.ts +282 -0
  338. package/src/cli/utils/output.ts +465 -0
  339. package/src/config/networks.ts +32 -9
  340. package/src/errors/index.ts +298 -1
  341. package/src/index.ts +207 -71
  342. package/src/level0/Provider.ts +117 -0
  343. package/src/level0/ServiceDirectory.ts +131 -0
  344. package/src/level0/index.ts +10 -0
  345. package/src/level0/provide.ts +131 -0
  346. package/src/level0/request.ts +494 -0
  347. package/src/level1/Agent.ts +1432 -0
  348. package/src/level1/index.ts +10 -0
  349. package/src/level1/pricing/PriceCalculator.ts +255 -0
  350. package/src/level1/pricing/PricingStrategy.ts +198 -0
  351. package/src/level1/types/Job.ts +179 -0
  352. package/src/level1/types/Options.ts +291 -0
  353. package/src/level1/types/index.ts +8 -0
  354. package/src/protocol/ACTPKernel.ts +175 -23
  355. package/src/protocol/AgentRegistry.ts +559 -0
  356. package/src/protocol/DIDManager.ts +629 -0
  357. package/src/protocol/DIDResolver.ts +554 -0
  358. package/src/protocol/EASHelper.ts +230 -46
  359. package/src/protocol/EscrowVault.ts +68 -50
  360. package/src/protocol/EventMonitor.ts +44 -15
  361. package/src/protocol/MessageSigner.ts +193 -13
  362. package/src/protocol/ProofGenerator.ts +223 -4
  363. package/src/runtime/BlockchainRuntime.ts +993 -0
  364. package/src/runtime/IACTPRuntime.ts +284 -0
  365. package/src/runtime/MockRuntime.ts +1244 -0
  366. package/src/runtime/MockStateManager.ts +576 -0
  367. package/src/runtime/index.ts +25 -0
  368. package/src/runtime/types/MockState.ts +227 -0
  369. package/src/types/agent.ts +79 -0
  370. package/src/types/did.ts +223 -0
  371. package/src/types/escrow.ts +12 -11
  372. package/src/types/index.ts +5 -1
  373. package/src/types/state.ts +12 -3
  374. package/src/types/transaction.ts +4 -1
  375. package/src/utils/ErrorRecoveryGuide.ts +675 -0
  376. package/src/utils/Helpers.ts +688 -0
  377. package/src/utils/IPFSClient.ts +122 -5
  378. package/src/utils/Logger.ts +484 -0
  379. package/src/utils/NonceManager.ts +305 -8
  380. package/src/utils/RateLimiter.ts +534 -0
  381. package/src/utils/ReceivedNonceTracker.ts +170 -0
  382. package/src/utils/SDKLifecycle.ts +416 -0
  383. package/src/utils/SecureNonce.ts +78 -0
  384. package/src/utils/Semaphore.ts +276 -0
  385. package/src/utils/UsedAttestationTracker.ts +387 -0
  386. package/src/utils/fsSafe.ts +75 -0
  387. package/src/utils/index.ts +80 -0
  388. package/src/utils/security.ts +418 -0
  389. package/src/utils/validation.ts +164 -0
  390. package/src/__tests__/ProofGenerator.test.ts +0 -124
  391. package/src/__tests__/QuoteBuilder.test.ts +0 -516
  392. package/src/__tests__/StateMachine.test.ts +0 -82
  393. package/src/__tests__/builders/DeliveryProofBuilder.test.ts +0 -581
  394. package/src/__tests__/integration/ACTPClient.test.ts +0 -263
  395. package/src/__tests__/integration.test.ts +0 -289
  396. package/src/__tests__/protocol/EASHelper.test.ts +0 -472
  397. package/src/__tests__/protocol/EventMonitor.test.ts +0 -382
  398. package/src/__tests__/security/ACTPKernel.security.test.ts +0 -1167
  399. package/src/__tests__/security/EscrowVault.security.test.ts +0 -570
  400. package/src/__tests__/security/MessageSigner.security.test.ts +0 -286
  401. package/src/__tests__/security/NonceReplay.security.test.ts +0 -501
  402. package/src/__tests__/security/validation.security.test.ts +0 -376
  403. package/src/__tests__/utils/IPFSClient.test.ts +0 -262
  404. package/src/__tests__/utils/NonceManager.test.ts +0 -205
  405. package/src/__tests__/utils/canonicalJson.test.ts +0 -153
@@ -0,0 +1,993 @@
1
+ /**
2
+ * BlockchainRuntime - Real blockchain implementation of ACTP protocol
3
+ *
4
+ * Implements IACTPRuntime interface using actual smart contracts deployed
5
+ * on Base Sepolia (testnet) or Base Mainnet (production).
6
+ *
7
+ * Features:
8
+ * - Real blockchain transactions via ethers.js
9
+ * - ACTPKernel smart contract integration
10
+ * - EscrowVault contract integration
11
+ * - EIP-712 message signing support
12
+ * - Event monitoring and indexing
13
+ * - Gas optimization
14
+ *
15
+ * @module runtime/BlockchainRuntime
16
+ */
17
+
18
+ import { ethers, Signer, JsonRpcProvider, keccak256, toUtf8Bytes } from 'ethers';
19
+ import { ACTPKernel } from '../protocol/ACTPKernel';
20
+ import { EscrowVault } from '../protocol/EscrowVault';
21
+ import { EventMonitor } from '../protocol/EventMonitor';
22
+ import { MessageSigner } from '../protocol/MessageSigner';
23
+ import { EASHelper, EASConfig } from '../protocol/EASHelper';
24
+ import { NetworkConfig, getNetwork } from '../config/networks';
25
+ import { IACTPRuntime, CreateTransactionParams } from './IACTPRuntime';
26
+ import { MockTransaction, TransactionState } from './types/MockState';
27
+ import { ValidationError } from '../errors';
28
+ import { ServiceHash, DisputeWindow } from '../utils/Helpers';
29
+ import { IUsedAttestationTracker, createUsedAttestationTracker } from '../utils/UsedAttestationTracker';
30
+ import { IReceivedNonceTracker, createReceivedNonceTracker } from '../utils/ReceivedNonceTracker';
31
+
32
+ /**
33
+ * Configuration for BlockchainRuntime
34
+ */
35
+ export interface BlockchainRuntimeConfig {
36
+ /** Network to connect to */
37
+ network: 'base-sepolia' | 'base-mainnet';
38
+ /** Ethers signer for transaction signing */
39
+ signer: Signer;
40
+ /** Ethers provider for blockchain queries */
41
+ provider: JsonRpcProvider;
42
+ /** Optional contract address overrides */
43
+ contracts?: {
44
+ actpKernel?: string;
45
+ escrowVault?: string;
46
+ usdc?: string;
47
+ eas?: string;
48
+ };
49
+ /** Optional gas settings */
50
+ gasSettings?: {
51
+ maxFeePerGas?: bigint;
52
+ maxPriorityFeePerGas?: bigint;
53
+ };
54
+ /** EAS (Ethereum Attestation Service) configuration for delivery proof verification */
55
+ easConfig?: EASConfig;
56
+ /**
57
+ * SECURITY FIX (CRITICAL-2): Require attestation verification before escrow release
58
+ * When true, releaseEscrow() will require a valid EAS attestation
59
+ * Default: false for backward compatibility, SHOULD be true in production
60
+ */
61
+ requireAttestation?: boolean;
62
+ /**
63
+ * State directory for persistent attestation tracking
64
+ * If provided, attestation replay protection will survive restarts
65
+ */
66
+ stateDirectory?: string;
67
+ }
68
+
69
+ /**
70
+ * BlockchainRuntime - Production blockchain implementation
71
+ *
72
+ * Bridges the IACTPRuntime interface to actual smart contracts.
73
+ * Provides seamless migration path from MockRuntime to production.
74
+ *
75
+ * @example
76
+ * ```typescript
77
+ * const provider = new ethers.JsonRpcProvider(rpcUrl);
78
+ * const signer = new ethers.Wallet(privateKey, provider);
79
+ *
80
+ * const runtime = new BlockchainRuntime({
81
+ * network: 'base-sepolia',
82
+ * signer,
83
+ * provider
84
+ * });
85
+ *
86
+ * // Now use with adapters
87
+ * const adapter = new BeginnerAdapter(runtime, requesterAddress);
88
+ * await adapter.createJob({...});
89
+ * ```
90
+ */
91
+ export class BlockchainRuntime implements IACTPRuntime {
92
+ private readonly kernel: ACTPKernel;
93
+ private readonly escrow: EscrowVault;
94
+ private readonly events: EventMonitor;
95
+ // SECURITY FIX (H-4): MessageSigner created via factory in initialize()
96
+ private messageSigner: MessageSigner | null = null;
97
+ // SECURITY FIX (CRITICAL-2): EAS helper for attestation verification
98
+ private easHelper: EASHelper | null = null;
99
+ // SECURITY FIX (HIGH-3): Attestation tracker for replay protection
100
+ private readonly attestationTracker: IUsedAttestationTracker;
101
+ // SECURITY FIX (CRITICAL-2): Flag to require attestation before release
102
+ private readonly requireAttestation: boolean;
103
+ // SECURITY FIX (MEDIUM-9): Nonce tracker for message replay protection
104
+ private readonly nonceTracker: IReceivedNonceTracker;
105
+ private readonly networkConfig: NetworkConfig;
106
+ private readonly provider: JsonRpcProvider;
107
+ private readonly signer: Signer;
108
+ private readonly easConfig?: EASConfig;
109
+
110
+ // SECURITY FIX (HIGH-3): Provider reconnection with exponential backoff
111
+ private reconnectAttempts = 0;
112
+ private readonly maxReconnectAttempts = 5;
113
+ private readonly baseReconnectDelay = 1000; // 1 second
114
+ private lastConnectionCheck = 0;
115
+ private readonly connectionCheckInterval = 30000; // 30 seconds
116
+
117
+ /**
118
+ * Create new BlockchainRuntime instance
119
+ *
120
+ * @param config - Runtime configuration
121
+ */
122
+ constructor(config: BlockchainRuntimeConfig) {
123
+ this.provider = config.provider;
124
+ this.signer = config.signer;
125
+
126
+ // Get network configuration
127
+ this.networkConfig = getNetwork(config.network);
128
+
129
+ // Apply contract address overrides if provided
130
+ if (config.contracts) {
131
+ this.networkConfig = {
132
+ ...this.networkConfig,
133
+ contracts: {
134
+ ...this.networkConfig.contracts,
135
+ ...config.contracts,
136
+ },
137
+ };
138
+ }
139
+
140
+ // NOTE (GAS DEFAULTS):
141
+ // We intentionally do NOT force default maxFee/maxPriority caps unless the caller
142
+ // explicitly provides gasSettings. Hardcoded caps can cause "insufficient funds for
143
+ // intrinsic transaction cost" even when the wallet has enough ETH for the *actual*
144
+ // network fee (ethers uses maxFee * gasLimit for the balance check).
145
+
146
+ // SECURITY FIX (CRITICAL-2): Store EAS config for initialization
147
+ this.easConfig = config.easConfig;
148
+
149
+ // SECURITY FIX (CRITICAL-2): Default to NOT requiring attestation for backward compatibility
150
+ // Production deployments SHOULD set this to true
151
+ this.requireAttestation = config.requireAttestation ?? false;
152
+
153
+ // SECURITY FIX (HIGH-3): Create attestation tracker with optional persistence
154
+ // If stateDirectory is provided, attestations survive process restarts
155
+ this.attestationTracker = createUsedAttestationTracker(config.stateDirectory);
156
+
157
+ // SECURITY FIX (MEDIUM-9): Create nonce tracker for message replay protection
158
+ // Uses memory-efficient strategy (tracks highest nonce per sender+type)
159
+ this.nonceTracker = createReceivedNonceTracker('memory-efficient');
160
+
161
+ // Initialize protocol modules
162
+ this.kernel = new ACTPKernel(
163
+ this.networkConfig.contracts.actpKernel,
164
+ this.signer,
165
+ config.gasSettings
166
+ );
167
+
168
+ this.escrow = new EscrowVault(
169
+ this.networkConfig.contracts.escrowVault,
170
+ this.signer,
171
+ config.gasSettings
172
+ );
173
+
174
+ // SECURITY FIX (C-3): Use public getters instead of private field access
175
+ this.events = new EventMonitor(
176
+ this.kernel.getContract(),
177
+ this.escrow.getContract()
178
+ );
179
+
180
+ // SECURITY FIX (H-4): MessageSigner is created in initialize() using factory pattern
181
+ // This ensures EIP-712 domain is always properly initialized before use
182
+ }
183
+
184
+ /**
185
+ * Initialize async components (must be called after construction)
186
+ *
187
+ * CRITICAL: This method MUST be called before using the runtime.
188
+ * It initializes the MessageSigner with proper EIP-712 domain and
189
+ * optionally the EASHelper for attestation verification.
190
+ *
191
+ * SECURITY FIX (CHAINID-VALIDATION): Validates that the connected network
192
+ * matches the expected network configuration to prevent cross-chain attacks.
193
+ *
194
+ * @example
195
+ * ```typescript
196
+ * const runtime = new BlockchainRuntime(config);
197
+ * await runtime.initialize();
198
+ * ```
199
+ */
200
+ async initialize(): Promise<void> {
201
+ // SECURITY FIX (CHAINID-VALIDATION): Verify connected network matches config
202
+ // This prevents:
203
+ // 1. Cross-chain replay attacks (signing for one chain, replaying on another)
204
+ // 2. Misconfigured RPC endpoints (connecting to wrong network)
205
+ // 3. Man-in-the-middle RPC attacks (redirected to wrong chain)
206
+ try {
207
+ const network = await this.provider.getNetwork();
208
+ const connectedChainId = Number(network.chainId);
209
+ const expectedChainId = this.networkConfig.chainId;
210
+
211
+ if (connectedChainId !== expectedChainId) {
212
+ throw new Error(
213
+ `Network mismatch: Connected to chainId ${connectedChainId}, ` +
214
+ `but expected ${expectedChainId} (${this.networkConfig.name}). ` +
215
+ `This could indicate a misconfigured RPC endpoint or cross-chain attack. ` +
216
+ `Please verify your RPC URL points to the correct network.`
217
+ );
218
+ }
219
+
220
+ console.info(
221
+ `BlockchainRuntime: Connected to ${this.networkConfig.name} (chainId: ${connectedChainId})`
222
+ );
223
+ } catch (error) {
224
+ if (error instanceof Error && error.message.includes('Network mismatch')) {
225
+ throw error; // Re-throw our validation error
226
+ }
227
+ // For other errors (e.g., network issues), log warning but continue
228
+ // This allows initialization to proceed even if network check fails temporarily
229
+ console.warn(
230
+ `BlockchainRuntime: Could not verify network chainId. ` +
231
+ `Error: ${error instanceof Error ? error.message : String(error)}. ` +
232
+ `Proceeding with expected chainId ${this.networkConfig.chainId}.`
233
+ );
234
+ }
235
+
236
+ // SECURITY FIX (H-4): Use factory pattern to guarantee domain initialization
237
+ // This prevents runtime errors from uninitialized domain
238
+ // SECURITY FIX (MEDIUM-9): Wire nonce tracker for message replay protection
239
+ this.messageSigner = await MessageSigner.create(
240
+ this.signer,
241
+ this.networkConfig.contracts.actpKernel,
242
+ {
243
+ chainId: this.networkConfig.chainId,
244
+ nonceTracker: this.nonceTracker,
245
+ }
246
+ );
247
+
248
+ // SECURITY FIX (CRITICAL-2): Initialize EAS helper if config provided
249
+ // This enables attestation verification for escrow release
250
+ if (this.easConfig) {
251
+ this.easHelper = new EASHelper(
252
+ this.signer,
253
+ this.easConfig,
254
+ this.attestationTracker
255
+ );
256
+ } else if (this.requireAttestation) {
257
+ console.warn(
258
+ '[SECURITY WARNING] BlockchainRuntime: requireAttestation is true but no EAS config provided. ' +
259
+ 'Attestation verification will fail. Please provide easConfig in BlockchainRuntimeConfig.'
260
+ );
261
+ }
262
+ }
263
+
264
+ /**
265
+ * Check if runtime has been initialized
266
+ * @returns true if initialize() has been called
267
+ */
268
+ isInitialized(): boolean {
269
+ return this.messageSigner !== null;
270
+ }
271
+
272
+ /**
273
+ * Require initialization before use
274
+ *
275
+ * SECURITY FIX (M-4): Enforces initialize() call before operations
276
+ * @throws Error if initialize() has not been called
277
+ */
278
+ private requireInitialized(): void {
279
+ if (!this.messageSigner) {
280
+ throw new Error(
281
+ 'BlockchainRuntime not initialized. Call initialize() before using any methods. ' +
282
+ 'This ensures proper EIP-712 domain setup and prevents runtime errors.'
283
+ );
284
+ }
285
+ }
286
+
287
+ /**
288
+ * Ensure provider connection is healthy with automatic reconnection
289
+ *
290
+ * SECURITY FIX (HIGH-3): Implements exponential backoff reconnection
291
+ * to handle transient network failures gracefully.
292
+ *
293
+ * SECURITY FIX (H-4): Converted from recursive to iterative loop
294
+ * to prevent stack overflow on prolonged network failures.
295
+ *
296
+ * @throws Error if connection cannot be established after max attempts
297
+ */
298
+ private async ensureConnected(): Promise<void> {
299
+ const now = Date.now();
300
+
301
+ // Skip check if we recently verified connection
302
+ if (now - this.lastConnectionCheck < this.connectionCheckInterval) {
303
+ return;
304
+ }
305
+
306
+ // SECURITY FIX (H-4): Iterative loop instead of recursion (prevents stack overflow)
307
+ for (let attempt = 0; attempt <= this.maxReconnectAttempts; attempt++) {
308
+ try {
309
+ // Test connection with a simple call
310
+ await this.provider.getNetwork();
311
+
312
+ // Connection successful
313
+ this.reconnectAttempts = 0;
314
+ this.lastConnectionCheck = now;
315
+ return; // Exit successfully
316
+ } catch (error) {
317
+ if (attempt < this.maxReconnectAttempts) {
318
+ // Not the last attempt - retry with exponential backoff
319
+ this.reconnectAttempts = attempt + 1;
320
+ const delay = this.baseReconnectDelay * Math.pow(2, attempt);
321
+
322
+ console.warn(
323
+ `Provider connection lost. Attempting reconnection ${attempt + 1}/${this.maxReconnectAttempts} ` +
324
+ `after ${delay}ms delay... ` +
325
+ `(Error: ${error instanceof Error ? error.message : String(error)})`
326
+ );
327
+
328
+ // Wait before next attempt
329
+ await new Promise(resolve => setTimeout(resolve, delay));
330
+ } else {
331
+ // Last attempt failed - throw error
332
+ throw new Error(
333
+ `Provider connection lost after ${this.maxReconnectAttempts} reconnection attempts. ` +
334
+ `Last error: ${error instanceof Error ? error.message : String(error)}. ` +
335
+ `Please check your network connectivity and RPC endpoint.`
336
+ );
337
+ }
338
+ }
339
+ }
340
+ }
341
+
342
+ /**
343
+ * Get provider connection status
344
+ *
345
+ * SECURITY FIX (HIGH-3): Monitoring method for connection health
346
+ *
347
+ * @returns Connection status information
348
+ */
349
+ getConnectionStatus(): {
350
+ isHealthy: boolean;
351
+ reconnectAttempts: number;
352
+ maxReconnectAttempts: number;
353
+ lastCheckTimestamp: number;
354
+ } {
355
+ return {
356
+ isHealthy: this.reconnectAttempts === 0,
357
+ reconnectAttempts: this.reconnectAttempts,
358
+ maxReconnectAttempts: this.maxReconnectAttempts,
359
+ lastCheckTimestamp: this.lastConnectionCheck,
360
+ };
361
+ }
362
+
363
+ /**
364
+ * Creates a new transaction on-chain
365
+ *
366
+ * @param params - Transaction creation parameters
367
+ * @returns Promise resolving to transaction ID (bytes32 hex string)
368
+ */
369
+ async createTransaction(params: CreateTransactionParams): Promise<string> {
370
+ // SECURITY FIX (M-4): Enforce initialization
371
+ this.requireInitialized();
372
+
373
+ // SECURITY FIX (HIGH-3): Ensure provider connection before transaction
374
+ await this.ensureConnected();
375
+
376
+ // Validate parameters
377
+ if (!params.provider || !ethers.isAddress(params.provider)) {
378
+ throw new ValidationError('provider', 'Invalid provider address');
379
+ }
380
+ if (!params.requester || !ethers.isAddress(params.requester)) {
381
+ throw new ValidationError('requester', 'Invalid requester address');
382
+ }
383
+ if (BigInt(params.amount) <= 0n) {
384
+ throw new ValidationError('amount', 'Amount must be positive');
385
+ }
386
+
387
+ const now = Math.floor(Date.now() / 1000);
388
+ if (params.deadline <= now) {
389
+ throw new ValidationError('deadline', 'Deadline must be in the future');
390
+ }
391
+
392
+ // Call ACTPKernel contract
393
+ const txId = await this.kernel.createTransaction({
394
+ provider: params.provider,
395
+ requester: params.requester,
396
+ amount: BigInt(params.amount),
397
+ deadline: params.deadline,
398
+ disputeWindow: params.disputeWindow || 172800, // Default 2 days
399
+ // SECURITY FIX (CRITICAL): serviceDescription should be a bytes32 hash
400
+ // If caller passes raw string, it will fail on-chain. Basic/Standard API now hash before calling.
401
+ metadata: this.validateServiceHash(params.serviceDescription),
402
+ });
403
+
404
+ return txId;
405
+ }
406
+
407
+ /**
408
+ * Links escrow to a transaction and locks funds
409
+ *
410
+ * SIMPLIFICATION (ESCROW-ID): Uses txId as escrowId.
411
+ * Per ACTP standard, escrowId = txId simplifies tracking and eliminates
412
+ * the need for separate escrowId→txId mapping.
413
+ *
414
+ * @param txId - Transaction ID
415
+ * @param amount - Amount to lock (must match transaction amount)
416
+ * @returns Promise resolving to escrow ID (same as txId)
417
+ */
418
+ async linkEscrow(txId: string, amount: string): Promise<string> {
419
+ // SECURITY FIX (M-4): Enforce initialization
420
+ this.requireInitialized();
421
+
422
+ // SECURITY FIX (HIGH-3): Ensure provider connection before transaction
423
+ await this.ensureConnected();
424
+
425
+ // Validate transaction exists and get details
426
+ const tx = await this.getTransaction(txId);
427
+ if (!tx) {
428
+ throw new Error(`Transaction not found: ${txId}`);
429
+ }
430
+
431
+ // Validate state is INITIATED or QUOTED
432
+ if (tx.state !== 'INITIATED' && tx.state !== 'QUOTED') {
433
+ throw new Error(
434
+ `Cannot link escrow in current state ${tx.state}. Must be INITIATED or QUOTED.`
435
+ );
436
+ }
437
+
438
+ // Validate amount matches transaction
439
+ if (amount !== tx.amount) {
440
+ throw new ValidationError('amount', 'Amount must match transaction amount');
441
+ }
442
+
443
+ // Approve USDC to escrow vault
444
+ await this.escrow.approveToken(this.networkConfig.contracts.usdc, BigInt(amount));
445
+
446
+ // SIMPLIFICATION (ESCROW-ID): Use txId as escrowId
447
+ // This aligns with ACTP standard where escrowId = txId
448
+ // Benefits: No mapping needed, simpler tracking, direct correlation
449
+ const escrowId = txId;
450
+
451
+ // Link escrow to transaction
452
+ await this.kernel.linkEscrow(txId, this.networkConfig.contracts.escrowVault, escrowId);
453
+
454
+ return escrowId;
455
+ }
456
+
457
+ /**
458
+ * Transitions a transaction to a new state
459
+ *
460
+ * SECURITY FIX (PROOF-PARAM): Added optional proof parameter for DELIVERED state.
461
+ * The kernel contract uses proof data for dispute window configuration and
462
+ * delivery verification. Without proof, default dispute window applies.
463
+ *
464
+ * @param txId - Transaction ID
465
+ * @param newState - Target state
466
+ * @param proof - Optional proof data (hex string, e.g., ABI-encoded delivery proof)
467
+ */
468
+ async transitionState(txId: string, newState: TransactionState, proof?: string): Promise<void> {
469
+ // SECURITY FIX (M-4): Enforce initialization
470
+ this.requireInitialized();
471
+
472
+ // SECURITY FIX (HIGH-3): Ensure provider connection before transaction
473
+ await this.ensureConnected();
474
+
475
+ // Map TransactionState string to State enum value
476
+ const stateMap: Record<TransactionState, number> = {
477
+ INITIATED: 0,
478
+ QUOTED: 1,
479
+ COMMITTED: 2,
480
+ IN_PROGRESS: 3,
481
+ DELIVERED: 4,
482
+ SETTLED: 5,
483
+ DISPUTED: 6,
484
+ CANCELLED: 7,
485
+ };
486
+
487
+ const stateValue = stateMap[newState];
488
+ if (stateValue === undefined) {
489
+ throw new ValidationError('state', `Invalid state: ${newState}`);
490
+ }
491
+
492
+ // SECURITY FIX (PROOF-PARAM): Pass proof to kernel if provided
493
+ // Default to empty bytes (0x) if no proof provided
494
+ const proofBytes = proof || '0x';
495
+ await this.kernel.transitionState(txId, stateValue, proofBytes);
496
+ }
497
+
498
+ /**
499
+ * Gets a transaction by ID
500
+ *
501
+ * @param txId - Transaction ID
502
+ * @returns Promise resolving to transaction or null if not found
503
+ */
504
+ async getTransaction(txId: string): Promise<MockTransaction | null> {
505
+ try {
506
+ const tx = await this.kernel.getTransaction(txId);
507
+
508
+ // Check if transaction exists (zero address = not found)
509
+ if (tx.requester === ethers.ZeroAddress) {
510
+ return null;
511
+ }
512
+
513
+ // Map blockchain transaction to MockTransaction format
514
+ const stateMap: Record<number, TransactionState> = {
515
+ 0: 'INITIATED',
516
+ 1: 'QUOTED',
517
+ 2: 'COMMITTED',
518
+ 3: 'IN_PROGRESS',
519
+ 4: 'DELIVERED',
520
+ 5: 'SETTLED',
521
+ 6: 'DISPUTED',
522
+ 7: 'CANCELLED',
523
+ };
524
+
525
+ // SECURITY FIX (H-2): Throw error for unknown states instead of silent fallback
526
+ const mappedState = stateMap[tx.state];
527
+ if (mappedState === undefined) {
528
+ throw new Error(
529
+ `Unknown transaction state: ${tx.state}. ` +
530
+ `Valid states are 0-7 (INITIATED through CANCELLED). ` +
531
+ `This may indicate a contract version mismatch.`
532
+ );
533
+ }
534
+
535
+ return {
536
+ id: txId,
537
+ provider: tx.provider,
538
+ requester: tx.requester,
539
+ amount: tx.amount.toString(),
540
+ state: mappedState,
541
+ deadline: Number(tx.deadline),
542
+ disputeWindow: tx.disputeWindow !== undefined ? Number(tx.disputeWindow) : 172800, // Default 2 days
543
+ escrowId: tx.escrowId,
544
+ createdAt: Number(tx.createdAt),
545
+ updatedAt: Number(tx.updatedAt),
546
+ completedAt: 0, // V2: Track via DELIVERED event timestamp
547
+ serviceDescription: '', // V2: Decode from on-chain serviceHash
548
+ deliveryProof: '', // V2: Fetch from EAS attestation
549
+ events: [], // V2: Populate via EventMonitor.getTransactionEvents()
550
+ };
551
+ } catch (error) {
552
+ // If contract call fails, return null
553
+ return null;
554
+ }
555
+ }
556
+
557
+ /**
558
+ * Gets all transactions
559
+ *
560
+ * @returns Promise resolving to array of all transactions
561
+ */
562
+ async getAllTransactions(): Promise<MockTransaction[]> {
563
+ // V2: Implement event-based transaction indexing via EventMonitor
564
+ // For now, return empty array as this requires off-chain indexer
565
+ console.warn(
566
+ 'getAllTransactions() not fully implemented for BlockchainRuntime. Use EventMonitor for event-based queries.'
567
+ );
568
+ return [];
569
+ }
570
+
571
+ /**
572
+ * Releases escrow funds to provider by settling the transaction
573
+ *
574
+ * SECURITY FIX (CRITICAL-2): This method now validates:
575
+ * 1. Transaction state is DELIVERED
576
+ * 2. Dispute window has elapsed
577
+ * 3. EAS attestation is valid (if requireAttestation is true)
578
+ *
579
+ * SECURITY FIX (SETTLEMENT-FLOW): Uses transitionState(SETTLED) instead of
580
+ * direct releaseEscrow() call. Per ACTPKernel.sol, settlement via state transition
581
+ * automatically handles escrow release through _releaseEscrow() internal call.
582
+ * This ensures proper state machine progression and event emission.
583
+ *
584
+ * SIMPLIFICATION (ESCROW-ID): Uses escrowId = txId standard.
585
+ * The on-chain contract uses txId as the escrow identifier, so we simply
586
+ * treat escrowId and txId as equivalent (no complex parsing needed).
587
+ *
588
+ * @param escrowId - Escrow ID (equivalent to txId in ACTP standard)
589
+ * @param attestationUID - Optional EAS attestation UID for verification
590
+ * @throws Error if transaction not found, not in DELIVERED state, or attestation invalid
591
+ */
592
+ async releaseEscrow(escrowId: string, attestationUID?: string): Promise<void> {
593
+ // SECURITY FIX (M-4): Enforce initialization
594
+ this.requireInitialized();
595
+
596
+ // SECURITY FIX (HIGH-3): Ensure provider connection before transaction
597
+ await this.ensureConnected();
598
+
599
+ // SIMPLIFICATION (ESCROW-ID): escrowId = txId standard
600
+ // On-chain, escrowId IS the txId. No need for complex parsing.
601
+ // Support legacy format "escrow-{txId}-{timestamp}" for backward compatibility
602
+ let txId: string;
603
+ const legacyMatch = escrowId.match(/^escrow-(.+)-\d+$/);
604
+ if (legacyMatch) {
605
+ // Legacy SDK format - extract txId
606
+ txId = legacyMatch[1];
607
+ console.warn(
608
+ `BlockchainRuntime.releaseEscrow: Using legacy escrowId format. ` +
609
+ `Please update to use txId directly as escrowId.`
610
+ );
611
+ } else {
612
+ // Standard: escrowId = txId
613
+ txId = escrowId;
614
+ }
615
+
616
+ // SECURITY FIX (MEDIUM-1): Fetch transaction and validate state
617
+ const tx = await this.getTransaction(txId);
618
+ if (!tx) {
619
+ throw new Error(`Transaction not found: ${txId}`);
620
+ }
621
+
622
+ // SECURITY FIX (MEDIUM-1): Validate transaction is in DELIVERED state
623
+ if (tx.state !== 'DELIVERED') {
624
+ throw new Error(
625
+ `Cannot release escrow: transaction ${txId} is in state ${tx.state}, expected DELIVERED. ` +
626
+ `Escrow can only be released after delivery is confirmed.`
627
+ );
628
+ }
629
+
630
+ // SECURITY FIX (MEDIUM-1): Validate dispute window has elapsed
631
+ if (tx.completedAt && tx.disputeWindow) {
632
+ if (DisputeWindow.isActive(tx.completedAt, tx.disputeWindow)) {
633
+ const remaining = DisputeWindow.remaining(tx.completedAt, tx.disputeWindow);
634
+ throw new Error(
635
+ `Cannot release escrow: dispute window still active for transaction ${txId}. ` +
636
+ `Window expires in ${remaining} seconds. ` +
637
+ `Wait for dispute window to close before releasing funds.`
638
+ );
639
+ }
640
+ }
641
+
642
+ // SECURITY FIX (CRITICAL-2): Verify EAS attestation if required
643
+ if (this.requireAttestation) {
644
+ if (!attestationUID) {
645
+ throw new Error(
646
+ `Cannot release escrow: attestation verification is required but no attestationUID provided. ` +
647
+ `Call releaseEscrow(escrowId, attestationUID) with a valid EAS attestation UID.`
648
+ );
649
+ }
650
+
651
+ if (!this.easHelper) {
652
+ throw new Error(
653
+ `Cannot release escrow: attestation verification is required but EAS helper not initialized. ` +
654
+ `Provide easConfig in BlockchainRuntimeConfig and call initialize().`
655
+ );
656
+ }
657
+
658
+ // Verify attestation is valid for this transaction
659
+ try {
660
+ await this.easHelper.verifyAndRecordForRelease(txId, attestationUID);
661
+ console.info(
662
+ `BlockchainRuntime.releaseEscrow: Attestation ${attestationUID} verified for transaction ${txId}.`
663
+ );
664
+ } catch (error) {
665
+ throw new Error(
666
+ `Cannot release escrow: attestation verification failed for transaction ${txId}. ` +
667
+ `Error: ${error instanceof Error ? error.message : String(error)}`
668
+ );
669
+ }
670
+ } else if (attestationUID && this.easHelper) {
671
+ // Even if not required, verify attestation if provided (best effort)
672
+ try {
673
+ await this.easHelper.verifyAndRecordForRelease(txId, attestationUID);
674
+ console.info(
675
+ `BlockchainRuntime.releaseEscrow: Attestation ${attestationUID} verified (optional) for transaction ${txId}.`
676
+ );
677
+ } catch (error) {
678
+ console.warn(
679
+ `BlockchainRuntime.releaseEscrow: Attestation verification failed but not required. ` +
680
+ `Proceeding with release. Error: ${error instanceof Error ? error.message : String(error)}`
681
+ );
682
+ }
683
+ } else {
684
+ // No attestation verification
685
+ console.info(
686
+ `BlockchainRuntime.releaseEscrow: Settling transaction ${txId}. ` +
687
+ `Note: Set requireAttestation=true and provide easConfig for additional security.`
688
+ );
689
+ }
690
+
691
+ // SECURITY FIX (SETTLEMENT-FLOW): Use transitionState(SETTLED) instead of releaseEscrow()
692
+ // Per ACTPKernel.sol, the settlement flow is:
693
+ // transitionState(txId, SETTLED, proof) → internally calls _releaseEscrow(txn)
694
+ // This ensures proper state machine progression and emits correct events.
695
+ // Direct kernel.releaseEscrow() may not properly update transaction state.
696
+ await this.kernel.transitionState(txId, 5); // 5 = State.SETTLED
697
+ }
698
+
699
+ /**
700
+ * Gets escrow balance
701
+ *
702
+ * MEDIUM: Returns the locked balance for a transaction from the escrow vault.
703
+ * Queries the EscrowVault contract for the actual balance.
704
+ *
705
+ * @param escrowId - Escrow ID or transaction ID
706
+ * @returns Promise resolving to balance as string (in USDC wei)
707
+ */
708
+ async getEscrowBalance(escrowId: string): Promise<string> {
709
+ // SECURITY FIX (M-4): Enforce initialization
710
+ this.requireInitialized();
711
+
712
+ try {
713
+ // Try to get balance from escrow vault
714
+ // The escrow vault tracks balances by transaction ID
715
+ const match = escrowId.match(/^escrow-(.+)-\d+$/);
716
+ const txId = match ? match[1] : escrowId;
717
+
718
+ // Query the transaction to get the locked amount
719
+ const tx = await this.getTransaction(txId);
720
+ if (!tx) {
721
+ return '0';
722
+ }
723
+
724
+ // If transaction is in an active state (COMMITTED, IN_PROGRESS, DELIVERED),
725
+ // the escrow balance is the transaction amount
726
+ if (tx.state === 'COMMITTED' || tx.state === 'IN_PROGRESS' || tx.state === 'DELIVERED') {
727
+ return tx.amount;
728
+ }
729
+
730
+ // For settled or cancelled transactions, escrow is released
731
+ return '0';
732
+ } catch (error) {
733
+ // If query fails, return 0
734
+ console.warn('BlockchainRuntime.getEscrowBalance: Query failed', error);
735
+ return '0';
736
+ }
737
+ }
738
+
739
+ /**
740
+ * Time interface (uses real blockchain time)
741
+ */
742
+ public readonly time = {
743
+ /**
744
+ * Get current blockchain timestamp
745
+ */
746
+ now: (): number => {
747
+ return Math.floor(Date.now() / 1000);
748
+ },
749
+ };
750
+
751
+ // ============================================================================
752
+ // Utility Methods (Not in IACTPRuntime but useful for blockchain runtime)
753
+ // ============================================================================
754
+
755
+ /**
756
+ * Get the current signer address
757
+ */
758
+ async getAddress(): Promise<string> {
759
+ return await this.signer.getAddress();
760
+ }
761
+
762
+ /**
763
+ * Get current block number
764
+ */
765
+ async getBlockNumber(): Promise<number> {
766
+ return await this.provider.getBlockNumber();
767
+ }
768
+
769
+ /**
770
+ * Get network configuration
771
+ */
772
+ getNetworkConfig(): NetworkConfig {
773
+ return this.networkConfig;
774
+ }
775
+
776
+ /**
777
+ * Get ACTPKernel instance (for advanced usage)
778
+ */
779
+ getKernel(): ACTPKernel {
780
+ return this.kernel;
781
+ }
782
+
783
+ /**
784
+ * Get EscrowVault instance (for advanced usage)
785
+ */
786
+ getEscrow(): EscrowVault {
787
+ return this.escrow;
788
+ }
789
+
790
+ /**
791
+ * Get EventMonitor instance (for advanced usage)
792
+ */
793
+ getEvents(): EventMonitor {
794
+ return this.events;
795
+ }
796
+
797
+ /**
798
+ * Get MessageSigner instance (for advanced usage)
799
+ *
800
+ * @throws Error if initialize() has not been called
801
+ */
802
+ getMessageSigner(): MessageSigner {
803
+ if (!this.messageSigner) {
804
+ throw new Error(
805
+ 'BlockchainRuntime not initialized. Call initialize() before using MessageSigner. ' +
806
+ 'This is required for proper EIP-712 domain setup.'
807
+ );
808
+ }
809
+ return this.messageSigner;
810
+ }
811
+
812
+ /**
813
+ * Get EASHelper instance (for attestation operations)
814
+ *
815
+ * @throws Error if EAS config not provided or initialize() not called
816
+ */
817
+ getEASHelper(): EASHelper {
818
+ if (!this.easHelper) {
819
+ throw new Error(
820
+ 'EASHelper not initialized. Provide easConfig in BlockchainRuntimeConfig and call initialize().'
821
+ );
822
+ }
823
+ return this.easHelper;
824
+ }
825
+
826
+ /**
827
+ * Get attestation tracker instance
828
+ */
829
+ getAttestationTracker(): IUsedAttestationTracker {
830
+ return this.attestationTracker;
831
+ }
832
+
833
+ /**
834
+ * Get nonce tracker instance (for monitoring/debugging)
835
+ *
836
+ * SECURITY FIX (MEDIUM-9): Exposed for monitoring nonce replay protection
837
+ */
838
+ getNonceTracker(): IReceivedNonceTracker {
839
+ return this.nonceTracker;
840
+ }
841
+
842
+ /**
843
+ * Check if attestation verification is required
844
+ */
845
+ isAttestationRequired(): boolean {
846
+ return this.requireAttestation;
847
+ }
848
+
849
+ /**
850
+ * Validate and normalize service hash for on-chain storage
851
+ *
852
+ * SECURITY FIX (CRITICAL): ACTPKernel expects bytes32 serviceHash.
853
+ * This method validates format and hashes raw strings if needed.
854
+ *
855
+ * @param serviceDescription - Service hash or description string
856
+ * @returns Valid bytes32 hash
857
+ */
858
+ private validateServiceHash(serviceDescription?: string): string {
859
+ const ZERO_HASH = '0x0000000000000000000000000000000000000000000000000000000000000000';
860
+
861
+ if (!serviceDescription) {
862
+ return ZERO_HASH;
863
+ }
864
+
865
+ // If already a valid bytes32 hash, use it directly
866
+ if (ServiceHash.isValidHash(serviceDescription)) {
867
+ return serviceDescription;
868
+ }
869
+
870
+ // SECURITY FIX (CRITICAL): If it's a raw string (legacy format), hash it
871
+ // This ensures on-chain compatibility with the contract's bytes32 expectation
872
+ console.warn(
873
+ 'BlockchainRuntime: serviceDescription is not a valid bytes32 hash. ' +
874
+ 'Hashing it now. For best practice, use ServiceHash.hash() before calling createTransaction.'
875
+ );
876
+
877
+ return keccak256(toUtf8Bytes(serviceDescription));
878
+ }
879
+
880
+ // ============================================================================
881
+ // Gas Estimation (M-2)
882
+ // ============================================================================
883
+
884
+ /**
885
+ * Estimate gas for createTransaction operation
886
+ *
887
+ * SECURITY FIX (M-2): Pre-transaction gas estimation helps:
888
+ * - Prevent failed transactions due to insufficient gas
889
+ * - Allow users to make informed decisions about costs
890
+ * - Catch potential issues before spending gas
891
+ *
892
+ * @param params - Transaction parameters
893
+ * @returns Estimated gas limit and cost in wei
894
+ */
895
+ async estimateCreateTransactionGas(params: CreateTransactionParams): Promise<{
896
+ gasLimit: bigint;
897
+ gasCostWei: bigint;
898
+ gasCostGwei: string;
899
+ }> {
900
+ // Get current gas price
901
+ const feeData = await this.provider.getFeeData();
902
+ const gasPrice = feeData.gasPrice ?? 0n;
903
+
904
+ // V2: Use kernel.estimateGas.createTransaction() for precise estimation
905
+ // Current: Conservative estimate based on typical createTransaction costs
906
+ const estimatedGasLimit = 150000n;
907
+
908
+ const gasCostWei = estimatedGasLimit * gasPrice;
909
+ const gasCostGwei = (Number(gasCostWei) / 1e9).toFixed(4);
910
+
911
+ return {
912
+ gasLimit: estimatedGasLimit,
913
+ gasCostWei,
914
+ gasCostGwei,
915
+ };
916
+ }
917
+
918
+ /**
919
+ * Estimate gas for linkEscrow operation
920
+ *
921
+ * @param txId - Transaction ID
922
+ * @returns Estimated gas limit and cost
923
+ */
924
+ async estimateLinkEscrowGas(txId: string): Promise<{
925
+ gasLimit: bigint;
926
+ gasCostWei: bigint;
927
+ gasCostGwei: string;
928
+ }> {
929
+ const feeData = await this.provider.getFeeData();
930
+ const gasPrice = feeData.gasPrice ?? 0n;
931
+
932
+ // linkEscrow includes USDC approve + contract call
933
+ const estimatedGasLimit = 200000n; // Conservative estimate
934
+
935
+ const gasCostWei = estimatedGasLimit * gasPrice;
936
+ const gasCostGwei = (Number(gasCostWei) / 1e9).toFixed(4);
937
+
938
+ return {
939
+ gasLimit: estimatedGasLimit,
940
+ gasCostWei,
941
+ gasCostGwei,
942
+ };
943
+ }
944
+
945
+ /**
946
+ * Estimate gas for state transition
947
+ *
948
+ * @param txId - Transaction ID
949
+ * @param newState - Target state
950
+ * @returns Estimated gas limit and cost
951
+ */
952
+ async estimateTransitionGas(txId: string, newState: string): Promise<{
953
+ gasLimit: bigint;
954
+ gasCostWei: bigint;
955
+ gasCostGwei: string;
956
+ }> {
957
+ const feeData = await this.provider.getFeeData();
958
+ const gasPrice = feeData.gasPrice ?? 0n;
959
+
960
+ // State transitions are relatively cheap
961
+ const estimatedGasLimit = 80000n; // Conservative estimate
962
+
963
+ const gasCostWei = estimatedGasLimit * gasPrice;
964
+ const gasCostGwei = (Number(gasCostWei) / 1e9).toFixed(4);
965
+
966
+ return {
967
+ gasLimit: estimatedGasLimit,
968
+ gasCostWei,
969
+ gasCostGwei,
970
+ };
971
+ }
972
+
973
+ /**
974
+ * Get current gas price information
975
+ *
976
+ * @returns Current gas price data
977
+ */
978
+ async getGasPrice(): Promise<{
979
+ gasPrice: bigint;
980
+ gasPriceGwei: string;
981
+ maxFeePerGas?: bigint;
982
+ maxPriorityFeePerGas?: bigint;
983
+ }> {
984
+ const feeData = await this.provider.getFeeData();
985
+
986
+ return {
987
+ gasPrice: feeData.gasPrice ?? 0n,
988
+ gasPriceGwei: ((Number(feeData.gasPrice ?? 0n) / 1e9)).toFixed(4),
989
+ maxFeePerGas: feeData.maxFeePerGas ?? undefined,
990
+ maxPriorityFeePerGas: feeData.maxPriorityFeePerGas ?? undefined,
991
+ };
992
+ }
993
+ }