@hashgraphonline/standards-sdk 0.1.183 → 0.1.185

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 (289) hide show
  1. package/dist/browser/hcs-25/identifiers.d.ts +24 -0
  2. package/dist/browser/hcs-25/identifiers.d.ts.map +1 -0
  3. package/dist/browser/hcs-25/index.d.ts +4 -0
  4. package/dist/browser/hcs-25/index.d.ts.map +1 -0
  5. package/dist/browser/hcs-25/scoring.d.ts +32 -0
  6. package/dist/browser/hcs-25/scoring.d.ts.map +1 -0
  7. package/dist/browser/hcs-25/types.d.ts +363 -0
  8. package/dist/browser/hcs-25/types.d.ts.map +1 -0
  9. package/dist/browser/index.d.ts +1 -0
  10. package/dist/browser/index.d.ts.map +1 -1
  11. package/dist/browser/services/registry-broker/index.d.ts +1 -0
  12. package/dist/browser/services/registry-broker/index.d.ts.map +1 -1
  13. package/dist/browser/services/registry-broker/schemas.d.ts +6 -0
  14. package/dist/browser/services/registry-broker/schemas.d.ts.map +1 -1
  15. package/dist/browser/services/registry-broker/types.d.ts +7 -1
  16. package/dist/browser/services/registry-broker/types.d.ts.map +1 -1
  17. package/dist/browser/standards-sdk.browser.js.map +1 -1
  18. package/dist/browser-root/hcs-25/identifiers.d.ts +24 -0
  19. package/dist/browser-root/hcs-25/identifiers.d.ts.map +1 -0
  20. package/dist/browser-root/hcs-25/index.d.ts +4 -0
  21. package/dist/browser-root/hcs-25/index.d.ts.map +1 -0
  22. package/dist/browser-root/hcs-25/scoring.d.ts +32 -0
  23. package/dist/browser-root/hcs-25/scoring.d.ts.map +1 -0
  24. package/dist/browser-root/hcs-25/types.d.ts +363 -0
  25. package/dist/browser-root/hcs-25/types.d.ts.map +1 -0
  26. package/dist/browser-root/index.d.ts +1 -0
  27. package/dist/browser-root/index.d.ts.map +1 -1
  28. package/dist/browser-root/services/registry-broker/index.d.ts +1 -0
  29. package/dist/browser-root/services/registry-broker/index.d.ts.map +1 -1
  30. package/dist/browser-root/services/registry-broker/schemas.d.ts +6 -0
  31. package/dist/browser-root/services/registry-broker/schemas.d.ts.map +1 -1
  32. package/dist/browser-root/services/registry-broker/types.d.ts +7 -1
  33. package/dist/browser-root/services/registry-broker/types.d.ts.map +1 -1
  34. package/dist/browser-root/standards-sdk.root-browser.js +8 -1
  35. package/dist/browser-root/standards-sdk.root-browser.js.map +1 -1
  36. package/dist/cjs/hcs-25/identifiers.d.ts +24 -0
  37. package/dist/cjs/hcs-25/identifiers.d.ts.map +1 -0
  38. package/dist/cjs/hcs-25/index.d.ts +4 -0
  39. package/dist/cjs/hcs-25/index.d.ts.map +1 -0
  40. package/dist/cjs/hcs-25/scoring.d.ts +32 -0
  41. package/dist/cjs/hcs-25/scoring.d.ts.map +1 -0
  42. package/dist/cjs/hcs-25/types.d.ts +363 -0
  43. package/dist/cjs/hcs-25/types.d.ts.map +1 -0
  44. package/dist/cjs/index.d.ts +1 -0
  45. package/dist/cjs/index.d.ts.map +1 -1
  46. package/dist/cjs/services/registry-broker/index.d.ts +1 -0
  47. package/dist/cjs/services/registry-broker/index.d.ts.map +1 -1
  48. package/dist/cjs/services/registry-broker/schemas.d.ts +6 -0
  49. package/dist/cjs/services/registry-broker/schemas.d.ts.map +1 -1
  50. package/dist/cjs/services/registry-broker/types.d.ts +7 -1
  51. package/dist/cjs/services/registry-broker/types.d.ts.map +1 -1
  52. package/dist/cjs/standards-sdk.cjs +2 -2
  53. package/dist/cjs/standards-sdk.cjs.map +1 -1
  54. package/dist/es/hcs-25/identifiers.d.ts +24 -0
  55. package/dist/es/hcs-25/identifiers.d.ts.map +1 -0
  56. package/dist/es/hcs-25/index.d.ts +4 -0
  57. package/dist/es/hcs-25/index.d.ts.map +1 -0
  58. package/dist/es/hcs-25/scoring.d.ts +32 -0
  59. package/dist/es/hcs-25/scoring.d.ts.map +1 -0
  60. package/dist/es/hcs-25/types.d.ts +363 -0
  61. package/dist/es/hcs-25/types.d.ts.map +1 -0
  62. package/dist/es/index.d.ts +1 -0
  63. package/dist/es/index.d.ts.map +1 -1
  64. package/dist/es/services/registry-broker/index.d.ts +1 -0
  65. package/dist/es/services/registry-broker/index.d.ts.map +1 -1
  66. package/dist/es/services/registry-broker/schemas.d.ts +6 -0
  67. package/dist/es/services/registry-broker/schemas.d.ts.map +1 -1
  68. package/dist/es/services/registry-broker/types.d.ts +7 -1
  69. package/dist/es/services/registry-broker/types.d.ts.map +1 -1
  70. package/dist/es/standards-sdk.es.js +69 -39
  71. package/dist/es/standards-sdk.es.js.map +1 -1
  72. package/dist/es/standards-sdk.es101.js +2 -2
  73. package/dist/es/standards-sdk.es103.js +2 -2
  74. package/dist/es/standards-sdk.es104.js +1 -1
  75. package/dist/es/standards-sdk.es106.js +1 -1
  76. package/dist/es/standards-sdk.es108.js +2 -2
  77. package/dist/es/standards-sdk.es11.js +1 -1
  78. package/dist/es/standards-sdk.es110.js +1 -1
  79. package/dist/es/standards-sdk.es111.js +2 -2
  80. package/dist/es/standards-sdk.es115.js +3 -3
  81. package/dist/es/standards-sdk.es116.js +4 -4
  82. package/dist/es/standards-sdk.es117.js +19 -251
  83. package/dist/es/standards-sdk.es117.js.map +1 -1
  84. package/dist/es/standards-sdk.es118.js +60 -475
  85. package/dist/es/standards-sdk.es118.js.map +1 -1
  86. package/dist/es/standards-sdk.es119.js +217 -86
  87. package/dist/es/standards-sdk.es119.js.map +1 -1
  88. package/dist/es/standards-sdk.es12.js +1 -1
  89. package/dist/es/standards-sdk.es120.js +242 -150
  90. package/dist/es/standards-sdk.es120.js.map +1 -1
  91. package/dist/es/standards-sdk.es121.js +470 -26
  92. package/dist/es/standards-sdk.es121.js.map +1 -1
  93. package/dist/es/standards-sdk.es122.js +103 -10
  94. package/dist/es/standards-sdk.es122.js.map +1 -1
  95. package/dist/es/standards-sdk.es123.js +145 -167
  96. package/dist/es/standards-sdk.es123.js.map +1 -1
  97. package/dist/es/standards-sdk.es124.js +30 -25
  98. package/dist/es/standards-sdk.es124.js.map +1 -1
  99. package/dist/es/standards-sdk.es125.js +10 -20
  100. package/dist/es/standards-sdk.es125.js.map +1 -1
  101. package/dist/es/standards-sdk.es126.js +159 -137
  102. package/dist/es/standards-sdk.es126.js.map +1 -1
  103. package/dist/es/standards-sdk.es127.js +27 -199
  104. package/dist/es/standards-sdk.es127.js.map +1 -1
  105. package/dist/es/standards-sdk.es128.js +15 -783
  106. package/dist/es/standards-sdk.es128.js.map +1 -1
  107. package/dist/es/standards-sdk.es129.js +157 -10
  108. package/dist/es/standards-sdk.es129.js.map +1 -1
  109. package/dist/es/standards-sdk.es13.js +1 -1
  110. package/dist/es/standards-sdk.es130.js +198 -564
  111. package/dist/es/standards-sdk.es130.js.map +1 -1
  112. package/dist/es/standards-sdk.es131.js +703 -539
  113. package/dist/es/standards-sdk.es131.js.map +1 -1
  114. package/dist/es/standards-sdk.es132.js +12 -12
  115. package/dist/es/standards-sdk.es132.js.map +1 -1
  116. package/dist/es/standards-sdk.es133.js +567 -2
  117. package/dist/es/standards-sdk.es133.js.map +1 -1
  118. package/dist/es/standards-sdk.es134.js +610 -71
  119. package/dist/es/standards-sdk.es134.js.map +1 -1
  120. package/dist/es/standards-sdk.es135.js +12 -39
  121. package/dist/es/standards-sdk.es135.js.map +1 -1
  122. package/dist/es/standards-sdk.es136.js +2 -2
  123. package/dist/es/standards-sdk.es136.js.map +1 -1
  124. package/dist/es/standards-sdk.es137.js +42 -190
  125. package/dist/es/standards-sdk.es137.js.map +1 -1
  126. package/dist/es/standards-sdk.es138.js +39 -1139
  127. package/dist/es/standards-sdk.es138.js.map +1 -1
  128. package/dist/es/standards-sdk.es139.js +2 -306
  129. package/dist/es/standards-sdk.es139.js.map +1 -1
  130. package/dist/es/standards-sdk.es14.js +1 -1
  131. package/dist/es/standards-sdk.es140.js +231 -418
  132. package/dist/es/standards-sdk.es140.js.map +1 -1
  133. package/dist/es/standards-sdk.es141.js +1135 -350
  134. package/dist/es/standards-sdk.es141.js.map +1 -1
  135. package/dist/es/standards-sdk.es142.js +268 -1084
  136. package/dist/es/standards-sdk.es142.js.map +1 -1
  137. package/dist/es/standards-sdk.es143.js +418 -204
  138. package/dist/es/standards-sdk.es143.js.map +1 -1
  139. package/dist/es/standards-sdk.es144.js +350 -1562
  140. package/dist/es/standards-sdk.es144.js.map +1 -1
  141. package/dist/es/standards-sdk.es145.js +1061 -1096
  142. package/dist/es/standards-sdk.es145.js.map +1 -1
  143. package/dist/es/standards-sdk.es146.js +204 -13
  144. package/dist/es/standards-sdk.es146.js.map +1 -1
  145. package/dist/es/standards-sdk.es147.js +1541 -233
  146. package/dist/es/standards-sdk.es147.js.map +1 -1
  147. package/dist/es/standards-sdk.es148.js +1157 -4
  148. package/dist/es/standards-sdk.es148.js.map +1 -1
  149. package/dist/es/standards-sdk.es149.js +15 -79
  150. package/dist/es/standards-sdk.es149.js.map +1 -1
  151. package/dist/es/standards-sdk.es15.js +1 -1
  152. package/dist/es/standards-sdk.es150.js +250 -78
  153. package/dist/es/standards-sdk.es150.js.map +1 -1
  154. package/dist/es/standards-sdk.es151.js +4 -60
  155. package/dist/es/standards-sdk.es151.js.map +1 -1
  156. package/dist/es/standards-sdk.es152.js +75 -153
  157. package/dist/es/standards-sdk.es152.js.map +1 -1
  158. package/dist/es/standards-sdk.es153.js +87 -7
  159. package/dist/es/standards-sdk.es153.js.map +1 -1
  160. package/dist/es/standards-sdk.es154.js +54 -80
  161. package/dist/es/standards-sdk.es154.js.map +1 -1
  162. package/dist/es/standards-sdk.es155.js +2547 -65
  163. package/dist/es/standards-sdk.es155.js.map +1 -1
  164. package/dist/es/standards-sdk.es156.js +159 -30
  165. package/dist/es/standards-sdk.es156.js.map +1 -1
  166. package/dist/es/standards-sdk.es157.js +7 -34
  167. package/dist/es/standards-sdk.es157.js.map +1 -1
  168. package/dist/es/standards-sdk.es158.js +86 -48
  169. package/dist/es/standards-sdk.es158.js.map +1 -1
  170. package/dist/es/standards-sdk.es159.js +52 -125
  171. package/dist/es/standards-sdk.es159.js.map +1 -1
  172. package/dist/es/standards-sdk.es16.js +5 -5
  173. package/dist/es/standards-sdk.es160.js +30 -42
  174. package/dist/es/standards-sdk.es160.js.map +1 -1
  175. package/dist/es/standards-sdk.es161.js +32 -2538
  176. package/dist/es/standards-sdk.es161.js.map +1 -1
  177. package/dist/es/standards-sdk.es162.js +48 -12482
  178. package/dist/es/standards-sdk.es162.js.map +1 -1
  179. package/dist/es/standards-sdk.es163.js +12479 -53
  180. package/dist/es/standards-sdk.es163.js.map +1 -1
  181. package/dist/es/standards-sdk.es164.js +124 -97
  182. package/dist/es/standards-sdk.es164.js.map +1 -1
  183. package/dist/es/standards-sdk.es165.js +35 -74
  184. package/dist/es/standards-sdk.es165.js.map +1 -1
  185. package/dist/es/standards-sdk.es166.js +14 -197
  186. package/dist/es/standards-sdk.es166.js.map +1 -1
  187. package/dist/es/standards-sdk.es167.js +54 -15
  188. package/dist/es/standards-sdk.es167.js.map +1 -1
  189. package/dist/es/standards-sdk.es168.js +96 -58
  190. package/dist/es/standards-sdk.es168.js.map +1 -1
  191. package/dist/es/standards-sdk.es169.js +69 -660
  192. package/dist/es/standards-sdk.es169.js.map +1 -1
  193. package/dist/es/standards-sdk.es170.js +188 -160
  194. package/dist/es/standards-sdk.es170.js.map +1 -1
  195. package/dist/es/standards-sdk.es171.js +657 -307
  196. package/dist/es/standards-sdk.es171.js.map +1 -1
  197. package/dist/es/standards-sdk.es172.js +64 -337
  198. package/dist/es/standards-sdk.es172.js.map +1 -1
  199. package/dist/es/standards-sdk.es173.js +129 -410
  200. package/dist/es/standards-sdk.es173.js.map +1 -1
  201. package/dist/es/standards-sdk.es174.js +200 -209
  202. package/dist/es/standards-sdk.es174.js.map +1 -1
  203. package/dist/es/standards-sdk.es175.js +334 -64
  204. package/dist/es/standards-sdk.es175.js.map +1 -1
  205. package/dist/es/standards-sdk.es176.js +438 -124
  206. package/dist/es/standards-sdk.es176.js.map +1 -1
  207. package/dist/es/standards-sdk.es177.js +310 -496
  208. package/dist/es/standards-sdk.es177.js.map +1 -1
  209. package/dist/es/standards-sdk.es178.js +60 -243
  210. package/dist/es/standards-sdk.es178.js.map +1 -1
  211. package/dist/es/standards-sdk.es179.js +118 -175
  212. package/dist/es/standards-sdk.es179.js.map +1 -1
  213. package/dist/es/standards-sdk.es18.js +12 -12
  214. package/dist/es/standards-sdk.es180.js +465 -67
  215. package/dist/es/standards-sdk.es180.js.map +1 -1
  216. package/dist/es/standards-sdk.es181.js +250 -143
  217. package/dist/es/standards-sdk.es181.js.map +1 -1
  218. package/dist/es/standards-sdk.es182.js +172 -160
  219. package/dist/es/standards-sdk.es182.js.map +1 -1
  220. package/dist/es/standards-sdk.es183.js +65 -630
  221. package/dist/es/standards-sdk.es183.js.map +1 -1
  222. package/dist/es/standards-sdk.es184.js +128 -161
  223. package/dist/es/standards-sdk.es184.js.map +1 -1
  224. package/dist/es/standards-sdk.es185.js +144 -195
  225. package/dist/es/standards-sdk.es185.js.map +1 -1
  226. package/dist/es/standards-sdk.es186.js +668 -223
  227. package/dist/es/standards-sdk.es186.js.map +1 -1
  228. package/dist/es/standards-sdk.es187.js +188 -0
  229. package/dist/es/standards-sdk.es187.js.map +1 -0
  230. package/dist/es/standards-sdk.es188.js +238 -0
  231. package/dist/es/standards-sdk.es188.js.map +1 -0
  232. package/dist/es/standards-sdk.es189.js +242 -0
  233. package/dist/es/standards-sdk.es189.js.map +1 -0
  234. package/dist/es/standards-sdk.es19.js +9 -9
  235. package/dist/es/standards-sdk.es2.js +2 -2
  236. package/dist/es/standards-sdk.es20.js +1 -1
  237. package/dist/es/standards-sdk.es21.js +1 -1
  238. package/dist/es/standards-sdk.es22.js +1 -1
  239. package/dist/es/standards-sdk.es23.js +1 -1
  240. package/dist/es/standards-sdk.es24.js +1 -1
  241. package/dist/es/standards-sdk.es25.js +1 -1
  242. package/dist/es/standards-sdk.es26.js +1 -1
  243. package/dist/es/standards-sdk.es27.js +12 -12
  244. package/dist/es/standards-sdk.es30.js +2 -2
  245. package/dist/es/standards-sdk.es31.js +4 -4
  246. package/dist/es/standards-sdk.es32.js +1 -1
  247. package/dist/es/standards-sdk.es35.js +6 -6
  248. package/dist/es/standards-sdk.es36.js +4 -4
  249. package/dist/es/standards-sdk.es37.js +2 -2
  250. package/dist/es/standards-sdk.es38.js +2 -2
  251. package/dist/es/standards-sdk.es39.js +1 -1
  252. package/dist/es/standards-sdk.es4.js +2 -2
  253. package/dist/es/standards-sdk.es40.js +1 -1
  254. package/dist/es/standards-sdk.es41.js +2 -2
  255. package/dist/es/standards-sdk.es46.js +1 -1
  256. package/dist/es/standards-sdk.es5.js +2 -2
  257. package/dist/es/standards-sdk.es51.js +1 -1
  258. package/dist/es/standards-sdk.es53.js +1 -1
  259. package/dist/es/standards-sdk.es56.js +2 -2
  260. package/dist/es/standards-sdk.es59.js +1 -1
  261. package/dist/es/standards-sdk.es6.js +2 -2
  262. package/dist/es/standards-sdk.es60.js +1 -1
  263. package/dist/es/standards-sdk.es62.js +1 -1
  264. package/dist/es/standards-sdk.es63.js +2 -2
  265. package/dist/es/standards-sdk.es64.js +1 -1
  266. package/dist/es/standards-sdk.es65.js +1 -1
  267. package/dist/es/standards-sdk.es66.js +1 -1
  268. package/dist/es/standards-sdk.es67.js +7 -7
  269. package/dist/es/standards-sdk.es69.js +1 -1
  270. package/dist/es/standards-sdk.es7.js +1 -1
  271. package/dist/es/standards-sdk.es71.js +2 -2
  272. package/dist/es/standards-sdk.es72.js +3 -3
  273. package/dist/es/standards-sdk.es75.js +5 -5
  274. package/dist/es/standards-sdk.es76.js +3 -3
  275. package/dist/es/standards-sdk.es77.js +2 -2
  276. package/dist/es/standards-sdk.es78.js +1 -1
  277. package/dist/es/standards-sdk.es81.js +2 -2
  278. package/dist/es/standards-sdk.es83.js +2 -2
  279. package/dist/es/standards-sdk.es84.js +4 -4
  280. package/dist/es/standards-sdk.es85.js +1 -1
  281. package/dist/es/standards-sdk.es88.js +1 -1
  282. package/dist/es/standards-sdk.es89.js +2 -2
  283. package/dist/es/standards-sdk.es9.js +2 -2
  284. package/dist/es/standards-sdk.es90.js +4 -4
  285. package/dist/es/standards-sdk.es94.js +3 -3
  286. package/dist/es/standards-sdk.es96.js +2 -2
  287. package/dist/es/standards-sdk.es98.js +1 -1
  288. package/dist/es/standards-sdk.es99.js +3 -3
  289. package/package.json +1 -1
@@ -1,1160 +1,1125 @@
1
- import { Buffer } from "buffer";
2
- import { secp256k1 } from "@noble/curves/secp256k1.js";
3
- import { ZodError } from "zod";
4
- import { agentFeedbackResponseSchema, agentFeedbackIndexResponseSchema, agentFeedbackEntriesIndexResponseSchema, agentFeedbackEligibilityResponseSchema, agentFeedbackSubmissionResponseSchema, registerAgentResponseSchema } from "./standards-sdk.es161.js";
5
- import { fetchHistorySnapshot, attachDecryptedHistory, registerConversationContextForEncryption, resolveDecryptionContext, decryptHistoryEntryFromContext } from "./standards-sdk.es176.js";
6
- import { createChatApi, createSession, resumeSession, checkChatReadiness, startChat, startConversation, acceptConversation, compactHistory, fetchEncryptionStatus, postEncryptionHandshake, sendMessage, retryMessage, cancelSession, endSession, createPlaintextConversationHandle } from "./standards-sdk.es177.js";
7
- import { EncryptedChatManager } from "./standards-sdk.es178.js";
8
- import { generateEncryptionKeyPair, bootstrapEncryptionOptions, createEncryptionApi } from "./standards-sdk.es179.js";
9
- import { adapters, adaptersDetailed, adapterRegistryCategories, adapterRegistryAdapters, createAdapterRegistryCategory, submitAdapterRegistryAdapter, adapterRegistrySubmissionStatus } from "./standards-sdk.es180.js";
10
- import { resolveUaid, getRegistrationQuote, updateAgent, getRegistrationProgress, waitForRegistrationCompletion, validateUaid, getUaidConnectionStatus, closeUaidConnection, dashboardStats } from "./standards-sdk.es147.js";
11
- import { getRegisterStatus, registerOwnedMoltbookAgent, getVerificationStatus, createVerificationChallenge, getVerificationChallenge, verifyVerificationChallenge, getVerificationOwnership, verifySenderOwnership, verifyUaidDnsTxt, getVerificationDnsStatus } from "./standards-sdk.es181.js";
12
- import { getCreditsBalance, getCreditProviders, createHbarPurchaseIntent, purchaseCreditsWithHbar, getX402Minimums, purchaseCreditsWithX402, buyCreditsWithX402 } from "./standards-sdk.es182.js";
13
- import { getGuardSession, getGuardEntitlements, getGuardBillingBalance, getGuardFeed, getGuardOverview, getGuardTrustByHash, resolveGuardTrust, getGuardRevocations, fetchGuardAdvisories, fetchGuardPolicy, getGuardInventory, getGuardReceiptHistory, getGuardArtifactTimeline, getGuardInventoryDiff, exportGuardAbom, exportGuardArtifactAbom, exportGuardReceipts, getGuardDevices, getGuardAlertPreferences, updateGuardAlertPreferences, getGuardExceptions, getGuardWatchlist, lookupGuardWatchlist, getGuardPainSignals, getGuardAggregatedPainSignals, getGuardPreInstallVerdict, getGuardPreExecutionVerdict, addGuardWatchlistItem, removeGuardWatchlistItem, addGuardException, requestGuardException, removeGuardException, ingestGuardPainSignals, syncGuardReceipts, syncGuardInventory, submitGuardReceipts, getGuardTeamPolicyPack, updateGuardTeamPolicyPack } from "./standards-sdk.es183.js";
14
- import { createLedgerChallenge, verifyLedgerChallenge, authenticateWithLedger, authenticateWithLedgerCredentials } from "./standards-sdk.es184.js";
15
- import { search, delegate, stats, registries, getAdditionalRegistries, popularSearches, listProtocols, detectProtocol, registrySearchByNamespace, vectorSearch, searchStatus, websocketStats, metricsSummary, facets } from "./standards-sdk.es185.js";
16
- import { skillsConfig, listSkills, getSkillsCatalog, listSkillVersions, listMySkills, getMySkillsList, quoteSkillPublish, quoteSkillPublishPreview, publishSkill, getSkillPublishJob, getSkillOwnership, getRecommendedSkillVersion, setRecommendedSkillVersion, getSkillDeprecations, setSkillDeprecation, getSkillBadge, getSkillStatus, getSkillSecurityBreakdown, getSkillStatusByRepo, getSkillConversionSignalsByRepo, uploadSkillPreviewFromGithubOidc, getSkillPreview, getSkillPreviewByRepo, getSkillPreviewById, getSkillInstall, recordSkillInstallCopy, listSkillTags, listSkillCategories, resolveSkillMarkdown, resolveSkillManifest, getSkillVoteStatus, setSkillVote, requestSkillVerification, getSkillVerificationStatus, createSkillDomainProofChallenge, verifySkillDomainProof } from "./standards-sdk.es169.js";
17
- import { DEFAULT_BASE_URL, normaliseBaseUrl, normaliseHeaderName, isBrowserRuntime, DEFAULT_USER_AGENT, JSON_CONTENT_TYPE, serialiseAgentRegistrationRequest, MINIMUM_REGISTRATION_AUTO_TOP_UP_CREDITS, createAbortError, isJsonObject, DEFAULT_HISTORY_TOP_UP_HBAR } from "./standards-sdk.es186.js";
18
- import { RegistryBrokerError, RegistryBrokerParseError } from "./standards-sdk.es146.js";
19
- import { optionalImportSync } from "./standards-sdk.es164.js";
20
- class RegistryBrokerClient {
21
- constructor(options = {}) {
22
- this.encryptionBootstrapPromise = null;
23
- this.chatApi = null;
24
- this.encryptedChatManager = null;
25
- this.encryptionApi = null;
26
- this.conversationContexts = /* @__PURE__ */ new Map();
27
- const {
28
- baseUrl = DEFAULT_BASE_URL,
29
- fetchImplementation,
30
- defaultHeaders,
31
- apiKey,
32
- accountId,
33
- ledgerApiKey,
34
- registrationAutoTopUp,
35
- historyAutoTopUp,
36
- encryption
37
- } = options;
38
- this.baseUrl = normaliseBaseUrl(baseUrl);
39
- const resolvedFetch = fetchImplementation ?? (typeof globalThis.fetch === "function" ? globalThis.fetch : null);
40
- if (!resolvedFetch) {
41
- throw new Error(
42
- "A fetch implementation is required for RegistryBrokerClient"
43
- );
44
- }
45
- this.fetchImpl = resolvedFetch;
46
- this.defaultHeaders = {
47
- ...defaultHeaders ?? {}
48
- };
49
- Object.entries(this.defaultHeaders).forEach(([key, value]) => {
50
- const headerName = normaliseHeaderName(key);
51
- if (headerName !== key) {
52
- delete this.defaultHeaders[key];
53
- this.defaultHeaders[headerName] = value;
54
- }
55
- });
56
- const existingLedgerHeader = this.defaultHeaders["x-ledger-api-key"]?.trim();
57
- if (!this.defaultHeaders["x-api-key"] && existingLedgerHeader) {
58
- this.defaultHeaders["x-api-key"] = existingLedgerHeader;
59
- }
60
- if (apiKey) {
61
- this.defaultHeaders["x-api-key"] = apiKey;
62
- }
63
- if (typeof accountId === "string" && accountId.trim().length > 0) {
64
- this.defaultHeaders["x-account-id"] = accountId.trim();
65
- }
66
- if (ledgerApiKey) {
67
- if (!this.defaultHeaders["x-api-key"]) {
68
- this.defaultHeaders["x-api-key"] = ledgerApiKey;
1
+ import { InscriptionSDK } from "./standards-sdk.es163.js";
2
+ import { Logger } from "./standards-sdk.es126.js";
3
+ import { ProgressReporter } from "./standards-sdk.es129.js";
4
+ import { TransactionParser } from "./standards-sdk.es131.js";
5
+ import { isBrowser } from "./standards-sdk.es139.js";
6
+ import { optionalImport } from "./standards-sdk.es168.js";
7
+ import { validateQuoteParameters, getCachedQuote, getOrCreateSDK, cacheQuote } from "./standards-sdk.es146.js";
8
+ import { HederaMirrorNode } from "./standards-sdk.es147.js";
9
+ import { sleep } from "./standards-sdk.es136.js";
10
+ import { computeInscriptionCostSummary } from "./standards-sdk.es172.js";
11
+ let nodeModules = {};
12
+ const normalizeTransactionId = (txId) => {
13
+ if (!txId.includes("@")) {
14
+ return txId;
15
+ }
16
+ const txParts = txId?.split("@");
17
+ return `${txParts[0]}-${txParts[1].replace(".", "-")}`;
18
+ };
19
+ async function loadNodeModules() {
20
+ if (isBrowser || nodeModules.readFileSync) {
21
+ return;
22
+ }
23
+ try {
24
+ const [fsModule, pathModule] = await Promise.all([
25
+ optionalImport("node:fs"),
26
+ optionalImport("node:path")
27
+ ]);
28
+ if (!fsModule || !pathModule) {
29
+ throw new Error("Node.js fs or path module not available");
30
+ }
31
+ nodeModules.readFileSync = fsModule.readFileSync;
32
+ nodeModules.basename = pathModule.basename;
33
+ nodeModules.extname = pathModule.extname;
34
+ } catch (error) {
35
+ Logger.getInstance({
36
+ module: "Inscriber",
37
+ level: "warn"
38
+ }).warn(
39
+ "Node.js modules not available, file path operations will be disabled",
40
+ {
41
+ error: error instanceof Error ? error.message : String(error)
69
42
  }
70
- }
71
- this.registrationAutoTopUp = registrationAutoTopUp;
72
- this.historyAutoTopUp = historyAutoTopUp;
73
- this.encryptionOptions = encryption;
74
- if (this.encryptionOptions) {
75
- this.encryptionBootstrapPromise = this.initializeEncryptionBootstrap(
76
- this.encryptionOptions
77
- );
78
- }
43
+ );
79
44
  }
80
- static async initializeAgent(options) {
81
- const { uaid, ensureEncryptionKey = true, ...clientOptions } = options;
82
- const client = new RegistryBrokerClient(clientOptions);
83
- let encryption = null;
84
- if (ensureEncryptionKey) {
85
- const ensureOptions = typeof ensureEncryptionKey === "object" ? ensureEncryptionKey : { generateIfMissing: true };
86
- encryption = await client.encryption.ensureAgentKey({
87
- uaid,
88
- ...ensureOptions
89
- });
90
- }
91
- return { client, encryption };
45
+ }
46
+ const COST_LOOKUP_ATTEMPTS = 3;
47
+ const COST_LOOKUP_DELAY_MS = 1e3;
48
+ const COST_LOGGER_MODULE = "InscriberCost";
49
+ async function convertFileToBase64(filePath) {
50
+ if (isBrowser) {
51
+ throw new Error(
52
+ "File path operations are not supported in browser environment. Use buffer input type instead."
53
+ );
92
54
  }
93
- get chat() {
94
- if (this.chatApi) {
95
- return this.chatApi;
96
- }
97
- const api = createChatApi(this, this.getEncryptedChatManager());
98
- this.chatApi = api;
99
- return api;
55
+ await loadNodeModules();
56
+ if (!nodeModules.readFileSync || !nodeModules.basename || !nodeModules.extname) {
57
+ throw new Error(
58
+ "Node.js file system modules are not available. Cannot read file from path."
59
+ );
100
60
  }
101
- get encryption() {
102
- if (this.encryptionApi) {
103
- return this.encryptionApi;
61
+ try {
62
+ const buffer = nodeModules.readFileSync(filePath);
63
+ const base64 = buffer.toString("base64");
64
+ const fileName = nodeModules.basename(filePath);
65
+ let mimeType = "application/octet-stream";
66
+ try {
67
+ const fileTypeModule = await optionalImport("file-type");
68
+ const fileTypeResult = typeof fileTypeModule?.fileTypeFromBuffer === "function" ? await fileTypeModule.fileTypeFromBuffer(buffer) : void 0;
69
+ if (fileTypeResult) {
70
+ mimeType = fileTypeResult.mime;
71
+ }
72
+ } catch (_error) {
73
+ const ext = nodeModules.extname(filePath).toLowerCase();
74
+ const mimeMap = {
75
+ ".txt": "text/plain",
76
+ ".json": "application/json",
77
+ ".html": "text/html",
78
+ ".css": "text/css",
79
+ ".js": "application/javascript",
80
+ ".png": "image/png",
81
+ ".jpg": "image/jpeg",
82
+ ".jpeg": "image/jpeg",
83
+ ".gif": "image/gif",
84
+ ".svg": "image/svg+xml",
85
+ ".pdf": "application/pdf"
86
+ };
87
+ mimeType = mimeMap[ext] || "application/octet-stream";
104
88
  }
105
- const api = createEncryptionApi(this);
106
- this.encryptionApi = api;
107
- return api;
89
+ return { base64, fileName, mimeType };
90
+ } catch (error) {
91
+ throw new Error(
92
+ `Failed to read file ${filePath}: ${error.message}`
93
+ );
108
94
  }
109
- setApiKey(apiKey) {
110
- this.setDefaultHeader("x-api-key", apiKey);
95
+ }
96
+ function normalizeClientConfig(cfg) {
97
+ return {
98
+ accountId: cfg.accountId,
99
+ privateKey: typeof cfg.privateKey === "string" ? cfg.privateKey : cfg.privateKey.toString(),
100
+ network: cfg.network
101
+ };
102
+ }
103
+ function resolveConnectionMode(options) {
104
+ if (options.connectionMode) {
105
+ return options.connectionMode;
111
106
  }
112
- setLedgerApiKey(apiKey) {
113
- this.setDefaultHeader("x-api-key", apiKey);
114
- delete this.defaultHeaders["x-ledger-api-key"];
107
+ if (typeof options.websocket === "boolean") {
108
+ return options.websocket ? "websocket" : "http";
115
109
  }
116
- setDefaultHeader(name, value) {
117
- if (!name || name.trim().length === 0) {
118
- return;
119
- }
120
- const headerName = normaliseHeaderName(name);
121
- if (!value || value.trim().length === 0) {
122
- delete this.defaultHeaders[headerName];
123
- return;
110
+ return "websocket";
111
+ }
112
+ async function inscribe(input, clientConfig, options, existingSDK) {
113
+ const logger = Logger.getInstance({
114
+ module: "Inscriber",
115
+ ...options.logging
116
+ });
117
+ const resolvedConnectionMode = resolveConnectionMode(options);
118
+ logger.info("Starting inscription process", {
119
+ type: input.type,
120
+ mode: options.mode || "file",
121
+ quoteOnly: options.quoteOnly || false,
122
+ ...input.type === "url" ? { url: input.url } : {},
123
+ ...input.type === "file" ? { path: input.path } : {},
124
+ ...input.type === "buffer" ? { fileName: input.fileName, bufferSize: input.buffer.byteLength } : {}
125
+ });
126
+ try {
127
+ if (options.quoteOnly) {
128
+ logger.debug("Quote-only mode requested, generating quote");
129
+ return await generateQuote(input, clientConfig, options, existingSDK);
130
+ }
131
+ if (options.mode === "hashinal" && options.metadata) {
132
+ validateHashinalMetadata(options.metadata, logger);
133
+ }
134
+ let sdk;
135
+ if (existingSDK) {
136
+ logger.debug("Using existing InscriptionSDK instance");
137
+ sdk = existingSDK;
138
+ } else if (options.apiKey) {
139
+ logger.debug("Initializing InscriptionSDK with API key");
140
+ sdk = new InscriptionSDK({
141
+ apiKey: options.apiKey,
142
+ network: clientConfig.network || "mainnet",
143
+ connectionMode: resolvedConnectionMode,
144
+ baseURL: options.baseURL
145
+ });
146
+ } else {
147
+ logger.debug("Initializing InscriptionSDK with server auth");
148
+ const normalized = normalizeClientConfig(clientConfig);
149
+ sdk = await InscriptionSDK.createWithAuth({
150
+ type: "server",
151
+ accountId: normalized.accountId,
152
+ privateKey: normalized.privateKey,
153
+ network: normalized.network || "mainnet",
154
+ connectionMode: resolvedConnectionMode,
155
+ baseUrl: options.baseURL
156
+ });
124
157
  }
125
- this.defaultHeaders[headerName] = value.trim();
126
- }
127
- getDefaultHeaders() {
128
- return { ...this.defaultHeaders };
129
- }
130
- async encryptionReady() {
131
- if (!this.encryptionBootstrapPromise) {
132
- return;
158
+ const baseRequest = {
159
+ holderId: clientConfig.accountId,
160
+ metadata: options.metadata || {},
161
+ tags: options.tags || [],
162
+ mode: options.mode || "file",
163
+ fileStandard: options.fileStandard,
164
+ chunkSize: options.chunkSize
165
+ };
166
+ let request;
167
+ switch (input.type) {
168
+ case "url":
169
+ request = {
170
+ ...baseRequest,
171
+ file: {
172
+ type: "url",
173
+ url: input.url
174
+ }
175
+ };
176
+ break;
177
+ case "file": {
178
+ const fileData = await convertFileToBase64(input.path);
179
+ request = {
180
+ ...baseRequest,
181
+ file: {
182
+ type: "base64",
183
+ base64: fileData.base64,
184
+ fileName: fileData.fileName,
185
+ mimeType: fileData.mimeType
186
+ }
187
+ };
188
+ break;
189
+ }
190
+ case "buffer":
191
+ request = {
192
+ ...baseRequest,
193
+ file: {
194
+ type: "base64",
195
+ base64: Buffer.from(
196
+ input.buffer instanceof ArrayBuffer ? new Uint8Array(input.buffer) : input.buffer
197
+ ).toString("base64"),
198
+ fileName: input.fileName,
199
+ mimeType: input.mimeType
200
+ }
201
+ };
202
+ break;
203
+ }
204
+ if (options.mode === "hashinal") {
205
+ request.metadataObject = options.metadata;
206
+ request.creator = options.metadata?.creator || clientConfig.accountId;
207
+ request.description = options.metadata?.description;
208
+ if (options.jsonFileURL) {
209
+ request.jsonFileURL = options.jsonFileURL;
210
+ }
133
211
  }
134
- await this.encryptionBootstrapPromise;
135
- }
136
- buildUrl(path) {
137
- const normalisedPath = path.startsWith("/") ? path : `/${path}`;
138
- return `${this.baseUrl}${normalisedPath}`;
139
- }
140
- buildRequestInit(config) {
141
- const headers = new Headers();
142
- Object.entries(this.defaultHeaders).forEach(([key, value]) => {
143
- headers.set(key, value);
212
+ logger.debug("Preparing to inscribe content", {
213
+ type: input.type,
214
+ mode: options.mode || "file",
215
+ holderId: clientConfig.accountId
216
+ });
217
+ const normalizedCfg = normalizeClientConfig(clientConfig);
218
+ const result = await sdk.inscribeAndExecute(
219
+ request,
220
+ normalizedCfg,
221
+ options.progressCallback
222
+ );
223
+ const rawJobId = result.jobId || result.tx_id || result.transactionId || "";
224
+ const rawTxId = result.transactionId || rawJobId || "";
225
+ const normalizedJobId = normalizeTransactionId(rawJobId);
226
+ const normalizedTxId = normalizeTransactionId(rawTxId);
227
+ const waitId = normalizeTransactionId(
228
+ normalizedJobId || normalizedTxId || rawJobId || result.jobId || ""
229
+ );
230
+ logger.info("Starting to inscribe.", {
231
+ type: input.type,
232
+ mode: options.mode || "file",
233
+ transactionId: result.jobId
144
234
  });
145
- if (config.headers) {
146
- Object.entries(config.headers).forEach(([key, value]) => {
147
- headers.set(key, value);
235
+ if (options.waitForConfirmation) {
236
+ logger.debug("Waiting for inscription confirmation", {
237
+ transactionId: waitId,
238
+ maxAttempts: options.waitMaxAttempts,
239
+ intervalMs: options.waitIntervalMs
148
240
  });
241
+ const inscription = await waitForInscriptionConfirmation(
242
+ sdk,
243
+ waitId,
244
+ options.waitMaxAttempts,
245
+ options.waitIntervalMs,
246
+ options.progressCallback
247
+ );
248
+ logger.info("Inscription confirmation received", {
249
+ transactionId: result.jobId
250
+ });
251
+ return {
252
+ confirmed: true,
253
+ result: {
254
+ ...result,
255
+ jobId: waitId,
256
+ transactionId: normalizedTxId
257
+ },
258
+ inscription,
259
+ sdk,
260
+ costSummary: await resolveInscriptionCost(
261
+ normalizedTxId,
262
+ clientConfig.network || "mainnet",
263
+ options.logging?.level
264
+ )
265
+ };
149
266
  }
150
- if (!headers.has("accept")) {
151
- headers.set("accept", "application/json");
152
- }
153
- if (!headers.has("user-agent") && !isBrowserRuntime()) {
154
- headers.set("user-agent", DEFAULT_USER_AGENT);
155
- }
156
- const init = {
157
- method: config.method ?? "GET",
158
- headers
267
+ return {
268
+ confirmed: false,
269
+ result: {
270
+ ...result,
271
+ jobId: waitId,
272
+ transactionId: normalizedTxId
273
+ },
274
+ sdk,
275
+ costSummary: await resolveInscriptionCost(
276
+ normalizedTxId,
277
+ clientConfig.network || "mainnet",
278
+ options.logging?.level
279
+ )
159
280
  };
160
- if (config.body !== void 0) {
161
- init.body = JSON.stringify(config.body);
162
- if (!headers.has("content-type")) {
163
- headers.set("content-type", "application/json");
281
+ } catch (error) {
282
+ logger.error("Error during inscription process", error);
283
+ throw error;
284
+ }
285
+ }
286
+ async function resolveInscriptionCost(transactionId, network, level) {
287
+ const logger = Logger.getInstance({
288
+ module: COST_LOGGER_MODULE,
289
+ level: level ?? "info"
290
+ });
291
+ const mirrorNode = new HederaMirrorNode(network, logger);
292
+ const normalizedId = normalizeTransactionId(transactionId);
293
+ const payerAccountId = normalizedId.split("-")[0];
294
+ for (let attempt = 0; attempt < COST_LOOKUP_ATTEMPTS; attempt++) {
295
+ try {
296
+ const txn = await mirrorNode.getTransaction(normalizedId);
297
+ if (!txn) {
298
+ if (attempt < COST_LOOKUP_ATTEMPTS - 1) {
299
+ await sleep(COST_LOOKUP_DELAY_MS);
300
+ }
301
+ continue;
302
+ }
303
+ const computed = computeInscriptionCostSummary({
304
+ txn,
305
+ payerAccountId
306
+ });
307
+ if (!computed) {
308
+ if (attempt < COST_LOOKUP_ATTEMPTS - 1) {
309
+ await sleep(COST_LOOKUP_DELAY_MS);
310
+ }
311
+ continue;
312
+ }
313
+ return computed.summary;
314
+ } catch (error) {
315
+ logger.warn("Unable to resolve inscription cost", {
316
+ transactionId: normalizedId,
317
+ attempt: attempt + 1,
318
+ error: error instanceof Error ? error.message : String(error)
319
+ });
320
+ if (attempt < COST_LOOKUP_ATTEMPTS - 1) {
321
+ await sleep(COST_LOOKUP_DELAY_MS);
164
322
  }
165
323
  }
166
- return init;
167
324
  }
168
- async request(path, config) {
169
- const init = this.buildRequestInit(config);
170
- const response = await this.fetchImpl(this.buildUrl(path), init);
171
- if (response.ok) {
172
- return response;
325
+ return void 0;
326
+ }
327
+ async function inscribeWithSigner(input, signer, options, existingSDK) {
328
+ const logger = Logger.getInstance({
329
+ module: "Inscriber",
330
+ ...options.logging
331
+ });
332
+ const resolvedConnectionMode = resolveConnectionMode(options);
333
+ logger.info("Starting inscription process with signer", {
334
+ type: input.type,
335
+ mode: options.mode || "file",
336
+ quoteOnly: options.quoteOnly || false,
337
+ ...input.type === "url" ? { url: input.url } : {},
338
+ ...input.type === "file" ? { path: input.path } : {},
339
+ ...input.type === "buffer" ? { fileName: input.fileName, bufferSize: input.buffer.byteLength } : {}
340
+ });
341
+ try {
342
+ if (options.quoteOnly) {
343
+ logger.debug("Quote-only mode requested with signer, generating quote");
344
+ const clientConfig = {
345
+ accountId: signer.getAccountId().toString(),
346
+ privateKey: "",
347
+ network: options.network || "mainnet"
348
+ };
349
+ return await generateQuote(input, clientConfig, options, existingSDK);
350
+ }
351
+ if (options.mode === "hashinal" && options.metadata) {
352
+ validateHashinalMetadata(options.metadata, logger);
353
+ }
354
+ const accountId = signer.getAccountId().toString();
355
+ logger.debug("Using account ID from signer", { accountId });
356
+ let sdk;
357
+ if (existingSDK) {
358
+ logger.debug("Using existing InscriptionSDK instance");
359
+ sdk = existingSDK;
360
+ } else if (options.apiKey) {
361
+ logger.debug("Initializing InscriptionSDK with API key");
362
+ sdk = new InscriptionSDK({
363
+ apiKey: options.apiKey,
364
+ network: options.network || "mainnet",
365
+ connectionMode: resolvedConnectionMode,
366
+ baseURL: options.baseURL
367
+ });
368
+ } else {
369
+ logger.debug("Initializing InscriptionSDK with client auth (websocket)");
370
+ sdk = await InscriptionSDK.createWithAuth({
371
+ type: "client",
372
+ accountId,
373
+ signer,
374
+ network: options.network || "mainnet",
375
+ connectionMode: resolvedConnectionMode,
376
+ baseUrl: options.baseURL
377
+ });
173
378
  }
174
- const errorBody = await this.extractErrorBody(response);
175
- throw new RegistryBrokerError("Registry broker request failed", {
176
- status: response.status,
177
- statusText: response.statusText,
178
- body: errorBody
179
- });
180
- }
181
- async requestAbsolute(url, config) {
182
- const init = this.buildRequestInit(config);
183
- const response = await this.fetchImpl(url, init);
184
- if (response.ok) {
185
- return response;
379
+ const baseRequest = {
380
+ holderId: accountId,
381
+ metadata: options.metadata || {},
382
+ tags: options.tags || [],
383
+ mode: options.mode || "file",
384
+ fileStandard: options.fileStandard,
385
+ chunkSize: options.chunkSize
386
+ };
387
+ let request;
388
+ switch (input.type) {
389
+ case "url":
390
+ request = {
391
+ ...baseRequest,
392
+ file: {
393
+ type: "url",
394
+ url: input.url
395
+ }
396
+ };
397
+ break;
398
+ case "file": {
399
+ const fileData = await convertFileToBase64(input.path);
400
+ request = {
401
+ ...baseRequest,
402
+ file: {
403
+ type: "base64",
404
+ base64: fileData.base64,
405
+ fileName: fileData.fileName,
406
+ mimeType: fileData.mimeType
407
+ }
408
+ };
409
+ break;
410
+ }
411
+ case "buffer":
412
+ request = {
413
+ ...baseRequest,
414
+ file: {
415
+ type: "base64",
416
+ base64: Buffer.from(
417
+ input.buffer instanceof ArrayBuffer ? new Uint8Array(input.buffer) : input.buffer
418
+ ).toString("base64"),
419
+ fileName: input.fileName,
420
+ mimeType: input.mimeType
421
+ }
422
+ };
423
+ break;
424
+ }
425
+ if (options.mode === "hashinal") {
426
+ request.metadataObject = options.metadata;
427
+ request.creator = options.metadata?.creator || accountId;
428
+ request.description = options.metadata?.description;
429
+ if (options.jsonFileURL) {
430
+ request.jsonFileURL = options.jsonFileURL;
431
+ }
186
432
  }
187
- const errorBody = await this.extractErrorBody(response);
188
- throw new RegistryBrokerError("Registry broker request failed", {
189
- status: response.status,
190
- statusText: response.statusText,
191
- body: errorBody
433
+ logger.debug("Starting inscription via startInscription (websocket)", {
434
+ type: input.type,
435
+ mode: options.mode || "file",
436
+ holderId: accountId,
437
+ usesStartInscription: true
192
438
  });
193
- }
194
- async requestJson(path, config) {
195
- const response = await this.request(path, config);
196
- const contentType = response.headers?.get("content-type") ?? "";
197
- if (!JSON_CONTENT_TYPE.test(contentType)) {
198
- const body = await response.text();
199
- throw new RegistryBrokerParseError(
200
- "Expected JSON response from registry broker",
201
- body
439
+ const startResult = await sdk.startInscription({
440
+ ...request,
441
+ holderId: accountId,
442
+ network: options.network || "mainnet"
443
+ });
444
+ const startTransactionIdRaw = typeof startResult?.tx_id === "string" && startResult.tx_id.trim() || typeof startResult?.jobId === "string" && (startResult.jobId || "").trim() || typeof startResult?.id === "string" && (startResult.id || "").trim() || "";
445
+ const waitId = normalizeTransactionId(startTransactionIdRaw);
446
+ if (!waitId) {
447
+ throw new Error("startInscription did not return a transaction id");
448
+ }
449
+ logger.info("about to start inscription", {
450
+ type: input.type,
451
+ mode: options.mode || "file",
452
+ jobId: waitId,
453
+ ...startResult
454
+ });
455
+ if (typeof startResult?.transactionBytes === "string") {
456
+ logger.debug("Executing inscription transaction with signer from bytes");
457
+ await sdk.executeTransactionWithSigner(
458
+ startResult.transactionBytes,
459
+ signer
202
460
  );
203
- }
204
- return await response.json();
205
- }
206
- async requestAbsoluteJson(url, config) {
207
- const response = await this.requestAbsolute(url, config);
208
- const contentType = response.headers?.get("content-type") ?? "";
209
- if (!JSON_CONTENT_TYPE.test(contentType)) {
210
- const body = await response.text();
211
- throw new RegistryBrokerParseError(
212
- "Expected JSON response from registry broker",
213
- body
461
+ } else if (startResult?.transactionBytes?.type === "Buffer") {
462
+ logger.debug("Executing inscription transaction with signer from buffer");
463
+ await sdk.executeTransactionWithSigner(
464
+ Buffer.from(startResult.transactionBytes.data).toString("base64"),
465
+ signer
214
466
  );
215
467
  }
216
- return await response.json();
217
- }
218
- async getAgentFeedback(uaid, options = {}) {
219
- const normalized = uaid.trim();
220
- if (!normalized) {
221
- throw new Error("uaid is required");
468
+ if (options.waitForConfirmation) {
469
+ logger.debug("Waiting for inscription confirmation (websocket)", {
470
+ jobId: waitId,
471
+ maxAttempts: options.waitMaxAttempts,
472
+ intervalMs: options.waitIntervalMs
473
+ });
474
+ const inscription = await waitForInscriptionConfirmation(
475
+ sdk,
476
+ waitId,
477
+ options.waitMaxAttempts,
478
+ options.waitIntervalMs,
479
+ options.progressCallback
480
+ );
481
+ logger.info("Inscription confirmation received", {
482
+ jobId: waitId
483
+ });
484
+ return {
485
+ confirmed: true,
486
+ result: {
487
+ jobId: waitId,
488
+ transactionId: waitId,
489
+ topic_id: startResult.topic_id,
490
+ status: startResult.status,
491
+ completed: startResult.completed
492
+ },
493
+ inscription,
494
+ sdk,
495
+ costSummary: await resolveInscriptionCost(
496
+ waitId,
497
+ options.network || "mainnet",
498
+ options.logging?.level
499
+ )
500
+ };
222
501
  }
223
- const query = options.includeRevoked === true ? "?includeRevoked=true" : "";
224
- const raw = await this.requestJson(
225
- `/agents/${encodeURIComponent(normalized)}/feedback${query}`,
226
- { method: "GET" }
227
- );
228
- return this.parseWithSchema(
229
- raw,
230
- agentFeedbackResponseSchema,
231
- "agent feedback response"
232
- );
502
+ return {
503
+ confirmed: false,
504
+ result: {
505
+ jobId: waitId,
506
+ transactionId: waitId,
507
+ topic_id: startResult.topic_id,
508
+ status: startResult.status,
509
+ completed: startResult.completed
510
+ },
511
+ sdk,
512
+ costSummary: await resolveInscriptionCost(
513
+ waitId,
514
+ options.network || "mainnet",
515
+ options.logging?.level
516
+ )
517
+ };
518
+ } catch (error) {
519
+ logger.error("Error during inscription process", error);
520
+ throw error;
233
521
  }
234
- async listAgentFeedbackIndex(options = {}) {
235
- const params = new URLSearchParams();
236
- if (typeof options.page === "number" && Number.isFinite(options.page)) {
237
- params.set("page", String(Math.trunc(options.page)));
238
- }
239
- if (typeof options.limit === "number" && Number.isFinite(options.limit)) {
240
- params.set("limit", String(Math.trunc(options.limit)));
241
- }
242
- if (options.registries?.length) {
243
- params.set("registry", options.registries.join(","));
522
+ }
523
+ async function retrieveInscription(transactionId, options) {
524
+ const logger = Logger.getInstance({
525
+ module: "Inscriber",
526
+ ...options?.logging || {}
527
+ });
528
+ const formattedTransactionId = transactionId.includes("@") ? `${transactionId.split("@")[0]}-${transactionId.split("@")[1].replace(/\./g, "-")}` : transactionId;
529
+ logger.info("Retrieving inscription", {
530
+ originalTransactionId: transactionId,
531
+ formattedTransactionId
532
+ });
533
+ try {
534
+ let sdk;
535
+ if (options?.apiKey) {
536
+ logger.debug("Initializing InscriptionSDK with API key");
537
+ sdk = new InscriptionSDK({
538
+ apiKey: options.apiKey,
539
+ network: options.network || "mainnet",
540
+ baseURL: options.baseURL
541
+ });
542
+ } else if (options?.accountId && options?.privateKey) {
543
+ logger.debug("Initializing InscriptionSDK with server auth");
544
+ sdk = await InscriptionSDK.createWithAuth({
545
+ type: "server",
546
+ accountId: options.accountId,
547
+ privateKey: options.privateKey,
548
+ network: options.network || "mainnet",
549
+ baseUrl: options.baseURL
550
+ });
551
+ } else {
552
+ const error = new Error(
553
+ "Either API key or account ID and private key are required for retrieving inscriptions"
554
+ );
555
+ logger.error("Missing authentication credentials", {
556
+ hasApiKey: Boolean(options?.apiKey),
557
+ hasAccountId: Boolean(options?.accountId),
558
+ hasPrivateKey: Boolean(options?.privateKey)
559
+ });
560
+ throw error;
244
561
  }
245
- const suffix = params.size > 0 ? `?${params.toString()}` : "";
246
- const raw = await this.requestJson(`/agents/feedback${suffix}`, {
247
- method: "GET"
562
+ logger.debug("Initialized SDK for inscription retrieval", {
563
+ formattedTransactionId,
564
+ network: options.network || "mainnet"
248
565
  });
249
- return this.parseWithSchema(
250
- raw,
251
- agentFeedbackIndexResponseSchema,
252
- "agent feedback index response"
253
- );
566
+ const result = await sdk.retrieveInscription(formattedTransactionId);
567
+ logger.info("Successfully retrieved inscription", {
568
+ formattedTransactionId
569
+ });
570
+ return result;
571
+ } catch (error) {
572
+ logger.error("Error retrieving inscription", {
573
+ formattedTransactionId,
574
+ error
575
+ });
576
+ throw error;
254
577
  }
255
- async listAgentFeedbackEntriesIndex(options = {}) {
256
- const params = new URLSearchParams();
257
- if (typeof options.page === "number" && Number.isFinite(options.page)) {
258
- params.set("page", String(Math.trunc(options.page)));
259
- }
260
- if (typeof options.limit === "number" && Number.isFinite(options.limit)) {
261
- params.set("limit", String(Math.trunc(options.limit)));
262
- }
263
- if (options.registries?.length) {
264
- params.set("registry", options.registries.join(","));
265
- }
266
- const suffix = params.size > 0 ? `?${params.toString()}` : "";
267
- const raw = await this.requestJson(
268
- `/agents/feedback/entries${suffix}`,
269
- { method: "GET" }
270
- );
271
- return this.parseWithSchema(
272
- raw,
273
- agentFeedbackEntriesIndexResponseSchema,
274
- "agent feedback entries index response"
578
+ }
579
+ function validateHashinalMetadata(metadata, logger) {
580
+ const requiredFields = ["name", "creator", "description", "type"];
581
+ const missingFields = requiredFields.filter((field) => !metadata[field]);
582
+ if (missingFields.length > 0) {
583
+ const error = new Error(
584
+ `Missing required Hashinal metadata fields: ${missingFields.join(", ")}`
275
585
  );
276
- }
277
- async checkAgentFeedbackEligibility(uaid, payload) {
278
- const normalized = uaid.trim();
279
- if (!normalized) {
280
- throw new Error("uaid is required");
586
+ logger.error("Hashinal metadata validation failed", { missingFields });
587
+ throw error;
588
+ }
589
+ logger.debug("Hashinal metadata validation passed", {
590
+ name: metadata.name,
591
+ creator: metadata.creator,
592
+ description: metadata.description,
593
+ type: metadata.type,
594
+ hasAttributes: !!metadata.attributes,
595
+ hasProperties: !!metadata.properties
596
+ });
597
+ }
598
+ async function generateQuote(input, clientConfig, options, existingSDK) {
599
+ const logger = Logger.getInstance({
600
+ module: "Inscriber",
601
+ ...options.logging
602
+ });
603
+ logger.info("Generating inscription quote", {
604
+ type: input.type,
605
+ mode: options.mode || "file",
606
+ ...input.type === "url" ? { url: input.url } : {},
607
+ ...input.type === "file" ? { path: input.path } : {},
608
+ ...input.type === "buffer" ? { fileName: input.fileName, bufferSize: input.buffer.byteLength } : {}
609
+ });
610
+ try {
611
+ validateQuoteParameters(input, clientConfig, options);
612
+ const cachedQuote = getCachedQuote(input, clientConfig, options);
613
+ if (cachedQuote) {
614
+ logger.debug("Returning cached quote");
615
+ return {
616
+ confirmed: false,
617
+ quote: true,
618
+ result: cachedQuote
619
+ };
281
620
  }
282
- const raw = await this.requestJson(
283
- `/agents/${encodeURIComponent(normalized)}/feedback/eligibility`,
284
- {
285
- method: "POST",
286
- body: payload,
287
- headers: { "content-type": "application/json" }
621
+ if (options.mode === "hashinal" && options.metadata) {
622
+ validateHashinalMetadata(options.metadata, logger);
623
+ }
624
+ const sdk = await getOrCreateSDK(clientConfig, options, existingSDK);
625
+ const baseRequest = {
626
+ holderId: clientConfig.accountId,
627
+ metadata: options.metadata || {},
628
+ tags: options.tags || [],
629
+ mode: options.mode || "file",
630
+ fileStandard: options.fileStandard,
631
+ chunkSize: options.chunkSize
632
+ };
633
+ let request;
634
+ switch (input.type) {
635
+ case "url":
636
+ request = {
637
+ ...baseRequest,
638
+ file: {
639
+ type: "url",
640
+ url: input.url
641
+ }
642
+ };
643
+ break;
644
+ case "file": {
645
+ const fileData = await convertFileToBase64(input.path);
646
+ request = {
647
+ ...baseRequest,
648
+ file: {
649
+ type: "base64",
650
+ base64: fileData.base64,
651
+ fileName: fileData.fileName,
652
+ mimeType: fileData.mimeType
653
+ }
654
+ };
655
+ break;
288
656
  }
289
- );
290
- return this.parseWithSchema(
291
- raw,
292
- agentFeedbackEligibilityResponseSchema,
293
- "agent feedback eligibility response"
294
- );
295
- }
296
- async submitAgentFeedback(uaid, payload) {
297
- const normalized = uaid.trim();
298
- if (!normalized) {
299
- throw new Error("uaid is required");
300
- }
301
- const raw = await this.requestJson(
302
- `/agents/${encodeURIComponent(normalized)}/feedback`,
303
- {
304
- method: "POST",
305
- body: payload,
306
- headers: { "content-type": "application/json" }
657
+ case "buffer":
658
+ request = {
659
+ ...baseRequest,
660
+ file: {
661
+ type: "base64",
662
+ base64: Buffer.from(
663
+ input.buffer instanceof ArrayBuffer ? new Uint8Array(input.buffer) : input.buffer
664
+ ).toString("base64"),
665
+ fileName: input.fileName,
666
+ mimeType: input.mimeType
667
+ }
668
+ };
669
+ break;
670
+ }
671
+ if (options.mode === "hashinal") {
672
+ request.metadataObject = options.metadata;
673
+ request.creator = options.metadata?.creator || clientConfig.accountId;
674
+ request.description = options.metadata?.description;
675
+ if (options.jsonFileURL) {
676
+ request.jsonFileURL = options.jsonFileURL;
307
677
  }
308
- );
309
- return this.parseWithSchema(
310
- raw,
311
- agentFeedbackSubmissionResponseSchema,
312
- "agent feedback submission response"
313
- );
314
- }
315
- async search(params = {}) {
316
- return search(this, params);
317
- }
318
- async delegate(request) {
319
- return delegate(this, request);
320
- }
321
- async searchErc8004ByAgentId(params) {
322
- const chainId = Math.floor(params.chainId);
323
- if (!Number.isFinite(chainId) || chainId <= 0) {
324
- throw new Error("chainId must be a positive integer");
325
- }
326
- const rawAgentId = typeof params.agentId === "bigint" ? params.agentId.toString() : String(params.agentId);
327
- const agentId = rawAgentId.trim();
328
- if (!agentId) {
329
- throw new Error("agentId is required");
330
678
  }
331
- const nativeId = `${chainId}:${agentId}`;
332
- return search(this, {
333
- registries: ["erc-8004"],
334
- limit: params.limit ?? 1,
335
- ...typeof params.page === "number" ? { page: params.page } : {},
336
- ...typeof params.sortBy === "string" ? { sortBy: params.sortBy } : {},
337
- ...typeof params.sortOrder === "string" ? { sortOrder: params.sortOrder } : {},
338
- metadata: {
339
- nativeId: [nativeId],
340
- networkKey: [`eip155:${chainId}`]
341
- }
679
+ logger.debug("Calling inscription SDK startInscription for quote", {
680
+ type: input.type,
681
+ mode: options.mode || "file",
682
+ holderId: clientConfig.accountId
342
683
  });
343
- }
344
- async stats() {
345
- return stats(this);
346
- }
347
- async registries() {
348
- return registries(this);
349
- }
350
- async getAdditionalRegistries() {
351
- return getAdditionalRegistries(this);
352
- }
353
- async popularSearches() {
354
- return popularSearches(this);
355
- }
356
- async listProtocols() {
357
- return listProtocols(this);
358
- }
359
- async detectProtocol(message) {
360
- return detectProtocol(this, message);
361
- }
362
- async registrySearchByNamespace(registry, query) {
363
- return registrySearchByNamespace(this, registry, query);
364
- }
365
- async vectorSearch(request) {
366
- return vectorSearch(this, request);
367
- }
368
- async searchStatus() {
369
- return searchStatus(this);
370
- }
371
- async websocketStats() {
372
- return websocketStats(this);
373
- }
374
- async metricsSummary() {
375
- return metricsSummary(this);
376
- }
377
- async facets(adapter) {
378
- return facets(this, adapter);
379
- }
380
- async adapters() {
381
- return adapters(this);
382
- }
383
- async skillsConfig() {
384
- return skillsConfig(this);
385
- }
386
- async listSkills(options) {
387
- return listSkills(this, options);
388
- }
389
- async getSkillsCatalog(options) {
390
- return getSkillsCatalog(this, options);
391
- }
392
- async listSkillVersions(params) {
393
- return listSkillVersions(this, params);
394
- }
395
- async listMySkills(params) {
396
- return listMySkills(this, params);
397
- }
398
- async getMySkillsList(params) {
399
- return getMySkillsList(this, params);
400
- }
401
- async quoteSkillPublish(payload) {
402
- return quoteSkillPublish(this, payload);
403
- }
404
- async quoteSkillPublishPreview(payload) {
405
- return quoteSkillPublishPreview(this, payload);
406
- }
407
- async publishSkill(payload) {
408
- return publishSkill(this, payload);
409
- }
410
- async getSkillPublishJob(jobId, params) {
411
- return getSkillPublishJob(this, jobId, params);
412
- }
413
- async getSkillOwnership(params) {
414
- return getSkillOwnership(this, params);
415
- }
416
- async getRecommendedSkillVersion(params) {
417
- return getRecommendedSkillVersion(this, params);
418
- }
419
- async setRecommendedSkillVersion(payload) {
420
- return setRecommendedSkillVersion(this, payload);
421
- }
422
- async getSkillDeprecations(params) {
423
- return getSkillDeprecations(this, params);
424
- }
425
- async setSkillDeprecation(payload) {
426
- return setSkillDeprecation(this, payload);
427
- }
428
- async getSkillBadge(params) {
429
- return getSkillBadge(this, params);
430
- }
431
- async getSkillStatus(params) {
432
- return getSkillStatus(this, params);
433
- }
434
- async getSkillSecurityBreakdown(params) {
435
- return getSkillSecurityBreakdown(this, params);
436
- }
437
- async getSkillStatusByRepo(params) {
438
- return getSkillStatusByRepo(this, params);
439
- }
440
- async getSkillConversionSignalsByRepo(params) {
441
- return getSkillConversionSignalsByRepo(this, params);
442
- }
443
- async uploadSkillPreviewFromGithubOidc(payload) {
444
- return uploadSkillPreviewFromGithubOidc(this, payload);
445
- }
446
- async getSkillPreview(params) {
447
- return getSkillPreview(this, params);
448
- }
449
- async getSkillPreviewByRepo(params) {
450
- return getSkillPreviewByRepo(this, params);
451
- }
452
- async getSkillPreviewById(previewId) {
453
- return getSkillPreviewById(this, previewId);
454
- }
455
- async getSkillInstall(skillRef) {
456
- return getSkillInstall(this, skillRef);
457
- }
458
- async recordSkillInstallCopy(skillRef, payload) {
459
- return recordSkillInstallCopy(this, skillRef, payload);
460
- }
461
- async listSkillTags() {
462
- return listSkillTags(this);
463
- }
464
- async listSkillCategories() {
465
- return listSkillCategories(this);
466
- }
467
- async resolveSkillMarkdown(skillRef) {
468
- return resolveSkillMarkdown(this, skillRef);
469
- }
470
- async resolveSkillManifest(skillRef) {
471
- return resolveSkillManifest(this, skillRef);
472
- }
473
- async getSkillVoteStatus(params) {
474
- return getSkillVoteStatus(this, params);
475
- }
476
- async setSkillVote(payload) {
477
- return setSkillVote(this, payload);
478
- }
479
- async requestSkillVerification(payload) {
480
- return requestSkillVerification(this, payload);
481
- }
482
- async getSkillVerificationStatus(params) {
483
- return getSkillVerificationStatus(this, params);
484
- }
485
- async createSkillDomainProofChallenge(payload) {
486
- return createSkillDomainProofChallenge(this, payload);
487
- }
488
- async verifySkillDomainProof(payload) {
489
- return verifySkillDomainProof(this, payload);
490
- }
491
- async adaptersDetailed() {
492
- return adaptersDetailed(this);
493
- }
494
- async adapterRegistryCategories() {
495
- return adapterRegistryCategories(this);
496
- }
497
- async adapterRegistryAdapters(filters) {
498
- return adapterRegistryAdapters(this, filters);
499
- }
500
- async createAdapterRegistryCategory(payload) {
501
- return createAdapterRegistryCategory(this, payload);
502
- }
503
- async submitAdapterRegistryAdapter(payload) {
504
- return submitAdapterRegistryAdapter(this, payload);
505
- }
506
- async adapterRegistrySubmissionStatus(submissionId) {
507
- return adapterRegistrySubmissionStatus(this, submissionId);
508
- }
509
- async resolveUaid(uaid) {
510
- return resolveUaid(this, uaid);
511
- }
512
- async performRegisterAgent(payload) {
513
- const raw = await this.requestJson("/register", {
514
- method: "POST",
515
- body: serialiseAgentRegistrationRequest(payload),
516
- headers: { "content-type": "application/json" }
684
+ const inscriptionResponse = await sdk.startInscription(request);
685
+ logger.debug("Received inscription response for quote parsing", {
686
+ hasTransactionBytes: !!inscriptionResponse.transactionBytes,
687
+ bytesLength: inscriptionResponse.transactionBytes?.length || 0,
688
+ transactionBytesType: typeof inscriptionResponse.transactionBytes,
689
+ totalCost: inscriptionResponse.totalCost
517
690
  });
518
- return this.parseWithSchema(
519
- raw,
520
- registerAgentResponseSchema,
521
- "register agent response"
522
- );
523
- }
524
- calculateHbarAmount(creditsToPurchase, creditsPerHbar) {
525
- if (creditsPerHbar <= 0) {
526
- throw new Error("creditsPerHbar must be positive");
527
- }
528
- if (creditsToPurchase <= 0) {
529
- throw new Error("creditsToPurchase must be positive");
530
- }
531
- const rawHbar = creditsToPurchase / creditsPerHbar;
532
- const tinybars = Math.ceil(rawHbar * 1e8);
533
- return tinybars / 1e8;
534
- }
535
- resolveCreditsToPurchase(shortfallCredits) {
536
- if (!Number.isFinite(shortfallCredits) || shortfallCredits <= 0) {
537
- return 0;
538
- }
539
- return Math.max(
540
- Math.ceil(shortfallCredits),
541
- MINIMUM_REGISTRATION_AUTO_TOP_UP_CREDITS
691
+ const quote = await parseTransactionForQuote(
692
+ inscriptionResponse,
693
+ logger
542
694
  );
695
+ cacheQuote(input, clientConfig, options, quote);
696
+ logger.info("Successfully generated inscription quote", {
697
+ totalCostHbar: quote.totalCostHbar
698
+ });
699
+ return {
700
+ confirmed: false,
701
+ quote: true,
702
+ result: quote
703
+ };
704
+ } catch (error) {
705
+ logger.error("Error generating inscription quote", error);
706
+ throw error;
543
707
  }
544
- async ensureCreditsForRegistration(payload, autoTopUp) {
545
- const details = autoTopUp ?? null;
546
- if (!details) {
547
- return;
548
- }
549
- if (!details.accountId || !details.accountId.trim()) {
550
- throw new Error("autoTopUp.accountId is required");
551
- }
552
- if (!details.privateKey || !details.privateKey.trim()) {
553
- throw new Error("autoTopUp.privateKey is required");
554
- }
555
- for (let attempt = 0; attempt < 3; attempt += 1) {
556
- const quote = await this.getRegistrationQuote(payload);
557
- const shortfall = quote.shortfallCredits ?? 0;
558
- if (shortfall <= 0) {
559
- return;
560
- }
561
- const creditsToPurchase = this.resolveCreditsToPurchase(shortfall);
562
- if (creditsToPurchase <= 0) {
563
- return;
564
- }
565
- const creditsPerHbar = quote.creditsPerHbar ?? null;
566
- if (!creditsPerHbar || creditsPerHbar <= 0) {
567
- throw new Error("Unable to determine credits per HBAR for auto top-up");
568
- }
569
- const hbarAmount = this.calculateHbarAmount(
570
- creditsToPurchase,
571
- creditsPerHbar
572
- );
573
- await this.purchaseCreditsWithHbar({
574
- accountId: details.accountId.trim(),
575
- privateKey: details.privateKey.trim(),
576
- hbarAmount,
577
- memo: details.memo ?? "Registry Broker auto top-up",
578
- metadata: {
579
- shortfallCredits: shortfall,
580
- requiredCredits: quote.requiredCredits,
581
- purchasedCredits: creditsToPurchase
582
- }
708
+ }
709
+ async function parseTransactionForQuote(inscriptionResponse, logger) {
710
+ try {
711
+ let totalCostHbar = "0.001";
712
+ if (inscriptionResponse.totalCost && typeof inscriptionResponse.totalCost === "number") {
713
+ const hbarAmount = inscriptionResponse.totalCost / 1e8;
714
+ totalCostHbar = hbarAmount.toString();
715
+ logger.debug("Using totalCost from inscription response", {
716
+ totalCostTinybars: inscriptionResponse.totalCost,
717
+ totalCostHbar
583
718
  });
584
- }
585
- const finalQuote = await this.getRegistrationQuote(payload);
586
- if ((finalQuote.shortfallCredits ?? 0) > 0) {
587
- throw new Error("Unable to purchase sufficient credits for registration");
588
- }
589
- }
590
- async registerAgent(payload, options) {
591
- const autoTopUp = options?.autoTopUp ?? this.registrationAutoTopUp;
592
- if (!autoTopUp) {
593
- return this.performRegisterAgent(payload);
594
- }
595
- await this.ensureCreditsForRegistration(payload, autoTopUp);
596
- let retried = false;
597
- while (true) {
719
+ } else if (inscriptionResponse.transactionBytes) {
720
+ logger.debug("Parsing transaction bytes for cost information");
598
721
  try {
599
- return await this.performRegisterAgent(payload);
600
- } catch (error) {
601
- const shortfall = this.extractInsufficientCreditsDetails(error);
602
- if (shortfall && !retried) {
603
- await this.ensureCreditsForRegistration(payload, autoTopUp);
604
- retried = true;
605
- continue;
722
+ let transactionBytesString;
723
+ if (typeof inscriptionResponse.transactionBytes === "string") {
724
+ transactionBytesString = inscriptionResponse.transactionBytes;
725
+ } else if (inscriptionResponse.transactionBytes && typeof inscriptionResponse.transactionBytes === "object" && "data" in inscriptionResponse.transactionBytes) {
726
+ const buffer = Buffer.from(inscriptionResponse.transactionBytes.data);
727
+ transactionBytesString = buffer.toString("base64");
728
+ } else {
729
+ throw new Error("Invalid transactionBytes format");
730
+ }
731
+ logger.debug("About to parse transaction bytes", {
732
+ bytesLength: transactionBytesString.length,
733
+ bytesPreview: transactionBytesString.slice(0, 100)
734
+ });
735
+ const parsedTransaction = await TransactionParser.parseTransactionBytes(
736
+ transactionBytesString,
737
+ { includeRaw: false }
738
+ );
739
+ logger.debug("Parsed transaction for quote", {
740
+ type: parsedTransaction.type,
741
+ hasTransfers: !!parsedTransaction.transfers,
742
+ transferCount: parsedTransaction.transfers?.length || 0,
743
+ transfers: parsedTransaction.transfers
744
+ });
745
+ let totalTransferAmount = 0;
746
+ if (parsedTransaction.transfers && parsedTransaction.transfers.length > 0) {
747
+ for (const transfer of parsedTransaction.transfers) {
748
+ const transferAmount = typeof transfer.amount === "string" ? parseFloat(transfer.amount) : transfer.amount;
749
+ if (transferAmount < 0) {
750
+ const amountHbar = Math.abs(transferAmount);
751
+ totalTransferAmount += amountHbar;
752
+ logger.debug("Found HBAR transfer", {
753
+ from: transfer.accountId,
754
+ to: "service",
755
+ amount: amountHbar
756
+ });
757
+ }
758
+ }
606
759
  }
607
- throw error;
760
+ if (totalTransferAmount > 0) {
761
+ totalCostHbar = totalTransferAmount.toString();
762
+ logger.debug("Using parsed transaction transfer amount", {
763
+ totalTransferAmount,
764
+ totalCostHbar
765
+ });
766
+ }
767
+ } catch (parseError) {
768
+ logger.warn(
769
+ "Could not parse transaction bytes, using totalCost fallback",
770
+ {
771
+ error: parseError,
772
+ errorMessage: parseError instanceof Error ? parseError.message : String(parseError)
773
+ }
774
+ );
608
775
  }
609
776
  }
610
- }
611
- async getRegistrationQuote(payload) {
612
- return getRegistrationQuote(this, payload);
613
- }
614
- async updateAgent(uaid, payload) {
615
- return updateAgent(this, uaid, payload);
616
- }
617
- async getRegisterStatus(uaid) {
618
- return getRegisterStatus(this, uaid);
619
- }
620
- async registerOwnedMoltbookAgent(uaid, payload) {
621
- return registerOwnedMoltbookAgent(this, uaid, payload);
622
- }
623
- async getRegistrationProgress(attemptId) {
624
- return getRegistrationProgress(this, attemptId);
625
- }
626
- async waitForRegistrationCompletion(attemptId, options) {
627
- return waitForRegistrationCompletion(this, attemptId, options);
628
- }
629
- async validateUaid(uaid) {
630
- return validateUaid(this, uaid);
631
- }
632
- async getUaidConnectionStatus(uaid) {
633
- return getUaidConnectionStatus(this, uaid);
634
- }
635
- async closeUaidConnection(uaid) {
636
- return closeUaidConnection(this, uaid);
637
- }
638
- async dashboardStats() {
639
- return dashboardStats(this);
640
- }
641
- async getCreditsBalance(params = {}) {
642
- return getCreditsBalance(this, params);
643
- }
644
- async getCreditProviders() {
645
- return getCreditProviders(this);
646
- }
647
- async getGuardSession() {
648
- return getGuardSession(this);
649
- }
650
- async getGuardEntitlements() {
651
- return getGuardEntitlements(this);
652
- }
653
- async getGuardBillingBalance() {
654
- return getGuardBillingBalance(this);
655
- }
656
- async getGuardFeed(limit) {
657
- return getGuardFeed(this, limit);
658
- }
659
- async getGuardOverview() {
660
- return getGuardOverview(this);
661
- }
662
- async getGuardTrustByHash(sha256) {
663
- return getGuardTrustByHash(this, sha256);
664
- }
665
- async resolveGuardTrust(query) {
666
- return resolveGuardTrust(this, query);
667
- }
668
- async getGuardRevocations() {
669
- return getGuardRevocations(this);
670
- }
671
- async fetchGuardAdvisories() {
672
- return fetchGuardAdvisories(this);
673
- }
674
- async fetchGuardPolicy() {
675
- return fetchGuardPolicy(this);
676
- }
677
- async getGuardInventory() {
678
- return getGuardInventory(this);
679
- }
680
- async getGuardReceiptHistory() {
681
- return getGuardReceiptHistory(this);
682
- }
683
- async getGuardArtifactTimeline(artifactId) {
684
- return getGuardArtifactTimeline(this, artifactId);
685
- }
686
- async getGuardInventoryDiff() {
687
- return getGuardInventoryDiff(this);
688
- }
689
- async exportGuardAbom() {
690
- return exportGuardAbom(this);
691
- }
692
- async exportGuardArtifactAbom(artifactId) {
693
- return exportGuardArtifactAbom(this, artifactId);
694
- }
695
- async exportGuardReceipts() {
696
- return exportGuardReceipts(this);
697
- }
698
- async getGuardDevices() {
699
- return getGuardDevices(this);
700
- }
701
- async getGuardAlertPreferences() {
702
- return getGuardAlertPreferences(this);
703
- }
704
- async updateGuardAlertPreferences(payload) {
705
- return updateGuardAlertPreferences(this, payload);
706
- }
707
- async getGuardExceptions() {
708
- return getGuardExceptions(this);
709
- }
710
- async getGuardWatchlist() {
711
- return getGuardWatchlist(this);
712
- }
713
- async lookupGuardWatchlist(payload) {
714
- return lookupGuardWatchlist(this, payload);
715
- }
716
- async getGuardPainSignals() {
717
- return getGuardPainSignals(this);
718
- }
719
- async getGuardAggregatedPainSignals() {
720
- return getGuardAggregatedPainSignals(this);
721
- }
722
- async getGuardPreInstallVerdict(payload) {
723
- return getGuardPreInstallVerdict(this, payload);
724
- }
725
- async getGuardPreExecutionVerdict(payload) {
726
- return getGuardPreExecutionVerdict(this, payload);
727
- }
728
- async addGuardWatchlistItem(payload) {
729
- return addGuardWatchlistItem(this, payload);
730
- }
731
- async removeGuardWatchlistItem(artifactId) {
732
- return removeGuardWatchlistItem(this, artifactId);
733
- }
734
- async addGuardException(payload) {
735
- return addGuardException(this, payload);
736
- }
737
- async requestGuardException(payload) {
738
- return requestGuardException(this, payload);
739
- }
740
- async removeGuardException(exceptionId) {
741
- return removeGuardException(this, exceptionId);
742
- }
743
- async ingestGuardPainSignals(items) {
744
- return ingestGuardPainSignals(this, items);
745
- }
746
- async syncGuardReceipts(payload) {
747
- return syncGuardReceipts(this, payload);
748
- }
749
- async syncGuardInventory(payload) {
750
- return syncGuardInventory(this, payload);
751
- }
752
- async submitGuardReceipts(payload) {
753
- return submitGuardReceipts(this, payload);
754
- }
755
- async getGuardTeamPolicyPack() {
756
- return getGuardTeamPolicyPack(this);
757
- }
758
- async updateGuardTeamPolicyPack(payload) {
759
- return updateGuardTeamPolicyPack(this, payload);
760
- }
761
- async createHbarPurchaseIntent(payload) {
762
- return createHbarPurchaseIntent(this, payload);
763
- }
764
- async purchaseCreditsWithHbar(params) {
765
- return purchaseCreditsWithHbar(this, params);
766
- }
767
- async getX402Minimums() {
768
- return getX402Minimums(this);
769
- }
770
- async purchaseCreditsWithX402(params) {
771
- return purchaseCreditsWithX402(this, params);
772
- }
773
- async buyCreditsWithX402(params) {
774
- return buyCreditsWithX402(this, params);
775
- }
776
- async generateEncryptionKeyPair(options = {}) {
777
- return generateEncryptionKeyPair(this, options);
778
- }
779
- async createLedgerChallenge(payload) {
780
- return createLedgerChallenge(this, payload);
781
- }
782
- async verifyLedgerChallenge(payload) {
783
- return verifyLedgerChallenge(this, payload);
784
- }
785
- async authenticateWithLedger(options) {
786
- return authenticateWithLedger(this, options);
787
- }
788
- async authenticateWithLedgerCredentials(options) {
789
- return authenticateWithLedgerCredentials(this, options);
790
- }
791
- async getVerificationStatus(uaid) {
792
- return getVerificationStatus(this, uaid);
793
- }
794
- async createVerificationChallenge(uaid) {
795
- return createVerificationChallenge(this, uaid);
796
- }
797
- async getVerificationChallenge(challengeId) {
798
- return getVerificationChallenge(this, challengeId);
799
- }
800
- async verifyVerificationChallenge(params) {
801
- return verifyVerificationChallenge(this, params);
802
- }
803
- async getVerificationOwnership(uaid) {
804
- return getVerificationOwnership(this, uaid);
805
- }
806
- async verifySenderOwnership(uaid) {
807
- return verifySenderOwnership(this, uaid);
808
- }
809
- async verifyUaidDnsTxt(payload) {
810
- return verifyUaidDnsTxt(this, payload);
811
- }
812
- async getVerificationDnsStatus(uaid, query) {
813
- return getVerificationDnsStatus(this, uaid, query);
814
- }
815
- async fetchHistorySnapshot(sessionId, options) {
816
- return fetchHistorySnapshot(
817
- this.conversationContexts,
818
- this,
819
- sessionId,
820
- options
821
- );
822
- }
823
- attachDecryptedHistory(sessionId, snapshot, options) {
824
- return attachDecryptedHistory(
825
- this.conversationContexts,
826
- this,
827
- sessionId,
828
- snapshot,
829
- options
830
- );
831
- }
832
- registerConversationContextForEncryption(context) {
833
- registerConversationContextForEncryption(
834
- this.conversationContexts,
835
- context
836
- );
837
- }
838
- resolveDecryptionContext(sessionId, options) {
839
- return resolveDecryptionContext(
840
- this.conversationContexts,
841
- this,
842
- sessionId,
843
- options
844
- );
845
- }
846
- decryptHistoryEntryFromContext(_sessionId, entry, context) {
847
- return decryptHistoryEntryFromContext(this, entry, context);
848
- }
849
- async createSession(payload, allowHistoryAutoTopUp = true) {
850
- return createSession(this, payload, allowHistoryAutoTopUp);
851
- }
852
- async resumeSession(sessionId) {
853
- return resumeSession(this, sessionId);
854
- }
855
- async checkChatReadiness(payload) {
856
- return checkChatReadiness(this, payload);
857
- }
858
- async startChat(options) {
859
- return startChat(this, this.getEncryptedChatManager(), options);
860
- }
861
- async startConversation(options) {
862
- return startConversation(this, this.getEncryptedChatManager(), options);
863
- }
864
- async acceptConversation(options) {
865
- return acceptConversation(
866
- this,
867
- this.getEncryptedChatManager(),
868
- options
869
- );
870
- }
871
- compactHistory(payload) {
872
- return compactHistory(this, payload);
873
- }
874
- fetchEncryptionStatus(sessionId) {
875
- return fetchEncryptionStatus(this, sessionId);
876
- }
877
- postEncryptionHandshake(sessionId, payload) {
878
- return postEncryptionHandshake(this, sessionId, payload);
879
- }
880
- sendMessage(payload) {
881
- return sendMessage(this, payload);
882
- }
883
- retryMessage(messageId, payload) {
884
- return retryMessage(this, messageId, payload);
885
- }
886
- cancelSession(sessionId) {
887
- return cancelSession(this, sessionId);
888
- }
889
- endSession(sessionId) {
890
- return endSession(this, sessionId);
891
- }
892
- createPlaintextConversationHandle(sessionId, summary, defaultAuth, context) {
893
- return createPlaintextConversationHandle(
894
- this,
895
- sessionId,
896
- summary,
897
- defaultAuth,
898
- context
899
- );
900
- }
901
- getEncryptedChatManager() {
902
- if (this.encryptedChatManager) {
903
- return this.encryptedChatManager;
904
- }
905
- const manager = new EncryptedChatManager(this);
906
- this.encryptedChatManager = manager;
907
- return manager;
908
- }
909
- async extractErrorBody(response) {
910
- const contentType = response.headers?.get("content-type") ?? "";
911
- if (JSON_CONTENT_TYPE.test(contentType)) {
912
- try {
913
- return await response.json();
914
- } catch (error) {
915
- return { parseError: String(error) };
777
+ const transfers = [
778
+ {
779
+ to: "Inscription Service",
780
+ amount: totalCostHbar,
781
+ description: `Inscription fee (${totalCostHbar} HBAR)`
916
782
  }
917
- }
918
- try {
919
- return await response.text();
920
- } catch (error) {
921
- return { parseError: String(error) };
922
- }
783
+ ];
784
+ const validUntil = new Date(Date.now() + 15 * 60 * 1e3).toISOString();
785
+ const quote = {
786
+ totalCostHbar,
787
+ validUntil,
788
+ breakdown: {
789
+ transfers
790
+ }
791
+ };
792
+ logger.debug("Successfully parsed transaction for quote", {
793
+ totalCostHbar: quote.totalCostHbar,
794
+ transferCount: transfers.length,
795
+ hasTransactionBytes: !!inscriptionResponse.transactionBytes,
796
+ hasTotalCost: !!inscriptionResponse.totalCost
797
+ });
798
+ return quote;
799
+ } catch (error) {
800
+ logger.error("Error parsing transaction for quote", error);
801
+ throw error;
923
802
  }
924
- parseWithSchema(value, schema, context) {
803
+ }
804
+ async function waitForInscriptionConfirmation(sdk, transactionId, maxAttempts = 450, intervalMs = 4e3, progressCallback) {
805
+ const logger = Logger.getInstance({ module: "Inscriber" });
806
+ const normalizedId = normalizeTransactionId(transactionId);
807
+ const progressReporter = new ProgressReporter({
808
+ module: "Inscriber",
809
+ logger,
810
+ callback: progressCallback
811
+ });
812
+ try {
813
+ logger.debug("Waiting for inscription confirmation", {
814
+ transactionId: normalizedId,
815
+ maxAttempts,
816
+ intervalMs
817
+ });
818
+ progressReporter.preparing("Preparing for inscription confirmation", 5, {
819
+ transactionId: normalizedId,
820
+ maxAttempts,
821
+ intervalMs
822
+ });
925
823
  try {
926
- return schema.parse(value);
927
- } catch (error) {
928
- throw new RegistryBrokerParseError(
929
- `Failed to parse ${context}`,
930
- error instanceof ZodError || error instanceof Error ? error : String(error),
931
- value
824
+ const waitMethod = sdk.waitForInscription.bind(sdk);
825
+ const wrappedCallback = (data) => {
826
+ const stageRaw = data.stage || "confirming";
827
+ const allowedStages = [
828
+ "preparing",
829
+ "submitting",
830
+ "confirming",
831
+ "verifying",
832
+ "completed",
833
+ "failed"
834
+ ];
835
+ const stage = allowedStages.includes(stageRaw) ? stageRaw : "confirming";
836
+ const message = data.message || "Processing inscription";
837
+ const percent = data.progressPercent || 50;
838
+ progressReporter.report({
839
+ stage,
840
+ message,
841
+ progressPercent: percent,
842
+ details: data.details
843
+ });
844
+ };
845
+ return await waitMethod(
846
+ normalizedId,
847
+ maxAttempts,
848
+ intervalMs,
849
+ true,
850
+ wrappedCallback
851
+ );
852
+ } catch (e) {
853
+ logger.debug("Falling back to standard waitForInscription method", {
854
+ error: e
855
+ });
856
+ progressReporter.verifying("Verifying inscription status", 50, {
857
+ error: e
858
+ });
859
+ return await sdk.waitForInscription(
860
+ normalizedId,
861
+ maxAttempts,
862
+ intervalMs,
863
+ true
932
864
  );
933
865
  }
934
- }
935
- async delay(ms, signal) {
936
- if (ms <= 0) {
937
- if (signal?.aborted) {
938
- throw createAbortError();
939
- }
940
- return;
941
- }
942
- await new Promise((resolve, reject) => {
943
- const timer = setTimeout(() => {
944
- if (signal) {
945
- signal.removeEventListener("abort", onAbort);
946
- }
947
- resolve();
948
- }, ms);
949
- const onAbort = () => {
950
- clearTimeout(timer);
951
- signal?.removeEventListener("abort", onAbort);
952
- reject(createAbortError());
953
- };
954
- if (signal) {
955
- if (signal.aborted) {
956
- clearTimeout(timer);
957
- reject(createAbortError());
958
- return;
959
- }
960
- signal.addEventListener("abort", onAbort, { once: true });
961
- }
866
+ } catch (error) {
867
+ logger.error("Error waiting for inscription confirmation", {
868
+ transactionId,
869
+ maxAttempts,
870
+ intervalMs,
871
+ error
962
872
  });
873
+ progressReporter.failed("Inscription confirmation failed", {
874
+ transactionId,
875
+ error
876
+ });
877
+ throw error;
963
878
  }
964
- assertNodeRuntime(feature) {
965
- if (typeof process === "undefined" || !process.versions?.node) {
966
- throw new Error(`${feature} is only available in Node.js environments`);
967
- }
968
- }
969
- getNodeCrypto(feature) {
970
- this.assertNodeRuntime(feature);
971
- const nodeCrypto = optionalImportSync("node:crypto") ?? optionalImportSync("crypto");
972
- if (!nodeCrypto) {
973
- throw new Error(`${feature} requires the Node.js crypto module`);
974
- }
975
- return nodeCrypto;
976
- }
977
- getSecureRandomBytes(size, feature) {
978
- const webCrypto = globalThis.crypto;
979
- if (webCrypto && typeof webCrypto.getRandomValues === "function") {
980
- const bytes = new Uint8Array(size);
981
- webCrypto.getRandomValues(bytes);
982
- return bytes;
983
- }
984
- return this.getNodeCrypto(feature).randomBytes(size);
985
- }
986
- createEphemeralKeyPair() {
987
- const privateKeyBytes = this.getSecureRandomBytes(
988
- 32,
989
- "generateEphemeralKeyPair"
879
+ }
880
+ const DEFAULT_REGISTRY_BROKER_URL = "https://hol.org/registry/api/v1";
881
+ const DEFAULT_POLL_INTERVAL_MS = 2e3;
882
+ const DEFAULT_WAIT_TIMEOUT_MS = 12e4;
883
+ async function fetchRegistryBroker(url, options) {
884
+ const response = await fetch(url, options);
885
+ const body = await response.json().catch(() => ({}));
886
+ if (!response.ok) {
887
+ const errorMessage = typeof body === "object" && body && "error" in body ? String(body.error) : `HTTP ${response.status}`;
888
+ throw new Error(errorMessage);
889
+ }
890
+ return body;
891
+ }
892
+ async function inscribeViaRegistryBroker(input, options = {}) {
893
+ const logger = Logger.getInstance({
894
+ module: "InscribeViaBroker",
895
+ ...options.logging
896
+ });
897
+ const baseUrl = options.baseUrl ?? DEFAULT_REGISTRY_BROKER_URL;
898
+ const waitForConfirmation = options.waitForConfirmation ?? true;
899
+ const waitTimeoutMs = options.waitTimeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
900
+ const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
901
+ const headers = {
902
+ "Content-Type": "application/json",
903
+ Accept: "application/json"
904
+ };
905
+ if (options.ledgerApiKey) {
906
+ headers["x-api-key"] = options.ledgerApiKey;
907
+ } else if (options.apiKey) {
908
+ headers["x-api-key"] = options.apiKey;
909
+ } else {
910
+ throw new Error(
911
+ "Either ledgerApiKey or apiKey is required for Registry Broker inscription"
990
912
  );
991
- const publicKey = secp256k1.getPublicKey(privateKeyBytes, true);
992
- return {
993
- privateKey: Buffer.from(privateKeyBytes).toString("hex"),
994
- publicKey: Buffer.from(publicKey).toString("hex")
995
- };
996
- }
997
- deriveSharedSecret(options) {
998
- const { createHash } = this.getNodeCrypto("deriveSharedSecret");
999
- const privateKey = this.hexToBuffer(options.privateKey);
1000
- const peerPublicKey = this.hexToBuffer(options.peerPublicKey);
1001
- const shared = secp256k1.getSharedSecret(privateKey, peerPublicKey, true);
1002
- return createHash("sha256").update(Buffer.from(shared)).digest();
1003
913
  }
1004
- buildCipherEnvelope(options) {
1005
- const { createCipheriv, randomBytes } = this.getNodeCrypto(
1006
- "encryptCipherEnvelope"
1007
- );
1008
- const sharedSecret = this.normalizeSharedSecret(options.sharedSecret);
1009
- const iv = randomBytes(12);
1010
- const cipher = createCipheriv("aes-256-gcm", sharedSecret, iv);
1011
- const aadSource = options.associatedData ?? options.sessionId;
1012
- const associatedDataEncoded = aadSource ? Buffer.from(aadSource, "utf8").toString("base64") : void 0;
1013
- if (aadSource) {
1014
- cipher.setAAD(Buffer.from(aadSource, "utf8"));
914
+ logger.info("Starting inscription via Registry Broker", {
915
+ baseUrl,
916
+ inputType: input.type,
917
+ mode: options.mode ?? "file"
918
+ });
919
+ let base64Content;
920
+ let fileName;
921
+ let mimeType;
922
+ switch (input.type) {
923
+ case "url":
924
+ logger.debug("Creating job with URL input");
925
+ break;
926
+ case "file": {
927
+ const fileData = await convertFileToBase64(input.path);
928
+ base64Content = fileData.base64;
929
+ fileName = fileData.fileName;
930
+ mimeType = fileData.mimeType;
931
+ break;
932
+ }
933
+ case "buffer":
934
+ base64Content = Buffer.from(
935
+ input.buffer instanceof ArrayBuffer ? new Uint8Array(input.buffer) : input.buffer
936
+ ).toString("base64");
937
+ fileName = input.fileName;
938
+ mimeType = input.mimeType;
939
+ break;
940
+ }
941
+ const requestBody = {
942
+ inputType: input.type === "url" ? "url" : "base64",
943
+ mode: options.mode ?? "file"
944
+ };
945
+ if (input.type === "url") {
946
+ requestBody.url = input.url;
947
+ } else {
948
+ requestBody.base64 = base64Content;
949
+ requestBody.fileName = fileName;
950
+ if (mimeType) {
951
+ requestBody.mimeType = mimeType;
952
+ }
953
+ }
954
+ if (options.metadata) {
955
+ requestBody.metadata = options.metadata;
956
+ }
957
+ if (options.tags) {
958
+ requestBody.tags = options.tags;
959
+ }
960
+ if (options.fileStandard) {
961
+ requestBody.fileStandard = options.fileStandard;
962
+ }
963
+ if (options.chunkSize) {
964
+ requestBody.chunkSize = options.chunkSize;
965
+ }
966
+ logger.debug("Creating inscription job");
967
+ const job = await fetchRegistryBroker(
968
+ `${baseUrl}/inscribe/content`,
969
+ {
970
+ method: "POST",
971
+ headers,
972
+ body: JSON.stringify(requestBody)
1015
973
  }
1016
- const ciphertext = Buffer.concat([
1017
- cipher.update(Buffer.from(options.plaintext, "utf8")),
1018
- cipher.final()
1019
- ]);
1020
- const tag = cipher.getAuthTag();
1021
- const payload = Buffer.concat([ciphertext, tag]);
974
+ );
975
+ const jobId = job.jobId ?? job.id ?? "";
976
+ logger.info("Inscription job created", { jobId, status: job.status });
977
+ if (!waitForConfirmation) {
1022
978
  return {
1023
- algorithm: "aes-256-gcm",
1024
- ciphertext: payload.toString("base64"),
1025
- nonce: iv.toString("base64"),
1026
- associatedData: associatedDataEncoded,
1027
- keyLocator: {
1028
- sessionId: options.sessionId,
1029
- revision: options.revision ?? 1
1030
- },
1031
- recipients: options.recipients.map((recipient) => ({
1032
- ...recipient,
1033
- encryptedShare: ""
1034
- }))
979
+ confirmed: false,
980
+ jobId,
981
+ status: job.status,
982
+ credits: job.credits ?? job.quoteCredits,
983
+ usdCents: job.usdCents ?? job.quoteUsdCents,
984
+ sizeBytes: job.sizeBytes,
985
+ createdAt: job.createdAt,
986
+ updatedAt: job.updatedAt,
987
+ network: job.network
1035
988
  };
1036
989
  }
1037
- openCipherEnvelope(options) {
1038
- const { createDecipheriv } = this.getNodeCrypto("decryptCipherEnvelope");
1039
- const sharedSecret = this.normalizeSharedSecret(options.sharedSecret);
1040
- const payload = Buffer.from(options.envelope.ciphertext, "base64");
1041
- const nonce = Buffer.from(options.envelope.nonce, "base64");
1042
- const ciphertext = payload.slice(0, payload.length - 16);
1043
- const tag = payload.slice(payload.length - 16);
1044
- const decipher = createDecipheriv("aes-256-gcm", sharedSecret, nonce);
1045
- if (options.envelope.associatedData) {
1046
- decipher.setAAD(Buffer.from(options.envelope.associatedData, "base64"));
1047
- }
1048
- decipher.setAuthTag(tag);
1049
- const plaintext = Buffer.concat([
1050
- decipher.update(ciphertext),
1051
- decipher.final()
1052
- ]);
1053
- return plaintext.toString(options.encoding ?? "utf8");
1054
- }
1055
- normalizeSharedSecret(input) {
1056
- if (Buffer.isBuffer(input)) {
1057
- return Buffer.from(input);
1058
- }
1059
- if (input instanceof Uint8Array) {
1060
- return Buffer.from(input);
1061
- }
1062
- if (typeof input === "string") {
1063
- return this.bufferFromString(input);
1064
- }
1065
- throw new Error("Unsupported shared secret input");
1066
- }
1067
- bufferFromString(value) {
1068
- const trimmed = value.trim();
1069
- if (!trimmed) {
1070
- throw new Error("sharedSecret string cannot be empty");
1071
- }
1072
- const normalized = trimmed.startsWith("0x") ? trimmed.slice(2) : trimmed;
1073
- if (/^[0-9a-fA-F]+$/.test(normalized) && normalized.length % 2 === 0) {
1074
- return Buffer.from(normalized, "hex");
1075
- }
1076
- return Buffer.from(trimmed, "base64");
1077
- }
1078
- hexToBuffer(value) {
1079
- const normalized = value.startsWith("0x") ? value.slice(2) : value;
1080
- if (!/^[0-9a-fA-F]+$/.test(normalized) || normalized.length % 2 !== 0) {
1081
- throw new Error("Expected hex-encoded value");
1082
- }
1083
- return Buffer.from(normalized, "hex");
1084
- }
1085
- extractInsufficientCreditsDetails(error) {
1086
- if (!(error instanceof RegistryBrokerError) || error.status !== 402) {
1087
- return null;
1088
- }
1089
- const body = error.body;
1090
- if (!body || typeof body !== "object" || Array.isArray(body)) {
1091
- return null;
1092
- }
1093
- const maybeShortfall = body["shortfallCredits"];
1094
- if (typeof maybeShortfall !== "number" || maybeShortfall <= 0) {
1095
- return null;
1096
- }
1097
- return { shortfallCredits: maybeShortfall };
1098
- }
1099
- extractErrorMessage(body) {
1100
- if (typeof body === "string") {
1101
- return body;
1102
- }
1103
- if (isJsonObject(body) && typeof body.error === "string") {
1104
- return body.error;
990
+ logger.debug("Polling for job completion", { jobId, waitTimeoutMs });
991
+ const startTime = Date.now();
992
+ let lastStatus = "";
993
+ while (Date.now() - startTime < waitTimeoutMs) {
994
+ const currentJob = await fetchRegistryBroker(
995
+ `${baseUrl}/inscribe/content/${jobId}`,
996
+ { method: "GET", headers }
997
+ );
998
+ if (currentJob.status !== lastStatus) {
999
+ logger.debug("Job status update", { jobId, status: currentJob.status });
1000
+ lastStatus = currentJob.status;
1001
+ }
1002
+ if (currentJob.status === "completed") {
1003
+ logger.info("Inscription completed", {
1004
+ jobId,
1005
+ hrl: currentJob.hrl,
1006
+ topicId: currentJob.topicId
1007
+ });
1008
+ return {
1009
+ confirmed: true,
1010
+ jobId,
1011
+ status: currentJob.status,
1012
+ hrl: currentJob.hrl,
1013
+ topicId: currentJob.topicId,
1014
+ network: currentJob.network,
1015
+ credits: currentJob.credits ?? currentJob.quoteCredits,
1016
+ usdCents: currentJob.usdCents ?? currentJob.quoteUsdCents,
1017
+ sizeBytes: currentJob.sizeBytes,
1018
+ createdAt: currentJob.createdAt,
1019
+ updatedAt: currentJob.updatedAt
1020
+ };
1105
1021
  }
1106
- if (isJsonObject(body) && typeof body.message === "string") {
1107
- return body.message;
1022
+ if (currentJob.status === "failed") {
1023
+ logger.error("Inscription failed", { jobId, error: currentJob.error });
1024
+ return {
1025
+ confirmed: false,
1026
+ jobId,
1027
+ status: currentJob.status,
1028
+ error: currentJob.error ?? "Inscription failed",
1029
+ credits: currentJob.credits ?? currentJob.quoteCredits,
1030
+ createdAt: currentJob.createdAt,
1031
+ updatedAt: currentJob.updatedAt
1032
+ };
1108
1033
  }
1109
- return void 0;
1034
+ await sleep(pollIntervalMs);
1110
1035
  }
1111
- shouldAutoTopUpHistory(payload, error) {
1112
- if (!this.historyAutoTopUp || payload.historyTtlSeconds === void 0) {
1113
- return false;
1114
- }
1115
- if (!(error instanceof RegistryBrokerError)) {
1116
- return false;
1117
- }
1118
- if (error.status !== 402) {
1119
- return false;
1120
- }
1121
- const message = this.extractErrorMessage(error.body);
1122
- if (!message) {
1123
- return true;
1124
- }
1125
- const normalised = message.toLowerCase();
1126
- return normalised.includes("history") || normalised.includes("chat history");
1036
+ throw new Error(
1037
+ `Inscription job ${jobId} did not complete within ${waitTimeoutMs}ms`
1038
+ );
1039
+ }
1040
+ async function getRegistryBrokerQuote(input, options = {}) {
1041
+ const logger = Logger.getInstance({
1042
+ module: "InscribeViaBroker",
1043
+ ...options.logging
1044
+ });
1045
+ const baseUrl = options.baseUrl ?? DEFAULT_REGISTRY_BROKER_URL;
1046
+ const headers = {
1047
+ "Content-Type": "application/json",
1048
+ Accept: "application/json"
1049
+ };
1050
+ if (options.ledgerApiKey) {
1051
+ headers["x-api-key"] = options.ledgerApiKey;
1052
+ } else if (options.apiKey) {
1053
+ headers["x-api-key"] = options.apiKey;
1054
+ } else {
1055
+ throw new Error(
1056
+ "Either ledgerApiKey or apiKey is required for Registry Broker quotes"
1057
+ );
1127
1058
  }
1128
- async executeHistoryAutoTopUp(reason) {
1129
- if (!this.historyAutoTopUp) {
1130
- return;
1059
+ let base64Content;
1060
+ let fileName;
1061
+ let mimeType;
1062
+ switch (input.type) {
1063
+ case "url":
1064
+ break;
1065
+ case "file": {
1066
+ const fileData = await convertFileToBase64(input.path);
1067
+ base64Content = fileData.base64;
1068
+ fileName = fileData.fileName;
1069
+ mimeType = fileData.mimeType;
1070
+ break;
1071
+ }
1072
+ case "buffer":
1073
+ base64Content = Buffer.from(
1074
+ input.buffer instanceof ArrayBuffer ? new Uint8Array(input.buffer) : input.buffer
1075
+ ).toString("base64");
1076
+ fileName = input.fileName;
1077
+ mimeType = input.mimeType;
1078
+ break;
1079
+ }
1080
+ const requestBody = {
1081
+ inputType: input.type === "url" ? "url" : "base64",
1082
+ mode: options.mode ?? "file"
1083
+ };
1084
+ if (input.type === "url") {
1085
+ requestBody.url = input.url;
1086
+ } else {
1087
+ requestBody.base64 = base64Content;
1088
+ requestBody.fileName = fileName;
1089
+ if (mimeType) {
1090
+ requestBody.mimeType = mimeType;
1091
+ }
1092
+ }
1093
+ if (options.metadata) {
1094
+ requestBody.metadata = options.metadata;
1095
+ }
1096
+ if (options.tags) {
1097
+ requestBody.tags = options.tags;
1098
+ }
1099
+ if (options.fileStandard) {
1100
+ requestBody.fileStandard = options.fileStandard;
1101
+ }
1102
+ if (options.chunkSize) {
1103
+ requestBody.chunkSize = options.chunkSize;
1104
+ }
1105
+ logger.debug("Getting inscription quote from Registry Broker");
1106
+ return fetchRegistryBroker(
1107
+ `${baseUrl}/inscribe/content/quote`,
1108
+ {
1109
+ method: "POST",
1110
+ headers,
1111
+ body: JSON.stringify(requestBody)
1131
1112
  }
1132
- const hbarAmount = this.historyAutoTopUp.hbarAmount && this.historyAutoTopUp.hbarAmount > 0 ? this.historyAutoTopUp.hbarAmount : DEFAULT_HISTORY_TOP_UP_HBAR;
1133
- await this.purchaseCreditsWithHbar({
1134
- accountId: this.historyAutoTopUp.accountId,
1135
- privateKey: this.historyAutoTopUp.privateKey,
1136
- hbarAmount,
1137
- memo: this.historyAutoTopUp.memo ?? "registry-broker-client:chat-history-topup",
1138
- metadata: {
1139
- purpose: "chat-history",
1140
- reason
1141
- }
1142
- });
1143
- }
1144
- initializeEncryptionBootstrap(options) {
1145
- return this.bootstrapEncryptionOptions(options).then(() => void 0);
1146
- }
1147
- bootstrapEncryptionOptions(options) {
1148
- return bootstrapEncryptionOptions(this, options);
1149
- }
1113
+ );
1150
1114
  }
1151
- const isPendingRegisterAgentResponse = (response) => response.status === "pending";
1152
- const isPartialRegisterAgentResponse = (response) => response.status === "partial" && response.success === false;
1153
- const isSuccessRegisterAgentResponse = (response) => response.success === true && response.status !== "pending";
1154
1115
  export {
1155
- RegistryBrokerClient,
1156
- isPartialRegisterAgentResponse,
1157
- isPendingRegisterAgentResponse,
1158
- isSuccessRegisterAgentResponse
1116
+ generateQuote,
1117
+ getRegistryBrokerQuote,
1118
+ inscribe,
1119
+ inscribeViaRegistryBroker,
1120
+ inscribeWithSigner,
1121
+ normalizeTransactionId,
1122
+ retrieveInscription,
1123
+ waitForInscriptionConfirmation
1159
1124
  };
1160
1125
  //# sourceMappingURL=standards-sdk.es145.js.map