@hashgraphonline/standards-sdk 0.1.141-canary.8 → 0.1.141-feat-hcs-21-flora-adapter.canary.cff94ea.45

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 (237) hide show
  1. package/README.md +13 -1
  2. package/dist/cjs/hcs-16/base-client.d.ts.map +1 -1
  3. package/dist/cjs/hcs-17/types.d.ts.map +1 -1
  4. package/dist/cjs/hcs-20/sdk.d.ts.map +1 -1
  5. package/dist/cjs/hcs-20/types.d.ts +9 -8
  6. package/dist/cjs/hcs-20/types.d.ts.map +1 -1
  7. package/dist/cjs/hcs-21/base-client.d.ts +4 -3
  8. package/dist/cjs/hcs-21/base-client.d.ts.map +1 -1
  9. package/dist/cjs/hcs-21/index.d.ts +1 -0
  10. package/dist/cjs/hcs-21/index.d.ts.map +1 -1
  11. package/dist/cjs/hcs-21/sdk.d.ts.map +1 -1
  12. package/dist/cjs/hcs-21/tx.d.ts.map +1 -1
  13. package/dist/cjs/hcs-21/types.d.ts +135 -64
  14. package/dist/cjs/hcs-21/types.d.ts.map +1 -1
  15. package/dist/cjs/hcs-21/verify.d.ts +6 -0
  16. package/dist/cjs/hcs-21/verify.d.ts.map +1 -0
  17. package/dist/cjs/inscribe/inscriber.d.ts +1 -0
  18. package/dist/cjs/inscribe/inscriber.d.ts.map +1 -1
  19. package/dist/cjs/inscribe/quote-cache.d.ts.map +1 -1
  20. package/dist/cjs/services/registry-broker/client.d.ts +4 -3
  21. package/dist/cjs/services/registry-broker/client.d.ts.map +1 -1
  22. package/dist/cjs/services/registry-broker/private-key-signer.d.ts.map +1 -1
  23. package/dist/cjs/services/registry-broker/schemas.d.ts +38 -38
  24. package/dist/cjs/services/registry-broker/schemas.d.ts.map +1 -1
  25. package/dist/cjs/standards-sdk.cjs +2 -2
  26. package/dist/cjs/standards-sdk.cjs.map +1 -1
  27. package/dist/cjs/utils/dynamic-import.d.ts +1 -0
  28. package/dist/cjs/utils/dynamic-import.d.ts.map +1 -1
  29. package/dist/es/hcs-16/base-client.d.ts.map +1 -1
  30. package/dist/es/hcs-17/types.d.ts.map +1 -1
  31. package/dist/es/hcs-20/sdk.d.ts.map +1 -1
  32. package/dist/es/hcs-20/types.d.ts +9 -8
  33. package/dist/es/hcs-20/types.d.ts.map +1 -1
  34. package/dist/es/hcs-21/base-client.d.ts +4 -3
  35. package/dist/es/hcs-21/base-client.d.ts.map +1 -1
  36. package/dist/es/hcs-21/index.d.ts +1 -0
  37. package/dist/es/hcs-21/index.d.ts.map +1 -1
  38. package/dist/es/hcs-21/sdk.d.ts.map +1 -1
  39. package/dist/es/hcs-21/tx.d.ts.map +1 -1
  40. package/dist/es/hcs-21/types.d.ts +135 -64
  41. package/dist/es/hcs-21/types.d.ts.map +1 -1
  42. package/dist/es/hcs-21/verify.d.ts +6 -0
  43. package/dist/es/hcs-21/verify.d.ts.map +1 -0
  44. package/dist/es/inscribe/inscriber.d.ts +1 -0
  45. package/dist/es/inscribe/inscriber.d.ts.map +1 -1
  46. package/dist/es/inscribe/quote-cache.d.ts.map +1 -1
  47. package/dist/es/services/registry-broker/client.d.ts +4 -3
  48. package/dist/es/services/registry-broker/client.d.ts.map +1 -1
  49. package/dist/es/services/registry-broker/private-key-signer.d.ts.map +1 -1
  50. package/dist/es/services/registry-broker/schemas.d.ts +38 -38
  51. package/dist/es/services/registry-broker/schemas.d.ts.map +1 -1
  52. package/dist/es/standards-sdk.es.js +58 -50
  53. package/dist/es/standards-sdk.es.js.map +1 -1
  54. package/dist/es/standards-sdk.es10.js +2 -2
  55. package/dist/es/standards-sdk.es100.js +26 -229
  56. package/dist/es/standards-sdk.es100.js.map +1 -1
  57. package/dist/es/standards-sdk.es101.js +228 -109
  58. package/dist/es/standards-sdk.es101.js.map +1 -1
  59. package/dist/es/standards-sdk.es102.js +94 -15
  60. package/dist/es/standards-sdk.es102.js.map +1 -1
  61. package/dist/es/standards-sdk.es103.js +30 -80
  62. package/dist/es/standards-sdk.es103.js.map +1 -1
  63. package/dist/es/standards-sdk.es104.js +80 -27
  64. package/dist/es/standards-sdk.es104.js.map +1 -1
  65. package/dist/es/standards-sdk.es105.js +25 -136
  66. package/dist/es/standards-sdk.es105.js.map +1 -1
  67. package/dist/es/standards-sdk.es106.js +140 -27
  68. package/dist/es/standards-sdk.es106.js.map +1 -1
  69. package/dist/es/standards-sdk.es107.js +27 -20
  70. package/dist/es/standards-sdk.es107.js.map +1 -1
  71. package/dist/es/standards-sdk.es108.js +18 -156
  72. package/dist/es/standards-sdk.es108.js.map +1 -1
  73. package/dist/es/standards-sdk.es109.js +148 -196
  74. package/dist/es/standards-sdk.es109.js.map +1 -1
  75. package/dist/es/standards-sdk.es110.js +160 -747
  76. package/dist/es/standards-sdk.es110.js.map +1 -1
  77. package/dist/es/standards-sdk.es111.js +786 -9
  78. package/dist/es/standards-sdk.es111.js.map +1 -1
  79. package/dist/es/standards-sdk.es112.js +13 -567
  80. package/dist/es/standards-sdk.es112.js.map +1 -1
  81. package/dist/es/standards-sdk.es113.js +541 -576
  82. package/dist/es/standards-sdk.es113.js.map +1 -1
  83. package/dist/es/standards-sdk.es114.js +601 -12
  84. package/dist/es/standards-sdk.es114.js.map +1 -1
  85. package/dist/es/standards-sdk.es115.js +13 -2
  86. package/dist/es/standards-sdk.es115.js.map +1 -1
  87. package/dist/es/standards-sdk.es116.js +2 -83
  88. package/dist/es/standards-sdk.es116.js.map +1 -1
  89. package/dist/es/standards-sdk.es117.js +80 -36
  90. package/dist/es/standards-sdk.es117.js.map +1 -1
  91. package/dist/es/standards-sdk.es118.js +39 -2
  92. package/dist/es/standards-sdk.es118.js.map +1 -1
  93. package/dist/es/standards-sdk.es119.js +2 -223
  94. package/dist/es/standards-sdk.es119.js.map +1 -1
  95. package/dist/es/standards-sdk.es120.js +193 -1110
  96. package/dist/es/standards-sdk.es120.js.map +1 -1
  97. package/dist/es/standards-sdk.es121.js +1059 -225
  98. package/dist/es/standards-sdk.es121.js.map +1 -1
  99. package/dist/es/standards-sdk.es122.js +303 -419
  100. package/dist/es/standards-sdk.es122.js.map +1 -1
  101. package/dist/es/standards-sdk.es123.js +418 -351
  102. package/dist/es/standards-sdk.es123.js.map +1 -1
  103. package/dist/es/standards-sdk.es124.js +348 -785
  104. package/dist/es/standards-sdk.es124.js.map +1 -1
  105. package/dist/es/standards-sdk.es125.js +767 -183
  106. package/dist/es/standards-sdk.es125.js.map +1 -1
  107. package/dist/es/standards-sdk.es126.js +153 -1512
  108. package/dist/es/standards-sdk.es126.js.map +1 -1
  109. package/dist/es/standards-sdk.es127.js +1373 -1987
  110. package/dist/es/standards-sdk.es127.js.map +1 -1
  111. package/dist/es/standards-sdk.es128.js +2208 -67
  112. package/dist/es/standards-sdk.es128.js.map +1 -1
  113. package/dist/es/standards-sdk.es129.js +59 -79
  114. package/dist/es/standards-sdk.es129.js.map +1 -1
  115. package/dist/es/standards-sdk.es130.js +80 -152
  116. package/dist/es/standards-sdk.es130.js.map +1 -1
  117. package/dist/es/standards-sdk.es131.js +159 -7
  118. package/dist/es/standards-sdk.es131.js.map +1 -1
  119. package/dist/es/standards-sdk.es132.js +7 -86
  120. package/dist/es/standards-sdk.es132.js.map +1 -1
  121. package/dist/es/standards-sdk.es133.js +65 -44
  122. package/dist/es/standards-sdk.es133.js.map +1 -1
  123. package/dist/es/standards-sdk.es134.js +65 -28
  124. package/dist/es/standards-sdk.es134.js.map +1 -1
  125. package/dist/es/standards-sdk.es135.js +82 -760
  126. package/dist/es/standards-sdk.es135.js.map +1 -1
  127. package/dist/es/standards-sdk.es136.js +28 -12274
  128. package/dist/es/standards-sdk.es136.js.map +1 -1
  129. package/dist/es/standards-sdk.es137.js +1 -1
  130. package/dist/es/standards-sdk.es14.js +1 -1
  131. package/dist/es/standards-sdk.es140.js +766 -64
  132. package/dist/es/standards-sdk.es140.js.map +1 -1
  133. package/dist/es/standards-sdk.es141.js +12235 -133
  134. package/dist/es/standards-sdk.es141.js.map +1 -1
  135. package/dist/es/standards-sdk.es142.js +13 -318
  136. package/dist/es/standards-sdk.es142.js.map +1 -1
  137. package/dist/es/standards-sdk.es143.js +120 -294
  138. package/dist/es/standards-sdk.es143.js.map +1 -1
  139. package/dist/es/standards-sdk.es144.js +191 -322
  140. package/dist/es/standards-sdk.es144.js.map +1 -1
  141. package/dist/es/standards-sdk.es145.js +294 -279
  142. package/dist/es/standards-sdk.es145.js.map +1 -1
  143. package/dist/es/standards-sdk.es146.js +440 -63
  144. package/dist/es/standards-sdk.es146.js.map +1 -1
  145. package/dist/es/standards-sdk.es147.js +327 -13
  146. package/dist/es/standards-sdk.es147.js.map +1 -1
  147. package/dist/es/standards-sdk.es148.js +79 -0
  148. package/dist/es/standards-sdk.es148.js.map +1 -0
  149. package/dist/es/standards-sdk.es15.js +1 -1
  150. package/dist/es/standards-sdk.es16.js +1 -1
  151. package/dist/es/standards-sdk.es17.js +5 -11
  152. package/dist/es/standards-sdk.es17.js.map +1 -1
  153. package/dist/es/standards-sdk.es19.js +10 -15
  154. package/dist/es/standards-sdk.es19.js.map +1 -1
  155. package/dist/es/standards-sdk.es2.js +26 -72
  156. package/dist/es/standards-sdk.es2.js.map +1 -1
  157. package/dist/es/standards-sdk.es20.js +9 -14
  158. package/dist/es/standards-sdk.es20.js.map +1 -1
  159. package/dist/es/standards-sdk.es21.js +1 -1
  160. package/dist/es/standards-sdk.es22.js +1 -1
  161. package/dist/es/standards-sdk.es24.js +1 -1
  162. package/dist/es/standards-sdk.es25.js +1 -1
  163. package/dist/es/standards-sdk.es26.js +1 -1
  164. package/dist/es/standards-sdk.es27.js +1 -1
  165. package/dist/es/standards-sdk.es28.js +11 -16
  166. package/dist/es/standards-sdk.es28.js.map +1 -1
  167. package/dist/es/standards-sdk.es3.js +2 -2
  168. package/dist/es/standards-sdk.es31.js +2 -2
  169. package/dist/es/standards-sdk.es32.js +4 -4
  170. package/dist/es/standards-sdk.es33.js +1 -1
  171. package/dist/es/standards-sdk.es36.js +6 -12
  172. package/dist/es/standards-sdk.es36.js.map +1 -1
  173. package/dist/es/standards-sdk.es37.js +2 -2
  174. package/dist/es/standards-sdk.es38.js +2 -2
  175. package/dist/es/standards-sdk.es39.js +2 -2
  176. package/dist/es/standards-sdk.es40.js +1 -1
  177. package/dist/es/standards-sdk.es41.js +1 -1
  178. package/dist/es/standards-sdk.es42.js +2 -2
  179. package/dist/es/standards-sdk.es47.js +1 -1
  180. package/dist/es/standards-sdk.es5.js +1 -1
  181. package/dist/es/standards-sdk.es52.js +1 -1
  182. package/dist/es/standards-sdk.es57.js +1 -1
  183. package/dist/es/standards-sdk.es6.js +2 -2
  184. package/dist/es/standards-sdk.es60.js +1 -1
  185. package/dist/es/standards-sdk.es61.js +6 -11
  186. package/dist/es/standards-sdk.es61.js.map +1 -1
  187. package/dist/es/standards-sdk.es63.js +1 -1
  188. package/dist/es/standards-sdk.es65.js +2 -2
  189. package/dist/es/standards-sdk.es66.js +2 -2
  190. package/dist/es/standards-sdk.es7.js +2 -2
  191. package/dist/es/standards-sdk.es70.js +2 -2
  192. package/dist/es/standards-sdk.es71.js +2 -2
  193. package/dist/es/standards-sdk.es73.js.map +1 -1
  194. package/dist/es/standards-sdk.es75.js +2 -2
  195. package/dist/es/standards-sdk.es77.js +4 -2
  196. package/dist/es/standards-sdk.es77.js.map +1 -1
  197. package/dist/es/standards-sdk.es78.js +4 -10
  198. package/dist/es/standards-sdk.es78.js.map +1 -1
  199. package/dist/es/standards-sdk.es80.js +26 -15
  200. package/dist/es/standards-sdk.es80.js.map +1 -1
  201. package/dist/es/standards-sdk.es82.js +11 -3
  202. package/dist/es/standards-sdk.es82.js.map +1 -1
  203. package/dist/es/standards-sdk.es83.js +7 -6
  204. package/dist/es/standards-sdk.es83.js.map +1 -1
  205. package/dist/es/standards-sdk.es84.js +6 -4
  206. package/dist/es/standards-sdk.es84.js.map +1 -1
  207. package/dist/es/standards-sdk.es86.js +55 -21
  208. package/dist/es/standards-sdk.es86.js.map +1 -1
  209. package/dist/es/standards-sdk.es87.js +22 -75
  210. package/dist/es/standards-sdk.es87.js.map +1 -1
  211. package/dist/es/standards-sdk.es88.js +45 -30
  212. package/dist/es/standards-sdk.es88.js.map +1 -1
  213. package/dist/es/standards-sdk.es89.js +57 -22
  214. package/dist/es/standards-sdk.es89.js.map +1 -1
  215. package/dist/es/standards-sdk.es90.js +28 -23
  216. package/dist/es/standards-sdk.es90.js.map +1 -1
  217. package/dist/es/standards-sdk.es91.js +23 -167
  218. package/dist/es/standards-sdk.es91.js.map +1 -1
  219. package/dist/es/standards-sdk.es92.js +158 -119
  220. package/dist/es/standards-sdk.es92.js.map +1 -1
  221. package/dist/es/standards-sdk.es93.js +68 -95
  222. package/dist/es/standards-sdk.es93.js.map +1 -1
  223. package/dist/es/standards-sdk.es94.js +136 -119
  224. package/dist/es/standards-sdk.es94.js.map +1 -1
  225. package/dist/es/standards-sdk.es95.js +139 -39
  226. package/dist/es/standards-sdk.es95.js.map +1 -1
  227. package/dist/es/standards-sdk.es96.js +42 -257
  228. package/dist/es/standards-sdk.es96.js.map +1 -1
  229. package/dist/es/standards-sdk.es97.js +243 -80
  230. package/dist/es/standards-sdk.es97.js.map +1 -1
  231. package/dist/es/standards-sdk.es98.js +47 -48
  232. package/dist/es/standards-sdk.es98.js.map +1 -1
  233. package/dist/es/standards-sdk.es99.js +100 -28
  234. package/dist/es/standards-sdk.es99.js.map +1 -1
  235. package/dist/es/utils/dynamic-import.d.ts +1 -0
  236. package/dist/es/utils/dynamic-import.d.ts.map +1 -1
  237. package/package.json +63 -65
@@ -1,2184 +1,1570 @@
1
- import * as path from "node:path";
2
- import { Buffer } from "node:buffer";
3
- import { randomBytes, createHash, createCipheriv, createDecipheriv } from "node:crypto";
4
- import { createRequire } from "node:module";
5
- import { secp256k1 } from "@noble/curves/secp256k1.js";
6
- import { canonicalizeLedgerNetwork } from "./standards-sdk.es129.js";
1
+ import { PublicKey, Timestamp, AccountId } from "@hashgraph/sdk";
7
2
  import axios from "axios";
8
- import { privateKeyToAccount } from "viem/accounts";
9
- import "viem/chains";
10
- import { withPaymentInterceptor, decodeXPaymentResponse } from "x402-axios";
11
- import { createSigner } from "x402/types";
12
- import { searchResponseSchema, statsResponseSchema, registriesResponseSchema, additionalRegistryCatalogResponseSchema, popularResponseSchema, resolveResponseSchema, registerAgentResponseSchema, registrationQuoteResponseSchema, registrationProgressResponseSchema, creditPurchaseResponseSchema, x402MinimumsResponseSchema, x402CreditPurchaseResponseSchema, ledgerChallengeResponseSchema, ledgerVerifyResponseSchema, protocolsResponseSchema, detectProtocolResponseSchema, registrySearchByNamespaceSchema, vectorSearchResponseSchema, searchStatusResponseSchema, adapterDetailsResponseSchema, websocketStatsResponseSchema, metricsSummaryResponseSchema, uaidValidationResponseSchema, uaidConnectionStatusSchema, dashboardStatsResponseSchema, adaptersResponseSchema, searchFacetsResponseSchema, createSessionResponseSchema, chatHistorySnapshotResponseSchema, chatHistoryCompactionResponseSchema, sessionEncryptionStatusResponseSchema, encryptionHandshakeResponseSchema, registerEncryptionKeyResponseSchema, sendMessageResponseSchema } from "./standards-sdk.es135.js";
13
- import { ZodError } from "zod";
14
- import { createPrivateKeySigner } from "./standards-sdk.es128.js";
15
- const createNodeRequire = () => {
16
- const metaUrl = typeof import.meta !== "undefined" && typeof import.meta.url === "string" ? import.meta.url : void 0;
17
- try {
18
- return createRequire(metaUrl ?? `${process.cwd()}/.hol-rb-client.cjs`);
19
- } catch {
20
- return null;
21
- }
22
- };
23
- const getFs = () => {
24
- const loader = createNodeRequire();
25
- if (!loader) {
26
- return null;
27
- }
28
- try {
29
- const fsModule = loader("node:fs");
30
- if (fsModule && typeof fsModule.existsSync === "function" && typeof fsModule.readFileSync === "function" && typeof fsModule.writeFileSync === "function" && typeof fsModule.appendFileSync === "function") {
31
- return fsModule;
32
- }
33
- } catch {
34
- }
35
- return null;
36
- };
37
- const DEFAULT_USER_AGENT = "@hol-org/rb-client";
38
- const DEFAULT_PROGRESS_INTERVAL_MS = 1500;
39
- const DEFAULT_PROGRESS_TIMEOUT_MS = 5 * 60 * 1e3;
40
- const createAbortError = () => typeof DOMException === "function" ? new DOMException("Aborted", "AbortError") : new Error("The operation was aborted");
41
- const normaliseHeaderName = (name) => name.trim().toLowerCase();
42
- const isBrowserRuntime = () => typeof window !== "undefined" && typeof window.fetch === "function";
43
- const DEFAULT_BASE_URL = "https://hol.org/registry/api/v1";
44
- const JSON_CONTENT_TYPE = /application\/json/i;
45
- const DEFAULT_HISTORY_TOP_UP_HBAR = 0.25;
46
- const MINIMUM_REGISTRATION_AUTO_TOP_UP_CREDITS = 1;
47
- const toJsonValue = (value) => {
48
- if (value === null) {
49
- return null;
50
- }
51
- if (value instanceof Date) {
52
- return value.toISOString();
53
- }
54
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
55
- return value;
56
- }
57
- if (Array.isArray(value)) {
58
- return value.map((item) => item === void 0 ? null : toJsonValue(item));
59
- }
60
- if (typeof value === "object") {
61
- const result = {};
62
- Object.entries(value).forEach(
63
- ([key, entryValue]) => {
64
- if (entryValue !== void 0) {
65
- result[key] = toJsonValue(entryValue);
66
- }
67
- }
3
+ import { Logger } from "./standards-sdk.es106.js";
4
+ import { proto } from "@hashgraph/proto";
5
+ class HederaMirrorNode {
6
+ constructor(network, logger, config) {
7
+ this.maxRetries = 5;
8
+ this.initialDelayMs = 2e3;
9
+ this.maxDelayMs = 3e4;
10
+ this.backoffFactor = 2;
11
+ this.network = network;
12
+ this.apiKey = config?.apiKey;
13
+ this.customHeaders = config?.headers || {};
14
+ this.baseUrl = config?.customUrl || this.getMirrorNodeUrl();
15
+ this.logger = logger || new Logger({
16
+ level: "debug",
17
+ module: "MirrorNode"
18
+ });
19
+ this.isServerEnvironment = typeof window === "undefined";
20
+ if (config?.customUrl) {
21
+ this.logger.info(`Using custom mirror node URL: ${config.customUrl}`);
22
+ }
23
+ if (config?.apiKey) {
24
+ this.logger.info("Using API key for mirror node requests");
25
+ }
26
+ }
27
+ /**
28
+ * Configures the retry mechanism for API requests.
29
+ * @param config The retry configuration.
30
+ */
31
+ configureRetry(config) {
32
+ this.maxRetries = config.maxRetries ?? this.maxRetries;
33
+ this.initialDelayMs = config.initialDelayMs ?? this.initialDelayMs;
34
+ this.maxDelayMs = config.maxDelayMs ?? this.maxDelayMs;
35
+ this.backoffFactor = config.backoffFactor ?? this.backoffFactor;
36
+ this.logger.info(
37
+ `Retry configuration updated: maxRetries=${this.maxRetries}, initialDelayMs=${this.initialDelayMs}, maxDelayMs=${this.maxDelayMs}, backoffFactor=${this.backoffFactor}`
68
38
  );
69
- return result;
70
- }
71
- throw new TypeError("Only JSON-compatible values are supported");
72
- };
73
- const isJsonObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
74
- const toJsonObject = (value) => {
75
- const normalised = toJsonValue(value);
76
- if (isJsonObject(normalised)) {
77
- return normalised;
78
- }
79
- throw new TypeError("Expected JSON object value");
80
- };
81
- const serialiseAuthConfig = (auth) => {
82
- const authPayload = {};
83
- if (auth.type) {
84
- authPayload.type = auth.type;
85
- }
86
- if (auth.token) {
87
- authPayload.token = auth.token;
88
- }
89
- if (auth.username) {
90
- authPayload.username = auth.username;
91
- }
92
- if (auth.password) {
93
- authPayload.password = auth.password;
94
- }
95
- if (auth.headerName) {
96
- authPayload.headerName = auth.headerName;
97
- }
98
- if (auth.headerValue) {
99
- authPayload.headerValue = auth.headerValue;
100
- }
101
- if (auth.headers) {
102
- authPayload.headers = { ...auth.headers };
103
39
  }
104
- return authPayload;
105
- };
106
- const serialiseAgentRegistrationRequest = (payload) => {
107
- const body = {
108
- profile: toJsonObject(payload.profile)
109
- };
110
- if (payload.endpoint !== void 0) {
111
- body.endpoint = payload.endpoint;
112
- }
113
- if (payload.protocol !== void 0) {
114
- body.protocol = payload.protocol;
115
- }
116
- if (payload.communicationProtocol !== void 0) {
117
- body.communicationProtocol = payload.communicationProtocol;
118
- }
119
- if (payload.registry !== void 0) {
120
- body.registry = payload.registry;
121
- }
122
- if (payload.additionalRegistries !== void 0) {
123
- body.additionalRegistries = payload.additionalRegistries;
124
- }
125
- if (payload.metadata !== void 0) {
126
- body.metadata = toJsonObject(payload.metadata);
127
- }
128
- return body;
129
- };
130
- const normalizeHexPrivateKey = (value) => {
131
- const trimmed = value.trim();
132
- if (!trimmed) {
133
- throw new Error("evmPrivateKey is required");
134
- }
135
- return trimmed.startsWith("0x") ? trimmed : `0x${trimmed}`;
136
- };
137
- class RegistryBrokerError extends Error {
138
- constructor(message, details) {
139
- super(message);
140
- this.status = details.status;
141
- this.statusText = details.statusText;
142
- this.body = details.body;
143
- }
144
- }
145
- class RegistryBrokerParseError extends Error {
146
- constructor(message, cause, rawValue) {
147
- super(message);
148
- this.cause = cause;
149
- this.rawValue = rawValue;
150
- }
151
- }
152
- function normaliseBaseUrl(input) {
153
- const trimmed = input?.trim();
154
- let baseCandidate = trimmed && trimmed.length > 0 ? trimmed : DEFAULT_BASE_URL;
155
- try {
156
- const url = new URL(baseCandidate.replace(/\/+$/, ""));
157
- const hostname = url.hostname.toLowerCase();
158
- const ensureRegistryPrefix = () => {
159
- if (!url.pathname.startsWith("/registry")) {
160
- url.pathname = url.pathname === "/" ? "/registry" : `/registry${url.pathname}`;
40
+ /**
41
+ * Updates the mirror node configuration.
42
+ * @param config The new mirror node configuration.
43
+ */
44
+ configureMirrorNode(config) {
45
+ if (config.customUrl) {
46
+ this.baseUrl = config.customUrl;
47
+ this.logger.info(`Updated mirror node URL: ${config.customUrl}`);
48
+ }
49
+ if (config.apiKey) {
50
+ this.apiKey = config.apiKey;
51
+ this.logger.info("Updated API key for mirror node requests");
52
+ }
53
+ if (config.headers) {
54
+ this.customHeaders = { ...this.customHeaders, ...config.headers };
55
+ this.logger.info("Updated custom headers for mirror node requests");
56
+ }
57
+ }
58
+ /**
59
+ * Constructs a full URL for API requests, handling custom providers with API keys in the path.
60
+ * @param endpoint The API endpoint (e.g., '/api/v1/accounts/0.0.123')
61
+ * @returns The full URL for the request
62
+ */
63
+ constructUrl(endpoint) {
64
+ if (this.baseUrl.includes("<API-KEY>") && this.apiKey) {
65
+ const baseUrlWithKey = this.baseUrl.replace("<API-KEY>", this.apiKey);
66
+ return endpoint.startsWith("/") ? `${baseUrlWithKey}${endpoint}` : `${baseUrlWithKey}/${endpoint}`;
67
+ }
68
+ return endpoint.startsWith("/") ? `${this.baseUrl}${endpoint}` : `${this.baseUrl}/${endpoint}`;
69
+ }
70
+ /**
71
+ * Returns the base URL for the Hedera mirror node based on the network type
72
+ * @returns The mirror node base URL
73
+ * @private
74
+ */
75
+ getMirrorNodeUrl() {
76
+ return this.network === "mainnet" ? "https://mainnet-public.mirrornode.hedera.com" : "https://testnet.mirrornode.hedera.com";
77
+ }
78
+ getBaseUrl() {
79
+ return this.baseUrl;
80
+ }
81
+ /**
82
+ * Retrieves the public key for a given account ID from the mirror node.
83
+ * @param accountId The ID of the account to retrieve the public key for.
84
+ * @returns A promise that resolves to the public key for the given account.
85
+ * @throws An error if the account ID is invalid or the public key cannot be retrieved.
86
+ */
87
+ async getPublicKey(accountId) {
88
+ this.logger.debug(`Getting public key for account ${accountId}`);
89
+ const accountInfo = await this.requestAccount(accountId);
90
+ try {
91
+ if (!accountInfo || !accountInfo.key) {
92
+ throw new Error(
93
+ `Failed to retrieve public key for account ID: ${accountId}`
94
+ );
161
95
  }
162
- };
163
- if (hostname === "hol.org") {
164
- ensureRegistryPrefix();
165
- baseCandidate = url.toString();
166
- } else if (hostname === "registry.hashgraphonline.com" || hostname === "hashgraphonline.com") {
167
- ensureRegistryPrefix();
168
- url.hostname = "hol.org";
169
- baseCandidate = url.toString();
170
- }
171
- } catch {
172
- }
173
- const withoutTrailing = baseCandidate.replace(/\/+$/, "");
174
- if (/\/api\/v\d+$/i.test(withoutTrailing)) {
175
- return withoutTrailing;
176
- }
177
- if (/\/api$/i.test(withoutTrailing)) {
178
- return `${withoutTrailing}/v1`;
179
- }
180
- return `${withoutTrailing}/api/v1`;
181
- }
182
- function buildSearchQuery(params) {
183
- const query = new URLSearchParams();
184
- const appendList = (key, values) => {
185
- if (!values) {
186
- return;
187
- }
188
- values.forEach((value) => {
189
- if (typeof value === "string") {
190
- const trimmed = value.trim();
191
- if (trimmed.length > 0) {
192
- query.append(key, trimmed);
193
- }
96
+ return PublicKey.fromString(accountInfo.key.key);
97
+ } catch (e) {
98
+ const error = e;
99
+ const logMessage = `Error fetching public key from Mirror Node: ${error.message}`;
100
+ this.logger.error(logMessage);
101
+ throw new Error(logMessage);
102
+ }
103
+ }
104
+ /**
105
+ * Retrieves the memo for a given account ID from the mirror node.
106
+ * @param accountId The ID of the account to retrieve the memo for.
107
+ * @returns A promise that resolves to the memo for the given account.
108
+ * @throws An error if the account ID is invalid or the memo cannot be retrieved.
109
+ */
110
+ async getAccountMemo(accountId) {
111
+ this.logger.debug(`Getting account memo for account ID: ${accountId}`);
112
+ try {
113
+ const accountInfo = await this._requestWithRetry(
114
+ `/api/v1/accounts/${accountId}`
115
+ );
116
+ if (accountInfo?.memo) {
117
+ return accountInfo.memo;
194
118
  }
195
- });
196
- };
197
- if (params.q) {
198
- const trimmed = params.q.trim();
199
- if (trimmed.length > 0) {
200
- query.set("q", trimmed);
201
- }
202
- }
203
- if (typeof params.page === "number") {
204
- query.set("page", params.page.toString());
205
- }
206
- if (typeof params.limit === "number") {
207
- query.set("limit", params.limit.toString());
208
- }
209
- if (params.registry) {
210
- const trimmed = params.registry.trim();
211
- if (trimmed.length > 0) {
212
- query.set("registry", trimmed);
119
+ this.logger.warn(`No memo found for account ${accountId}`);
120
+ return null;
121
+ } catch (e) {
122
+ const error = e;
123
+ this.logger.error(
124
+ `Failed to get account memo for ${accountId} after retries: ${error.message}`
125
+ );
126
+ return null;
213
127
  }
214
128
  }
215
- appendList("registries", params.registries);
216
- if (typeof params.minTrust === "number") {
217
- query.set("minTrust", params.minTrust.toString());
218
- }
219
- appendList("capabilities", params.capabilities);
220
- appendList("protocols", params.protocols);
221
- appendList("adapters", params.adapters);
222
- if (params.metadata) {
223
- Object.entries(params.metadata).forEach(([key, values]) => {
224
- if (!key || !Array.isArray(values) || values.length === 0) {
225
- return;
226
- }
227
- const trimmedKey = key.trim();
228
- if (trimmedKey.length === 0) {
229
- return;
230
- }
231
- values.forEach((value) => {
232
- if (value === void 0 || value === null) {
233
- return;
234
- }
235
- query.append(`metadata.${trimmedKey}`, String(value));
236
- });
237
- });
238
- }
239
- if (params.type) {
240
- const trimmedType = params.type.trim();
241
- if (trimmedType.length > 0 && trimmedType.toLowerCase() !== "all") {
242
- query.set("type", trimmedType);
129
+ /**
130
+ * Retrieves topic information for a given topic ID from the mirror node.
131
+ * @param topicId The ID of the topic to retrieve information for.
132
+ * @returns A promise that resolves to the topic information.
133
+ * @throws An error if the topic ID is invalid or the information cannot be retrieved.
134
+ */
135
+ async getTopicInfo(topicId) {
136
+ try {
137
+ this.logger.debug(`Fetching topic info for ${topicId}`);
138
+ const data = await this._requestWithRetry(
139
+ `/api/v1/topics/${topicId}`
140
+ );
141
+ return data;
142
+ } catch (e) {
143
+ const error = e;
144
+ const logMessage = `Error retrieving topic information for ${topicId} after retries: ${error.message}`;
145
+ this.logger.error(logMessage);
146
+ throw new Error(logMessage);
147
+ }
148
+ }
149
+ /**
150
+ * Retrieves custom fees for a given topic ID from the mirror node.
151
+ * @param topicId The ID of the topic to retrieve custom fees for.
152
+ * @returns A promise that resolves to the custom fees for the given topic.
153
+ * @throws An error if the topic ID is invalid or the custom fees cannot be retrieved.
154
+ */
155
+ async getTopicFees(topicId) {
156
+ try {
157
+ const topicInfo = await this.getTopicInfo(topicId);
158
+ return topicInfo.custom_fees;
159
+ } catch (e) {
160
+ const error = e;
161
+ const logMessage = `Error retrieving topic fees: ${error.message}`;
162
+ this.logger.error(logMessage);
163
+ return null;
243
164
  }
244
165
  }
245
- if (params.verified === true) {
246
- query.set("verified", "true");
247
- }
248
- if (params.online === true) {
249
- query.set("online", "true");
250
- }
251
- if (params.sortBy) {
252
- const trimmedSort = params.sortBy.trim();
253
- if (trimmedSort.length > 0) {
254
- query.set("sortBy", trimmedSort);
166
+ /**
167
+ * Retrieves the current HBAR price from the mirror node.
168
+ * @param date The date to retrieve the HBAR price for.
169
+ * @returns A promise that resolves to the HBAR price for the given date.
170
+ * @throws An error if the date is invalid or the price cannot be retrieved.
171
+ */
172
+ async getHBARPrice(date) {
173
+ try {
174
+ const timestamp = Timestamp.fromDate(date).toString();
175
+ this.logger.debug(`Fetching HBAR price for timestamp ${timestamp}`);
176
+ const response = await this._requestWithRetry(
177
+ `/api/v1/network/exchangerate?timestamp=${timestamp}`
178
+ );
179
+ const usdPrice = Number(response?.current_rate?.cent_equivalent) / Number(response?.current_rate?.hbar_equivalent) / 100;
180
+ return usdPrice;
181
+ } catch (e) {
182
+ const error = e;
183
+ const logMessage = `Error retrieving HBAR price: ${error.message}`;
184
+ this.logger.error(logMessage);
185
+ return null;
255
186
  }
256
187
  }
257
- if (params.sortOrder) {
258
- const lowered = params.sortOrder.toLowerCase();
259
- if (lowered === "asc" || lowered === "desc") {
260
- query.set("sortOrder", lowered);
188
+ /**
189
+ * Retrieves token information for a given token ID from the mirror node.
190
+ * @param tokenId The ID of the token to retrieve information for.
191
+ * @returns A promise that resolves to the token information.
192
+ * @throws An error if the token ID is invalid or the information cannot be retrieved.
193
+ */
194
+ async getTokenInfo(tokenId) {
195
+ this.logger.debug(`Fetching token info for ${tokenId}`);
196
+ try {
197
+ const data = await this._requestWithRetry(
198
+ `/api/v1/tokens/${tokenId}`
199
+ );
200
+ if (data) {
201
+ this.logger.trace(`Token info found for ${tokenId}:`, data);
202
+ return data;
203
+ }
204
+ this.logger.warn(`No token info found for ${tokenId}`);
205
+ return null;
206
+ } catch (e) {
207
+ const error = e;
208
+ const logMessage = `Error fetching token info for ${tokenId}: ${error.message}`;
209
+ this.logger.error(logMessage);
210
+ return null;
261
211
  }
262
212
  }
263
- const queryString = query.toString();
264
- return queryString.length > 0 ? `?${queryString}` : "";
265
- }
266
- class RegistryBrokerClient {
267
- constructor(options = {}) {
268
- this.conversationContexts = /* @__PURE__ */ new Map();
269
- this.request = async (path2, config) => {
270
- const headers = new Headers();
271
- Object.entries(this.defaultHeaders).forEach(([key, value]) => {
272
- headers.set(key, value);
273
- });
274
- if (config.headers) {
275
- Object.entries(config.headers).forEach(([key, value]) => {
276
- headers.set(key, value);
277
- });
278
- }
279
- if (!headers.has("accept")) {
280
- headers.set("accept", "application/json");
281
- }
282
- if (!headers.has("user-agent") && !isBrowserRuntime()) {
283
- headers.set("user-agent", DEFAULT_USER_AGENT);
284
- }
285
- const init = {
286
- method: config.method ?? "GET",
287
- headers
288
- };
289
- if (config.body !== void 0) {
290
- init.body = JSON.stringify(config.body);
291
- if (!headers.has("content-type")) {
292
- headers.set("content-type", "application/json");
213
+ /**
214
+ * Retrieves messages for a given topic ID from the mirror node. Supports filtering by sequence number
215
+ * based on the OpenAPI specification.
216
+ * @param topicId The ID of the topic to retrieve messages for.
217
+ * @param options Optional filtering parameters.
218
+ * @returns A promise that resolves to the messages for the given topic.
219
+ */
220
+ async getTopicMessages(topicId, options) {
221
+ this.logger.trace(
222
+ `Querying messages for topic ${topicId}${options ? " with filters" : ""}`
223
+ );
224
+ let endpoint = `/api/v1/topics/${topicId}/messages`;
225
+ const params = new URLSearchParams();
226
+ if (options) {
227
+ if (options.sequenceNumber !== void 0) {
228
+ const seqNum = typeof options.sequenceNumber === "number" ? options.sequenceNumber.toString() : options.sequenceNumber;
229
+ if (!seqNum.match(/^(gt|gte|lt|lte|eq|ne):/)) {
230
+ params.append("sequencenumber", `gt:${seqNum}`);
231
+ } else {
232
+ params.append("sequencenumber", seqNum);
293
233
  }
294
234
  }
295
- const response = await this.fetchImpl(this.buildUrl(path2), init);
296
- if (response.ok) {
297
- return response;
235
+ if (options.limit) {
236
+ params.append("limit", options.limit.toString());
237
+ }
238
+ if (options.order) {
239
+ params.append("order", options.order);
298
240
  }
299
- const errorBody = await this.extractErrorBody(response);
300
- throw new RegistryBrokerError("Registry broker request failed", {
301
- status: response.status,
302
- statusText: response.statusText,
303
- body: errorBody
304
- });
305
- };
306
- this.baseUrl = normaliseBaseUrl(options.baseUrl);
307
- const fetchCandidate = options.fetchImplementation ?? globalThis.fetch;
308
- if (!fetchCandidate) {
309
- throw new Error(
310
- "A fetch implementation is required for RegistryBrokerClient"
311
- );
312
- }
313
- this.fetchImpl = fetchCandidate;
314
- this.defaultHeaders = {};
315
- if (options.defaultHeaders) {
316
- Object.entries(options.defaultHeaders).forEach(([name, value]) => {
317
- if (typeof value === "string") {
318
- this.setDefaultHeader(name, value);
319
- }
320
- });
321
241
  }
322
- if (options.apiKey && options.apiKey.trim().length > 0) {
323
- this.setApiKey(options.apiKey);
242
+ const queryString = params.toString();
243
+ if (queryString) {
244
+ endpoint += `?${queryString}`;
324
245
  }
325
- if (options.ledgerApiKey && options.ledgerApiKey.trim().length > 0) {
326
- this.setLedgerApiKey(options.ledgerApiKey);
246
+ const messages = [];
247
+ let nextEndpoint = endpoint;
248
+ while (nextEndpoint) {
249
+ try {
250
+ const data = await this._requestWithRetry(nextEndpoint);
251
+ if (data.messages && data.messages.length > 0) {
252
+ for (const message of data.messages) {
253
+ try {
254
+ if (!message.message) {
255
+ continue;
256
+ }
257
+ let messageContent;
258
+ try {
259
+ if (this.isServerEnvironment) {
260
+ messageContent = Buffer.from(
261
+ message.message,
262
+ "base64"
263
+ ).toString("utf-8");
264
+ } else {
265
+ messageContent = new TextDecoder().decode(
266
+ Uint8Array.from(
267
+ atob(message.message),
268
+ (c) => c.charCodeAt(0)
269
+ )
270
+ );
271
+ }
272
+ } catch (error) {
273
+ const logMessage = `Error decoding message: ${error}`;
274
+ this.logger.error(logMessage);
275
+ continue;
276
+ }
277
+ let messageJson;
278
+ try {
279
+ messageJson = JSON.parse(messageContent);
280
+ } catch (error) {
281
+ const logMessage = `Invalid JSON message content: ${messageContent}`;
282
+ this.logger.error(logMessage);
283
+ continue;
284
+ }
285
+ messageJson.sequence_number = message.sequence_number;
286
+ messages.push({
287
+ ...messageJson,
288
+ consensus_timestamp: message.consensus_timestamp,
289
+ sequence_number: message.sequence_number,
290
+ running_hash: message.running_hash,
291
+ running_hash_version: message.running_hash_version,
292
+ topic_id: message.topic_id,
293
+ payer: message.payer_account_id,
294
+ created: new Date(Number(message.consensus_timestamp) * 1e3)
295
+ });
296
+ } catch (error) {
297
+ const logMessage = `Error processing message: ${error.message}`;
298
+ this.logger.error(logMessage);
299
+ }
300
+ }
301
+ }
302
+ nextEndpoint = data.links?.next || "";
303
+ } catch (e) {
304
+ const error = e;
305
+ const logMessage = `Error querying topic messages for topic ${topicId} (endpoint: ${nextEndpoint}) after retries: ${error.message}`;
306
+ this.logger.error(logMessage);
307
+ throw new Error(logMessage);
308
+ }
327
309
  }
328
- this.registrationAutoTopUp = options.registrationAutoTopUp;
329
- this.historyAutoTopUp = options.historyAutoTopUp;
330
- this.encryptedChatManager = new EncryptedChatManager(this);
331
- this.encryptionOptions = options.encryption;
332
- this.encryptionBootstrapPromise = this.bootstrapEncryptionOptions(
333
- options.encryption
334
- );
335
- this.chat = {
336
- start: (options2) => this.startChat(options2),
337
- createSession: (payload) => this.createSession(payload),
338
- sendMessage: (payload) => this.sendMessage(payload),
339
- endSession: (sessionId) => this.endSession(sessionId),
340
- getHistory: (sessionId, options2) => this.fetchHistorySnapshot(sessionId, options2),
341
- compactHistory: (payload) => this.compactHistory(payload),
342
- getEncryptionStatus: (sessionId) => this.fetchEncryptionStatus(sessionId),
343
- submitEncryptionHandshake: (sessionId, payload) => this.postEncryptionHandshake(sessionId, payload),
344
- startConversation: (opts) => this.startConversation(opts),
345
- acceptConversation: (opts) => this.acceptConversation(opts)
346
- };
347
- this.encryption = {
348
- registerKey: (payload) => this.registerEncryptionKey(payload),
349
- generateEphemeralKeyPair: () => this.createEphemeralKeyPair(),
350
- deriveSharedSecret: (options2) => this.deriveSharedSecret(options2),
351
- encryptCipherEnvelope: (options2) => this.buildCipherEnvelope(options2),
352
- decryptCipherEnvelope: (options2) => this.openCipherEnvelope(options2),
353
- ensureAgentKey: (options2) => this.ensureAgentEncryptionKey(options2)
354
- };
355
- this.chat.createEncryptedSession = (options2) => this.encryptedChatManager.startSession(options2);
356
- this.chat.acceptEncryptedSession = (options2) => this.encryptedChatManager.acceptSession(options2);
357
- }
358
- static async initializeAgent(options) {
359
- const { uaid, ensureEncryptionKey = true, ...clientOptions } = options;
360
- const client = new RegistryBrokerClient(clientOptions);
361
- let encryption = null;
362
- if (ensureEncryptionKey) {
363
- const ensureOptions = typeof ensureEncryptionKey === "object" ? ensureEncryptionKey : { generateIfMissing: true };
364
- encryption = await client.encryption.ensureAgentKey({
365
- uaid,
366
- ...ensureOptions
367
- });
368
- }
369
- return { client, encryption };
370
- }
371
- setApiKey(apiKey) {
372
- this.setDefaultHeader("x-api-key", apiKey);
310
+ return messages;
373
311
  }
374
- setLedgerApiKey(apiKey) {
375
- this.setDefaultHeader("x-ledger-api-key", apiKey);
376
- }
377
- setDefaultHeader(name, value) {
378
- if (!name || name.trim().length === 0) {
379
- return;
380
- }
381
- const headerName = normaliseHeaderName(name);
382
- if (!value || value.trim().length === 0) {
383
- delete this.defaultHeaders[headerName];
384
- return;
312
+ /**
313
+ * Requests account information for a given account ID from the mirror node.
314
+ * @param accountId The ID of the account to retrieve information for.
315
+ * @returns A promise that resolves to the account information.
316
+ * @throws An error if the account ID is invalid or the information cannot be retrieved.
317
+ */
318
+ async requestAccount(accountId) {
319
+ try {
320
+ this.logger.debug(`Requesting account info for ${accountId}`);
321
+ const data = await this._requestWithRetry(
322
+ `/api/v1/accounts/${accountId}`
323
+ );
324
+ if (!data) {
325
+ throw new Error(
326
+ `No data received from mirror node for account: ${accountId}`
327
+ );
328
+ }
329
+ return data;
330
+ } catch (e) {
331
+ const error = e;
332
+ const logMessage = `Failed to fetch account ${accountId} after retries: ${error.message}`;
333
+ this.logger.error(logMessage);
334
+ throw new Error(logMessage);
335
+ }
336
+ }
337
+ /**
338
+ * Checks if a user has access to a given key list.
339
+ * @param keyBytes The key list to check access for.
340
+ * @param userPublicKey The public key of the user to check access for.
341
+ * @returns A promise that resolves to true if the user has access, false otherwise.
342
+ */
343
+ async checkKeyListAccess(keyBytes, userPublicKey) {
344
+ try {
345
+ const key = proto.Key.decode(keyBytes);
346
+ return this.evaluateKeyAccess(key, userPublicKey);
347
+ } catch (e) {
348
+ const error = e;
349
+ const logMessage = `Error decoding protobuf key: ${error.message}`;
350
+ this.logger.error(logMessage);
351
+ throw new Error(logMessage);
352
+ }
353
+ }
354
+ /**
355
+ * Evaluates the access of a given key to a user's public key.
356
+ * @param key The key to evaluate access for.
357
+ * @param userPublicKey The public key of the user to evaluate access for.
358
+ * @returns A promise that resolves to true if the key has access, false otherwise.
359
+ */
360
+ async evaluateKeyAccess(key, userPublicKey) {
361
+ if (key.ed25519) {
362
+ return this.compareEd25519Key(key.ed25519, userPublicKey);
363
+ }
364
+ if (key.keyList) {
365
+ return this.evaluateKeyList(key.keyList, userPublicKey);
366
+ }
367
+ if (key.thresholdKey && key.thresholdKey.keys) {
368
+ return this.evaluateKeyList(key.thresholdKey.keys, userPublicKey);
385
369
  }
386
- this.defaultHeaders[headerName] = value.trim();
387
- }
388
- getDefaultHeaders() {
389
- return { ...this.defaultHeaders };
370
+ return false;
390
371
  }
391
- async encryptionReady() {
392
- if (!this.encryptionBootstrapPromise) {
393
- return;
372
+ /**
373
+ * Evaluates the access of a given key list to a user's public key.
374
+ * @param keyList The key list to evaluate access for.
375
+ * @param userPublicKey The public key of the user to evaluate access for.
376
+ * @returns A promise that resolves to true if the key list has access, false otherwise.
377
+ */
378
+ async evaluateKeyList(keyList, userPublicKey) {
379
+ const keys = keyList.keys || [];
380
+ for (const listKey of keys) {
381
+ if (!listKey) continue;
382
+ if (listKey.ed25519) {
383
+ if (this.compareEd25519Key(listKey.ed25519, userPublicKey)) {
384
+ return true;
385
+ }
386
+ } else if (listKey.keyList || listKey.thresholdKey) {
387
+ try {
388
+ const nestedKeyBytes = proto.Key.encode({
389
+ ...listKey.keyList ? { keyList: listKey.keyList } : {},
390
+ ...listKey.thresholdKey ? { thresholdKey: listKey.thresholdKey } : {}
391
+ }).finish();
392
+ const hasNestedAccess = await this.checkKeyListAccess(
393
+ Buffer.from(nestedKeyBytes),
394
+ userPublicKey
395
+ );
396
+ if (hasNestedAccess) {
397
+ return true;
398
+ }
399
+ } catch (e) {
400
+ const error = e;
401
+ const logMessage = `Error in nested key: ${error.message}`;
402
+ this.logger.debug(logMessage);
403
+ }
404
+ }
394
405
  }
395
- await this.encryptionBootstrapPromise;
396
- }
397
- async search(params = {}) {
398
- const query = buildSearchQuery(params);
399
- const raw = await this.requestJson(`/search${query}`, {
400
- method: "GET"
401
- });
402
- return this.parseWithSchema(raw, searchResponseSchema, "search response");
403
- }
404
- async stats() {
405
- const raw = await this.requestJson("/stats", { method: "GET" });
406
- return this.parseWithSchema(raw, statsResponseSchema, "stats response");
406
+ return false;
407
407
  }
408
- async registries() {
409
- const raw = await this.requestJson("/registries", {
410
- method: "GET"
411
- });
412
- return this.parseWithSchema(
413
- raw,
414
- registriesResponseSchema,
415
- "registries response"
416
- );
408
+ /**
409
+ * Compares an Ed25519 key with a user's public key.
410
+ * @param keyData The Ed25519 key data to compare.
411
+ * @param userPublicKey The public key of the user to compare with.
412
+ * @returns A boolean indicating whether the key matches the user's public key.
413
+ */
414
+ compareEd25519Key(keyData, userPublicKey) {
415
+ try {
416
+ const decodedKey = PublicKey.fromBytes(Buffer.from(keyData));
417
+ return decodedKey.toString() === userPublicKey.toString();
418
+ } catch (e) {
419
+ const error = e;
420
+ const logMessage = `Error comparing Ed25519 key: ${error.message}`;
421
+ this.logger.debug(logMessage);
422
+ return false;
423
+ }
417
424
  }
418
- async getAdditionalRegistries() {
419
- const raw = await this.requestJson(
420
- "/register/additional-registries",
421
- {
422
- method: "GET"
425
+ /**
426
+ * Retrieves information about a scheduled transaction
427
+ * @param scheduleId The ID of the scheduled transaction
428
+ * @returns A promise that resolves to the scheduled transaction information
429
+ */
430
+ async getScheduleInfo(scheduleId) {
431
+ try {
432
+ this.logger.info(
433
+ `Getting information for scheduled transaction ${scheduleId}`
434
+ );
435
+ const data = await this._requestWithRetry(
436
+ `/api/v1/schedules/${scheduleId}`
437
+ );
438
+ if (data) {
439
+ return data;
423
440
  }
424
- );
425
- return this.parseWithSchema(
426
- raw,
427
- additionalRegistryCatalogResponseSchema,
428
- "additional registry catalog response"
429
- );
430
- }
431
- bootstrapEncryptionOptions(options) {
432
- if (!options?.autoRegister || options.autoRegister.enabled === false) {
441
+ this.logger.warn(
442
+ `No schedule info found for ${scheduleId} after retries.`
443
+ );
444
+ return null;
445
+ } catch (error) {
446
+ this.logger.error(
447
+ `Error fetching schedule info for ${scheduleId} after retries: ${error.message}`
448
+ );
433
449
  return null;
434
450
  }
435
- return this.autoRegisterEncryptionKey(options.autoRegister).then(
436
- () => void 0
437
- );
438
451
  }
439
- async autoRegisterEncryptionKey(config) {
440
- const identity = this.normalizeAutoRegisterIdentity(config);
441
- if (!identity) {
442
- throw new Error(
443
- "Auto-registration requires uaid, ledgerAccountId, or email"
452
+ /**
453
+ * Checks the status of a scheduled transaction
454
+ * @param scheduleId The schedule ID to check
455
+ * @returns Status of the scheduled transaction
456
+ */
457
+ async getScheduledTransactionStatus(scheduleId) {
458
+ try {
459
+ this.logger.info(
460
+ `Checking status of scheduled transaction ${scheduleId}`
444
461
  );
445
- }
446
- const material = await this.resolveAutoRegisterKeyMaterial(config);
447
- if (!material) {
448
- throw new Error(
449
- "Unable to resolve encryption public key for auto-registration"
462
+ const scheduleInfo = await this.getScheduleInfo(scheduleId);
463
+ if (!scheduleInfo) {
464
+ throw new Error(`Schedule ${scheduleId} not found`);
465
+ }
466
+ return {
467
+ executed: Boolean(scheduleInfo.executed_timestamp),
468
+ executedDate: scheduleInfo.executed_timestamp ? new Date(Number(scheduleInfo.executed_timestamp) * 1e3) : void 0,
469
+ deleted: scheduleInfo.deleted || false
470
+ };
471
+ } catch (error) {
472
+ this.logger.error(
473
+ `Error checking scheduled transaction status: ${error}`
450
474
  );
475
+ throw error;
451
476
  }
452
- await this.registerEncryptionKey({
453
- keyType: config.keyType ?? "secp256k1",
454
- publicKey: material.publicKey,
455
- ...identity
456
- });
457
- return material;
458
477
  }
459
- normalizeAutoRegisterIdentity(config) {
460
- const identity = {};
461
- if (config.uaid) {
462
- identity.uaid = config.uaid;
463
- }
464
- if (config.ledgerAccountId) {
465
- identity.ledgerAccountId = config.ledgerAccountId;
466
- if (config.ledgerNetwork) {
467
- identity.ledgerNetwork = config.ledgerNetwork;
478
+ /**
479
+ * Retrieves details for a given transaction ID or hash from the mirror node.
480
+ * @param transactionIdOrHash The ID or hash of the transaction.
481
+ * @returns A promise that resolves to the transaction details.
482
+ * @throws An error if the transaction ID/hash is invalid or details cannot be retrieved.
483
+ */
484
+ async getTransaction(transactionIdOrHash) {
485
+ this.logger.info(
486
+ `Getting transaction details for ID/hash: ${transactionIdOrHash}`
487
+ );
488
+ try {
489
+ const response = await this._requestWithRetry(`/api/v1/transactions/${transactionIdOrHash}`);
490
+ if (response?.transactions?.length > 0) {
491
+ this.logger.trace(
492
+ `Transaction details found for ${transactionIdOrHash}:`,
493
+ response.transactions[0]
494
+ );
495
+ return response.transactions[0];
468
496
  }
497
+ this.logger.warn(
498
+ `No transaction details found for ${transactionIdOrHash} or unexpected response structure.`
499
+ );
500
+ return null;
501
+ } catch (e) {
502
+ const error = e;
503
+ this.logger.error(
504
+ `Failed to get transaction details for ${transactionIdOrHash} after retries: ${error.message}`
505
+ );
506
+ return null;
469
507
  }
470
- if (config.email) {
471
- identity.email = config.email;
472
- }
473
- if (identity.uaid || identity.ledgerAccountId || identity.email) {
474
- return identity;
475
- }
476
- return null;
477
508
  }
478
- async resolveAutoRegisterKeyMaterial(config) {
479
- if (config.publicKey?.trim()) {
480
- return { publicKey: config.publicKey.trim() };
481
- }
482
- let privateKey = config.privateKey?.trim();
483
- const envVar = config.envVar ?? "RB_ENCRYPTION_PRIVATE_KEY";
484
- if (!privateKey && envVar && process?.env?.[envVar]?.trim()) {
485
- privateKey = process.env[envVar]?.trim();
486
- }
487
- if (!privateKey && config.generateIfMissing) {
488
- const pair = await this.generateEncryptionKeyPair({
489
- keyType: config.keyType ?? "secp256k1",
490
- envVar,
491
- envPath: config.envPath,
492
- overwrite: config.overwriteEnv
493
- });
494
- if (envVar) {
495
- process.env[envVar] = pair.privateKey;
509
+ /**
510
+ * Private helper to make GET requests with retry logic using Axios.
511
+ */
512
+ async _requestWithRetry(endpoint, axiosConfig) {
513
+ let attempt = 0;
514
+ let delay = this.initialDelayMs;
515
+ const url = this.constructUrl(endpoint);
516
+ const config = {
517
+ ...axiosConfig,
518
+ headers: {
519
+ ...this.customHeaders,
520
+ ...axiosConfig?.headers
496
521
  }
497
- return { publicKey: pair.publicKey, privateKey: pair.privateKey };
498
- }
499
- if (privateKey) {
500
- const publicKey = this.derivePublicKeyFromPrivateKey(privateKey);
501
- return { publicKey, privateKey };
522
+ };
523
+ if (this.apiKey) {
524
+ config.headers = {
525
+ ...config.headers,
526
+ Authorization: `Bearer ${this.apiKey}`,
527
+ "X-API-Key": this.apiKey
528
+ };
502
529
  }
503
- return null;
504
- }
505
- derivePublicKeyFromPrivateKey(privateKey) {
506
- const normalized = this.hexToBuffer(privateKey);
507
- const publicKey = secp256k1.getPublicKey(normalized, true);
508
- return Buffer.from(publicKey).toString("hex");
509
- }
510
- ensureAgentEncryptionKey(options) {
511
- return this.autoRegisterEncryptionKey({
512
- ...options,
513
- uaid: options.uaid,
514
- enabled: true
515
- });
516
- }
517
- async popularSearches() {
518
- const raw = await this.requestJson("/popular", {
519
- method: "GET"
520
- });
521
- return this.parseWithSchema(
522
- raw,
523
- popularResponseSchema,
524
- "popular searches response"
525
- );
526
- }
527
- async resolveUaid(uaid) {
528
- const raw = await this.requestJson(
529
- `/resolve/${encodeURIComponent(uaid)}`,
530
- {
531
- method: "GET"
532
- }
533
- );
534
- return this.parseWithSchema(
535
- raw,
536
- resolveResponseSchema,
537
- "resolve UAID response"
538
- );
539
- }
540
- async performRegisterAgent(payload) {
541
- const raw = await this.requestJson("/register", {
542
- method: "POST",
543
- body: serialiseAgentRegistrationRequest(payload),
544
- headers: { "content-type": "application/json" }
545
- });
546
- return this.parseWithSchema(
547
- raw,
548
- registerAgentResponseSchema,
549
- "register agent response"
550
- );
551
- }
552
- async registerAgent(payload, options) {
553
- const autoTopUp = options?.autoTopUp ?? this.registrationAutoTopUp;
554
- if (!autoTopUp) {
555
- return this.performRegisterAgent(payload);
556
- }
557
- await this.ensureCreditsForRegistration(payload, autoTopUp);
558
- let retried = false;
559
- while (true) {
530
+ while (attempt < this.maxRetries) {
560
531
  try {
561
- return await this.performRegisterAgent(payload);
532
+ const response = await axios.get(url, config);
533
+ return response.data;
562
534
  } catch (error) {
563
- const shortfall = this.extractInsufficientCreditsDetails(error);
564
- if (shortfall && !retried) {
565
- await this.ensureCreditsForRegistration(payload, autoTopUp);
566
- retried = true;
567
- continue;
535
+ attempt++;
536
+ const isLastAttempt = attempt >= this.maxRetries;
537
+ const statusCode = error.response?.status;
538
+ if (statusCode && statusCode > 404 && statusCode < 500 && statusCode !== 429) {
539
+ this.logger.error(
540
+ `Client error for ${url} (status ${statusCode}): ${error.message}. Not retrying.`
541
+ );
542
+ throw error;
543
+ }
544
+ if (isLastAttempt) {
545
+ this.logger.error(
546
+ `Max retries (${this.maxRetries}) reached for ${url}. Last error: ${error.message}`
547
+ );
548
+ throw error;
568
549
  }
569
- throw error;
550
+ this.logger.warn(
551
+ `Attempt ${attempt}/${this.maxRetries} failed for ${url}: ${error.message}. Retrying in ${delay}ms...`
552
+ );
553
+ await new Promise((resolve) => setTimeout(resolve, delay));
554
+ delay = Math.min(delay * this.backoffFactor, this.maxDelayMs);
570
555
  }
571
556
  }
572
- }
573
- async getRegistrationQuote(payload) {
574
- const raw = await this.requestJson("/register/quote", {
575
- method: "POST",
576
- body: serialiseAgentRegistrationRequest(payload),
577
- headers: { "content-type": "application/json" }
578
- });
579
- return this.parseWithSchema(
580
- raw,
581
- registrationQuoteResponseSchema,
582
- "registration quote response"
557
+ throw new Error(
558
+ `Failed to fetch data from ${url} after ${this.maxRetries} attempts.`
583
559
  );
584
560
  }
585
- async updateAgent(uaid, payload) {
586
- const raw = await this.requestJson(
587
- `/register/${encodeURIComponent(uaid)}`,
588
- {
589
- method: "PUT",
590
- body: serialiseAgentRegistrationRequest(payload),
591
- headers: { "content-type": "application/json" }
561
+ /**
562
+ * Private helper to make fetch requests with retry logic.
563
+ */
564
+ async _fetchWithRetry(url, fetchOptions) {
565
+ let attempt = 0;
566
+ let delay = this.initialDelayMs;
567
+ const headers = {
568
+ ...this.customHeaders
569
+ };
570
+ if (fetchOptions?.headers) {
571
+ if (fetchOptions.headers instanceof Headers) {
572
+ fetchOptions.headers.forEach((value, key) => {
573
+ headers[key] = value;
574
+ });
575
+ } else if (Array.isArray(fetchOptions.headers)) {
576
+ fetchOptions.headers.forEach(([key, value]) => {
577
+ headers[key] = value;
578
+ });
579
+ } else {
580
+ Object.assign(headers, fetchOptions.headers);
592
581
  }
593
- );
594
- return this.parseWithSchema(
595
- raw,
596
- registerAgentResponseSchema,
597
- "update agent response"
598
- );
599
- }
600
- async getRegistrationProgress(attemptId) {
601
- const normalisedAttemptId = attemptId.trim();
602
- if (!normalisedAttemptId) {
603
- throw new Error("attemptId is required");
604
582
  }
605
- try {
606
- const raw = await this.requestJson(
607
- `/register/progress/${encodeURIComponent(normalisedAttemptId)}`,
608
- { method: "GET" }
609
- );
610
- const parsed = this.parseWithSchema(
611
- raw,
612
- registrationProgressResponseSchema,
613
- "registration progress response"
614
- );
615
- return parsed.progress;
616
- } catch (error) {
617
- if (error instanceof RegistryBrokerError && error.status === 404) {
618
- return null;
619
- }
620
- throw error;
583
+ if (this.apiKey) {
584
+ headers["Authorization"] = `Bearer ${this.apiKey}`;
585
+ headers["X-API-Key"] = this.apiKey;
621
586
  }
622
- }
623
- async waitForRegistrationCompletion(attemptId, options = {}) {
624
- const normalisedAttemptId = attemptId.trim();
625
- if (!normalisedAttemptId) {
626
- throw new Error("attemptId is required");
627
- }
628
- const interval = Math.max(
629
- 250,
630
- options.intervalMs ?? DEFAULT_PROGRESS_INTERVAL_MS
631
- );
632
- const timeoutMs = options.timeoutMs ?? DEFAULT_PROGRESS_TIMEOUT_MS;
633
- const throwOnFailure = options.throwOnFailure ?? true;
634
- const signal = options.signal;
635
- const startedAt = Date.now();
636
- while (true) {
637
- if (signal?.aborted) {
638
- throw createAbortError();
639
- }
640
- const progress = await this.getRegistrationProgress(normalisedAttemptId);
641
- if (progress) {
642
- options.onProgress?.(progress);
643
- if (progress.status === "completed") {
644
- return progress;
645
- }
646
- if (progress.status === "partial" || progress.status === "failed") {
647
- if (throwOnFailure) {
648
- throw new RegistryBrokerError(
649
- "Registration did not complete successfully",
650
- {
651
- status: 409,
652
- statusText: progress.status,
653
- body: progress
654
- }
587
+ const options = {
588
+ ...fetchOptions,
589
+ headers
590
+ };
591
+ while (attempt < this.maxRetries) {
592
+ try {
593
+ const request = await fetch(url, options);
594
+ if (!request.ok) {
595
+ if (request.status >= 400 && request.status < 500 && request.status !== 429) {
596
+ this.logger.error(
597
+ `Client error for ${url} (status ${request.status}): ${request.statusText}. Not retrying.`
598
+ );
599
+ throw new Error(
600
+ `Fetch failed with status ${request.status}: ${request.statusText} for URL: ${url}`
655
601
  );
656
602
  }
657
- return progress;
603
+ throw new Error(
604
+ `Fetch failed with status ${request.status}: ${request.statusText} for URL: ${url}`
605
+ );
658
606
  }
659
- }
660
- if (Date.now() - startedAt >= timeoutMs) {
661
- throw new Error(
662
- `Registration progress polling timed out after ${timeoutMs}ms`
607
+ const response = await request.json();
608
+ return response;
609
+ } catch (error) {
610
+ attempt++;
611
+ if (attempt >= this.maxRetries) {
612
+ this.logger.error(
613
+ `Max retries (${this.maxRetries}) reached for ${url}. Last error: ${error.message}`
614
+ );
615
+ throw error;
616
+ }
617
+ this.logger.warn(
618
+ `Attempt ${attempt}/${this.maxRetries} failed for ${url}: ${error.message}. Retrying in ${delay}ms...`
663
619
  );
620
+ await new Promise((resolve) => setTimeout(resolve, delay));
621
+ delay = Math.min(delay * this.backoffFactor, this.maxDelayMs);
664
622
  }
665
- await this.delay(interval, signal);
666
623
  }
667
- }
668
- async purchaseCreditsWithHbar(params) {
669
- const body = {
670
- accountId: params.accountId,
671
- payerKey: params.privateKey,
672
- hbarAmount: this.calculateHbarAmountParam(params.hbarAmount)
673
- };
674
- if (params.memo) {
675
- body.memo = params.memo;
676
- }
677
- if (params.metadata) {
678
- body.metadata = params.metadata;
679
- }
680
- const raw = await this.requestJson("/credits/purchase", {
681
- method: "POST",
682
- headers: { "content-type": "application/json" },
683
- body
684
- });
685
- return this.parseWithSchema(
686
- raw,
687
- creditPurchaseResponseSchema,
688
- "credit purchase response"
624
+ throw new Error(
625
+ `Failed to fetch data from ${url} after ${this.maxRetries} attempts.`
689
626
  );
690
627
  }
691
- async getX402Minimums() {
692
- const raw = await this.requestJson(
693
- "/credits/purchase/x402/minimums",
694
- { method: "GET" }
695
- );
696
- return this.parseWithSchema(
697
- raw,
698
- x402MinimumsResponseSchema,
699
- "x402 minimums response"
700
- );
701
- }
702
- async purchaseCreditsWithX402(params) {
703
- if (!Number.isFinite(params.credits) || params.credits <= 0) {
704
- throw new Error("credits must be a positive number");
705
- }
706
- if (params.usdAmount !== void 0 && (!Number.isFinite(params.usdAmount) || params.usdAmount <= 0)) {
707
- throw new Error("usdAmount must be a positive number when provided");
708
- }
709
- const body = {
710
- accountId: params.accountId,
711
- credits: params.credits
712
- };
713
- if (params.usdAmount !== void 0) {
714
- body.usdAmount = params.usdAmount;
715
- }
716
- if (params.description) {
717
- body.description = params.description;
718
- }
719
- if (params.metadata) {
720
- body.metadata = params.metadata;
721
- }
722
- const axiosClient = axios.create({
723
- baseURL: this.baseUrl,
724
- headers: {
725
- ...this.getDefaultHeaders(),
726
- "content-type": "application/json"
628
+ /**
629
+ * Retrieves the numerical balance (in HBAR) for a given account ID.
630
+ * @param accountId The ID of the account.
631
+ * @returns A promise that resolves to the HBAR balance or null if an error occurs.
632
+ */
633
+ async getAccountBalance(accountId) {
634
+ this.logger.info(`Getting balance for account ${accountId}`);
635
+ try {
636
+ const accountInfo = await this.requestAccount(accountId);
637
+ if (accountInfo && accountInfo.balance) {
638
+ const hbarBalance = accountInfo.balance.balance / 1e8;
639
+ return hbarBalance;
727
640
  }
728
- });
729
- const paymentClient = withPaymentInterceptor(
730
- axiosClient,
731
- params.walletClient
732
- );
733
- const response = await paymentClient.post("/credits/purchase/x402", body);
734
- const parsed = this.parseWithSchema(
735
- response.data,
736
- x402CreditPurchaseResponseSchema,
737
- "x402 credit purchase response"
738
- );
739
- const paymentHeader = typeof response.headers["x-payment-response"] === "string" ? response.headers["x-payment-response"] : void 0;
740
- const decodedPayment = paymentHeader !== void 0 ? decodeXPaymentResponse(paymentHeader) : void 0;
741
- return {
742
- ...parsed,
743
- paymentResponseHeader: paymentHeader,
744
- paymentResponse: decodedPayment
745
- };
746
- }
747
- async buyCreditsWithX402(params) {
748
- const network = params.network ?? "base";
749
- const normalizedKey = normalizeHexPrivateKey(params.evmPrivateKey);
750
- const walletClient = await createSigner(network, normalizedKey);
751
- return this.purchaseCreditsWithX402({
752
- accountId: params.accountId,
753
- credits: params.credits,
754
- usdAmount: params.usdAmount,
755
- description: params.description,
756
- metadata: params.metadata,
757
- walletClient
758
- });
759
- }
760
- calculateHbarAmount(creditsToPurchase, creditsPerHbar) {
761
- if (creditsPerHbar <= 0) {
762
- throw new Error("creditsPerHbar must be positive");
763
- }
764
- if (creditsToPurchase <= 0) {
765
- throw new Error("creditsToPurchase must be positive");
641
+ this.logger.warn(
642
+ `Could not retrieve balance for account ${accountId} from account info.`
643
+ );
644
+ return null;
645
+ } catch (error) {
646
+ this.logger.error(
647
+ `Error fetching numerical balance for account ${accountId}: ${error.message}`
648
+ );
649
+ return null;
766
650
  }
767
- const rawHbar = creditsToPurchase / creditsPerHbar;
768
- const tinybars = Math.ceil(rawHbar * 1e8);
769
- return tinybars / 1e8;
770
651
  }
771
- resolveCreditsToPurchase(shortfallCredits) {
772
- if (!Number.isFinite(shortfallCredits) || shortfallCredits <= 0) {
773
- return 0;
774
- }
775
- return Math.max(
776
- Math.ceil(shortfallCredits),
777
- MINIMUM_REGISTRATION_AUTO_TOP_UP_CREDITS
652
+ /**
653
+ * Retrieves messages for a given topic ID with optional filters.
654
+ * @param topicId The ID of the topic.
655
+ * @param sequenceNumber Filter by sequence number (e.g., "gt:10", "lte:20").
656
+ * @param startTime Filter by consensus timestamp (e.g., "gt:1629400000.000000000").
657
+ * @param endTime Filter by consensus timestamp (e.g., "lt:1629500000.000000000").
658
+ * @param limit The maximum number of messages to return.
659
+ * @returns A promise that resolves to an array of HCSMessages or null.
660
+ */
661
+ async getTopicMessagesByFilter(topicId, options) {
662
+ this.logger.trace(
663
+ `Querying messages for topic ${topicId} with filters: ${JSON.stringify(
664
+ options
665
+ )}`
778
666
  );
779
- }
780
- calculateHbarAmountParam(hbarAmount) {
781
- const tinybars = Math.ceil(hbarAmount * 1e8);
782
- if (tinybars <= 0) {
783
- throw new Error("Calculated purchase amount must be positive");
667
+ let nextUrl = `/api/v1/topics/${topicId}/messages`;
668
+ const params = new URLSearchParams();
669
+ if (options?.limit) {
670
+ params.append("limit", options.limit.toString());
784
671
  }
785
- return tinybars / 1e8;
786
- }
787
- shouldAutoTopUpHistory(payload, error) {
788
- if (!this.historyAutoTopUp || payload.historyTtlSeconds === void 0) {
789
- return false;
672
+ if (options?.sequenceNumber) {
673
+ params.append("sequencenumber", options.sequenceNumber);
790
674
  }
791
- if (!(error instanceof RegistryBrokerError)) {
792
- return false;
675
+ if (options?.startTime) {
676
+ params.append("timestamp", `gte:${options.startTime}`);
793
677
  }
794
- if (error.status !== 402) {
795
- return false;
678
+ if (options?.endTime) {
679
+ params.append("timestamp", `lt:${options.endTime}`);
796
680
  }
797
- const message = this.extractErrorMessage(error.body);
798
- if (!message) {
799
- return true;
681
+ if (options?.order) {
682
+ params.append("order", options.order);
800
683
  }
801
- const normalised = message.toLowerCase();
802
- return normalised.includes("history") || normalised.includes("chat history");
803
- }
804
- extractErrorMessage(body) {
805
- if (typeof body === "string") {
806
- return body;
684
+ const queryString = params.toString();
685
+ if (queryString) {
686
+ nextUrl += `?${queryString}`;
807
687
  }
808
- if (isJsonObject(body) && typeof body.error === "string") {
809
- return body.error;
810
- }
811
- if (isJsonObject(body) && typeof body.message === "string") {
812
- return body.message;
813
- }
814
- return void 0;
815
- }
816
- async executeHistoryAutoTopUp(reason) {
817
- if (!this.historyAutoTopUp) {
818
- return;
819
- }
820
- const hbarAmount = this.historyAutoTopUp.hbarAmount && this.historyAutoTopUp.hbarAmount > 0 ? this.historyAutoTopUp.hbarAmount : DEFAULT_HISTORY_TOP_UP_HBAR;
821
- await this.purchaseCreditsWithHbar({
822
- accountId: this.historyAutoTopUp.accountId,
823
- privateKey: this.historyAutoTopUp.privateKey,
824
- hbarAmount,
825
- memo: this.historyAutoTopUp.memo ?? "registry-broker-client:chat-history-topup",
826
- metadata: {
827
- purpose: "chat-history",
828
- reason
829
- }
830
- });
831
- }
832
- async ensureCreditsForRegistration(payload, autoTopUp) {
833
- const details = autoTopUp ?? null;
834
- if (!details) {
835
- return;
836
- }
837
- if (!details.accountId || !details.accountId.trim()) {
838
- throw new Error("autoTopUp.accountId is required");
839
- }
840
- if (!details.privateKey || !details.privateKey.trim()) {
841
- throw new Error("autoTopUp.privateKey is required");
842
- }
843
- for (let attempt = 0; attempt < 3; attempt += 1) {
844
- const quote = await this.getRegistrationQuote(payload);
845
- const shortfall = quote.shortfallCredits ?? 0;
846
- if (shortfall <= 0) {
847
- return;
848
- }
849
- const creditsToPurchase = this.resolveCreditsToPurchase(shortfall);
850
- if (creditsToPurchase <= 0) {
851
- return;
852
- }
853
- const creditsPerHbar = quote.creditsPerHbar ?? null;
854
- if (!creditsPerHbar || creditsPerHbar <= 0) {
855
- throw new Error("Unable to determine credits per HBAR for auto top-up");
688
+ const messages = [];
689
+ let pagesFetched = 0;
690
+ const maxPages = 10;
691
+ try {
692
+ while (nextUrl && pagesFetched < maxPages) {
693
+ pagesFetched++;
694
+ const data = await this._requestWithRetry(nextUrl);
695
+ if (data.messages && data.messages.length > 0) {
696
+ for (const message of data.messages) {
697
+ try {
698
+ if (!message.message) {
699
+ continue;
700
+ }
701
+ let messageContent;
702
+ if (this.isServerEnvironment) {
703
+ messageContent = Buffer.from(
704
+ message.message,
705
+ "base64"
706
+ ).toString("utf-8");
707
+ } else {
708
+ messageContent = new TextDecoder().decode(
709
+ Uint8Array.from(atob(message.message), (c) => c.charCodeAt(0))
710
+ );
711
+ }
712
+ let messageJson = {};
713
+ try {
714
+ messageJson = JSON.parse(messageContent);
715
+ } catch (parseError) {
716
+ this.logger.debug(
717
+ `Message content is not valid JSON, using raw: ${messageContent}`
718
+ );
719
+ messageJson = { raw_content: messageContent };
720
+ }
721
+ const parsedContent = messageJson;
722
+ const hcsMsg = {
723
+ ...parsedContent,
724
+ consensus_timestamp: message.consensus_timestamp,
725
+ sequence_number: message.sequence_number,
726
+ payer_account_id: message.payer_account_id,
727
+ topic_id: message.topic_id,
728
+ running_hash: message.running_hash,
729
+ running_hash_version: message.running_hash_version,
730
+ chunk_info: message.chunk_info,
731
+ created: new Date(
732
+ Number(message.consensus_timestamp.split(".")[0]) * 1e3 + Number(message.consensus_timestamp.split(".")[1] || 0) / 1e6
733
+ ),
734
+ payer: message.payer_account_id
735
+ };
736
+ messages.push(hcsMsg);
737
+ } catch (error) {
738
+ this.logger.error(
739
+ `Error processing individual message: ${error.message}`
740
+ );
741
+ }
742
+ }
743
+ }
744
+ if (options?.limit && messages.length >= options.limit) break;
745
+ nextUrl = data.links?.next ? `${data.links.next}` : "";
856
746
  }
857
- const hbarAmount = this.calculateHbarAmount(
858
- creditsToPurchase,
859
- creditsPerHbar
747
+ return messages;
748
+ } catch (e) {
749
+ const error = e;
750
+ this.logger.error(
751
+ `Error querying filtered topic messages for ${topicId}: ${error.message}`
860
752
  );
861
- await this.purchaseCreditsWithHbar({
862
- accountId: details.accountId.trim(),
863
- privateKey: details.privateKey.trim(),
864
- hbarAmount,
865
- memo: details.memo ?? "Registry Broker auto top-up",
866
- metadata: {
867
- shortfallCredits: shortfall,
868
- requiredCredits: quote.requiredCredits,
869
- purchasedCredits: creditsToPurchase
870
- }
871
- });
872
- }
873
- const finalQuote = await this.getRegistrationQuote(payload);
874
- if ((finalQuote.shortfallCredits ?? 0) > 0) {
875
- throw new Error("Unable to purchase sufficient credits for registration");
876
- }
877
- }
878
- extractInsufficientCreditsDetails(error) {
879
- if (!(error instanceof RegistryBrokerError) || error.status !== 402) {
880
- return null;
881
- }
882
- const body = error.body;
883
- if (!body || typeof body !== "object" || Array.isArray(body)) {
884
- return null;
885
- }
886
- const maybeShortfall = body["shortfallCredits"];
887
- if (typeof maybeShortfall !== "number" || maybeShortfall <= 0) {
888
753
  return null;
889
754
  }
890
- return { shortfallCredits: maybeShortfall };
891
- }
892
- async createLedgerChallenge(payload) {
893
- const resolvedNetwork = canonicalizeLedgerNetwork(payload.network);
894
- const network = resolvedNetwork.kind === "hedera" ? resolvedNetwork.hederaNetwork ?? resolvedNetwork.canonical : resolvedNetwork.canonical;
895
- const raw = await this.requestJson("/auth/ledger/challenge", {
896
- method: "POST",
897
- headers: { "content-type": "application/json" },
898
- body: {
899
- accountId: payload.accountId,
900
- network
901
- }
902
- });
903
- return this.parseWithSchema(
904
- raw,
905
- ledgerChallengeResponseSchema,
906
- "ledger challenge response"
907
- );
908
- }
909
- async verifyLedgerChallenge(payload) {
910
- const resolvedNetwork = canonicalizeLedgerNetwork(payload.network);
911
- const network = resolvedNetwork.kind === "hedera" ? resolvedNetwork.hederaNetwork ?? resolvedNetwork.canonical : resolvedNetwork.canonical;
912
- const body = {
913
- challengeId: payload.challengeId,
914
- accountId: payload.accountId,
915
- network,
916
- signature: payload.signature
917
- };
918
- if (payload.signatureKind) {
919
- body.signatureKind = payload.signatureKind;
920
- }
921
- if (payload.publicKey) {
922
- body.publicKey = payload.publicKey;
923
- }
924
- if (typeof payload.expiresInMinutes === "number") {
925
- body.expiresInMinutes = payload.expiresInMinutes;
926
- }
927
- const raw = await this.requestJson("/auth/ledger/verify", {
928
- method: "POST",
929
- headers: { "content-type": "application/json" },
930
- body
931
- });
932
- const result = this.parseWithSchema(
933
- raw,
934
- ledgerVerifyResponseSchema,
935
- "ledger verification response"
936
- );
937
- this.setLedgerApiKey(result.key);
938
- return result;
939
- }
940
- async authenticateWithLedger(options) {
941
- const challenge = await this.createLedgerChallenge({
942
- accountId: options.accountId,
943
- network: options.network
944
- });
945
- const signed = await this.resolveLedgerAuthSignature(
946
- challenge.message,
947
- options
948
- );
949
- const verification = await this.verifyLedgerChallenge({
950
- challengeId: challenge.challengeId,
951
- accountId: options.accountId,
952
- network: options.network,
953
- signature: signed.signature,
954
- signatureKind: signed.signatureKind,
955
- publicKey: signed.publicKey,
956
- expiresInMinutes: options.expiresInMinutes
957
- });
958
- return verification;
959
755
  }
960
- async resolveLedgerAuthSignature(message, options) {
961
- if (typeof options.sign === "function") {
962
- const result = await options.sign(message);
963
- if (!result || typeof result.signature !== "string" || result.signature.length === 0) {
964
- throw new Error("Custom ledger signer failed to produce a signature.");
756
+ /**
757
+ * Retrieves token balances for a given account ID.
758
+ * @param accountId The ID of the account.
759
+ * @param limit The maximum number of tokens to return.
760
+ * @returns A promise that resolves to an array of AccountTokenBalance or null.
761
+ */
762
+ async getAccountTokens(accountId, limit = 100) {
763
+ this.logger.info(`Getting tokens for account ${accountId}`);
764
+ let allTokens = [];
765
+ let endpoint = `/api/v1/accounts/${accountId}/tokens?limit=${limit}`;
766
+ try {
767
+ for (let i = 0; i < 10 && endpoint; i++) {
768
+ const response = await this._requestWithRetry(endpoint);
769
+ if (response && response.tokens) {
770
+ allTokens = allTokens.concat(response.tokens);
771
+ }
772
+ endpoint = response.links?.next || "";
773
+ if (!endpoint || limit && allTokens.length >= limit) {
774
+ if (limit && allTokens.length > limit) {
775
+ allTokens = allTokens.slice(0, limit);
776
+ }
777
+ break;
778
+ }
965
779
  }
966
- return result;
967
- }
968
- if (!options.signer || typeof options.signer.sign !== "function") {
969
- throw new Error(
970
- "Ledger authentication requires a Hedera Signer or custom sign function."
780
+ return allTokens;
781
+ } catch (error) {
782
+ this.logger.error(
783
+ `Error fetching tokens for account ${accountId}: ${error.message}`
971
784
  );
785
+ return null;
972
786
  }
973
- const payload = Buffer.from(message, "utf8");
974
- const signatures = await options.signer.sign([payload]);
975
- const signatureEntry = signatures?.[0];
976
- if (!signatureEntry) {
977
- throw new Error("Signer did not return any signatures.");
978
- }
979
- let derivedPublicKey;
980
- if (signatureEntry.publicKey) {
981
- derivedPublicKey = signatureEntry.publicKey.toString();
982
- } else if (typeof options.signer.getAccountKey === "function") {
983
- const accountKey = await options.signer.getAccountKey();
984
- if (accountKey && typeof accountKey.toString === "function") {
985
- derivedPublicKey = accountKey.toString();
986
- }
987
- }
988
- return {
989
- signature: Buffer.from(signatureEntry.signature).toString("base64"),
990
- signatureKind: "raw",
991
- publicKey: derivedPublicKey
992
- };
993
787
  }
994
- async authenticateWithLedgerCredentials(options) {
995
- const {
996
- accountId,
997
- network,
998
- signer,
999
- sign,
1000
- hederaPrivateKey,
1001
- evmPrivateKey,
1002
- expiresInMinutes,
1003
- setAccountHeader = true,
1004
- label,
1005
- logger
1006
- } = options;
1007
- const resolvedNetwork = canonicalizeLedgerNetwork(network);
1008
- const labelSuffix = label ? ` for ${label}` : "";
1009
- const networkPayload = resolvedNetwork.canonical;
1010
- const authOptions = {
1011
- accountId,
1012
- network: networkPayload,
1013
- expiresInMinutes
1014
- };
1015
- if (sign) {
1016
- authOptions.sign = sign;
1017
- } else if (signer) {
1018
- authOptions.signer = signer;
1019
- } else if (hederaPrivateKey) {
1020
- if (resolvedNetwork.kind !== "hedera" || !resolvedNetwork.hederaNetwork) {
1021
- throw new Error(
1022
- "hederaPrivateKey can only be used with hedera:mainnet or hedera:testnet networks."
1023
- );
1024
- }
1025
- authOptions.signer = createPrivateKeySigner({
1026
- accountId,
1027
- privateKey: hederaPrivateKey,
1028
- network: resolvedNetwork.hederaNetwork
1029
- });
1030
- } else if (evmPrivateKey) {
1031
- if (resolvedNetwork.kind !== "evm") {
1032
- throw new Error(
1033
- "evmPrivateKey can only be used with CAIP-2 EVM networks (eip155:<chainId>)."
1034
- );
1035
- }
1036
- const formattedKey = evmPrivateKey.startsWith("0x") ? evmPrivateKey : `0x${evmPrivateKey}`;
1037
- const account = privateKeyToAccount(formattedKey);
1038
- authOptions.sign = async (message) => ({
1039
- signature: await account.signMessage({ message }),
1040
- signatureKind: "evm",
1041
- publicKey: account.publicKey
1042
- });
1043
- } else {
1044
- throw new Error(
1045
- "Provide a signer, sign function, hederaPrivateKey, or evmPrivateKey to authenticate with the ledger."
788
+ /**
789
+ * Retrieves transaction details by consensus timestamp.
790
+ * @param timestamp The consensus timestamp of the transaction (e.g., "1629400000.000000000").
791
+ * @returns A promise that resolves to the transaction details or null.
792
+ */
793
+ async getTransactionByTimestamp(timestamp) {
794
+ this.logger.info(`Getting transaction by timestamp: ${timestamp}`);
795
+ try {
796
+ const response = await this._requestWithRetry(`/api/v1/transactions?timestamp=${timestamp}&limit=1`);
797
+ return response.transactions;
798
+ } catch (error) {
799
+ this.logger.error(
800
+ `Error fetching transaction by timestamp ${timestamp}: ${error}`
1046
801
  );
1047
- }
1048
- logger?.info?.(
1049
- `Authenticating ledger account ${accountId} (${resolvedNetwork.canonical})${labelSuffix}...`
802
+ return [];
803
+ }
804
+ }
805
+ /**
806
+ * Retrieves NFTs for a given account ID, optionally filtered by token ID.
807
+ * @param accountId The ID of the account.
808
+ * @param tokenId Optional ID of the token to filter NFTs by.
809
+ * @param limit The maximum number of NFTs to return per page (API has its own max).
810
+ * @returns A promise that resolves to an array of NftDetail or null.
811
+ */
812
+ async getAccountNfts(accountId, tokenId, limit = 100) {
813
+ this.logger.info(
814
+ `Getting NFTs for account ${accountId}${tokenId ? ` for token ${tokenId}` : ""}`
1050
815
  );
1051
- const verification = await this.authenticateWithLedger(authOptions);
1052
- if (setAccountHeader) {
1053
- this.setDefaultHeader("x-account-id", verification.accountId);
816
+ let allNfts = [];
817
+ let endpoint = `/api/v1/accounts/${accountId}/nfts?limit=${limit}`;
818
+ if (tokenId) {
819
+ endpoint += `&token.id=${tokenId}`;
1054
820
  }
1055
- logger?.info?.(
1056
- `Ledger authentication complete${labelSuffix}. Issued key prefix: ${verification.apiKey.prefix}…${verification.apiKey.lastFour}`
1057
- );
1058
- return verification;
1059
- }
1060
- async listProtocols() {
1061
- const raw = await this.requestJson("/protocols", {
1062
- method: "GET"
1063
- });
1064
- return this.parseWithSchema(
1065
- raw,
1066
- protocolsResponseSchema,
1067
- "protocols response"
1068
- );
1069
- }
1070
- async detectProtocol(message) {
1071
- const raw = await this.requestJson("/detect-protocol", {
1072
- method: "POST",
1073
- body: { message },
1074
- headers: { "content-type": "application/json" }
1075
- });
1076
- return this.parseWithSchema(
1077
- raw,
1078
- detectProtocolResponseSchema,
1079
- "detect protocol response"
1080
- );
1081
- }
1082
- async registrySearchByNamespace(registry, query) {
1083
- const params = new URLSearchParams();
1084
- if (query) {
1085
- params.set("q", query);
1086
- }
1087
- const suffix = params.size > 0 ? `?${params.toString()}` : "";
1088
- const raw = await this.requestJson(
1089
- `/registries/${encodeURIComponent(registry)}/search${suffix}`,
1090
- {
1091
- method: "GET"
1092
- }
1093
- );
1094
- return this.parseWithSchema(
1095
- raw,
1096
- registrySearchByNamespaceSchema,
1097
- "registry search response"
1098
- );
1099
- }
1100
- async vectorSearch(request) {
1101
821
  try {
1102
- const raw = await this.requestJson("/search", {
1103
- method: "POST",
1104
- body: request,
1105
- headers: { "content-type": "application/json" }
1106
- });
1107
- return this.parseWithSchema(
1108
- raw,
1109
- vectorSearchResponseSchema,
1110
- "vector search response"
1111
- );
1112
- } catch (error) {
1113
- if (error instanceof RegistryBrokerError && error.status === 501) {
1114
- const fallback = await this.search(
1115
- this.buildVectorFallbackSearchParams(request)
1116
- );
1117
- return this.convertSearchResultToVectorResponse(fallback);
822
+ for (let i = 0; i < 10 && endpoint; i++) {
823
+ const response = await this._requestWithRetry(endpoint);
824
+ if (response && response.nfts) {
825
+ const nftsWithUri = response.nfts.map((nft) => {
826
+ let tokenUri = void 0;
827
+ if (nft.metadata) {
828
+ try {
829
+ if (this.isServerEnvironment) {
830
+ tokenUri = Buffer.from(nft.metadata, "base64").toString(
831
+ "utf-8"
832
+ );
833
+ } else {
834
+ tokenUri = new TextDecoder().decode(
835
+ Uint8Array.from(atob(nft.metadata), (c) => c.charCodeAt(0))
836
+ );
837
+ }
838
+ } catch (e) {
839
+ this.logger.warn(
840
+ `Failed to decode metadata for NFT ${nft.token_id} SN ${nft.serial_number}: ${e.message}`
841
+ );
842
+ }
843
+ }
844
+ return { ...nft, token_uri: tokenUri };
845
+ });
846
+ allNfts = allNfts.concat(nftsWithUri);
847
+ }
848
+ endpoint = response.links?.next || "";
849
+ if (!endpoint) break;
1118
850
  }
1119
- throw error;
851
+ return allNfts;
852
+ } catch (error) {
853
+ this.logger.error(
854
+ `Error fetching NFTs for account ${accountId}: ${error.message}`
855
+ );
856
+ return null;
1120
857
  }
1121
858
  }
1122
- async searchStatus() {
1123
- const raw = await this.requestJson("/search/status", {
1124
- method: "GET"
1125
- });
1126
- return this.parseWithSchema(
1127
- raw,
1128
- searchStatusResponseSchema,
1129
- "search status response"
1130
- );
1131
- }
1132
- async adaptersDetailed() {
1133
- const raw = await this.requestJson("/adapters/details", {
1134
- method: "GET"
1135
- });
1136
- return this.parseWithSchema(
1137
- raw,
1138
- adapterDetailsResponseSchema,
1139
- "adapter details response"
1140
- );
1141
- }
1142
- async websocketStats() {
1143
- const raw = await this.requestJson("/websocket/stats", {
1144
- method: "GET"
1145
- });
1146
- return this.parseWithSchema(
1147
- raw,
1148
- websocketStatsResponseSchema,
1149
- "websocket stats response"
1150
- );
1151
- }
1152
- async metricsSummary() {
1153
- const raw = await this.requestJson("/metrics", {
1154
- method: "GET"
1155
- });
1156
- return this.parseWithSchema(
1157
- raw,
1158
- metricsSummaryResponseSchema,
1159
- "metrics summary response"
1160
- );
1161
- }
1162
- async validateUaid(uaid) {
1163
- const raw = await this.requestJson(
1164
- `/uaids/validate/${encodeURIComponent(uaid)}`,
1165
- {
1166
- method: "GET"
1167
- }
859
+ /**
860
+ * Validates NFT ownership by checking if a specific serial number of a token ID exists for an account.
861
+ * @param accountId The ID of the account.
862
+ * @param tokenId The ID of the NFT's token.
863
+ * @param serialNumber The serial number of the NFT.
864
+ * @returns A promise that resolves to the NftDetail if owned, or null otherwise.
865
+ */
866
+ async validateNFTOwnership(accountId, tokenId, serialNumber) {
867
+ this.logger.info(
868
+ `Validating ownership of NFT ${tokenId} SN ${serialNumber} for account ${accountId}`
1168
869
  );
1169
- return this.parseWithSchema(
1170
- raw,
1171
- uaidValidationResponseSchema,
1172
- "UAID validation response"
1173
- );
1174
- }
1175
- async getUaidConnectionStatus(uaid) {
1176
- const raw = await this.requestJson(
1177
- `/uaids/connections/${encodeURIComponent(uaid)}/status`,
1178
- {
1179
- method: "GET"
870
+ try {
871
+ const nfts = await this.getAccountNfts(accountId, tokenId);
872
+ if (nfts) {
873
+ const foundNft = nfts.find(
874
+ (nft) => nft.token_id === tokenId && nft.serial_number === serialNumber
875
+ );
876
+ return foundNft || null;
1180
877
  }
1181
- );
1182
- return this.parseWithSchema(
1183
- raw,
1184
- uaidConnectionStatusSchema,
1185
- "UAID connection status"
1186
- );
1187
- }
1188
- async closeUaidConnection(uaid) {
1189
- await this.request(`/uaids/connections/${encodeURIComponent(uaid)}`, {
1190
- method: "DELETE"
1191
- });
878
+ return null;
879
+ } catch (error) {
880
+ this.logger.error(`Error validating NFT ownership: ${error.message}`);
881
+ return null;
882
+ }
1192
883
  }
1193
- async dashboardStats() {
1194
- const raw = await this.requestJson("/dashboard/stats", {
1195
- method: "GET"
1196
- });
1197
- return this.parseWithSchema(
1198
- raw,
1199
- dashboardStatsResponseSchema,
1200
- "dashboard stats response"
884
+ /**
885
+ * Performs a read-only query against a smart contract (eth_call like).
886
+ * @param contractIdOrAddress The contract ID (e.g., "0.0.123") or EVM address (e.g., "0x...").
887
+ * @param functionSelector The function selector and encoded parameters (e.g., "0xabcdef12...").
888
+ * @param payerAccountId The account ID of the payer (not strictly payer for read-only, but often required as 'from').
889
+ * @param estimate Whether this is an estimate call. Mirror node might not support this directly in /contracts/call for true estimation.
890
+ * @param block Block parameter, e.g., "latest", "pending", or block number.
891
+ * @param value The value in tinybars to send with the call (for payable view/pure functions, usually 0).
892
+ * @returns A promise that resolves to the contract call query response or null.
893
+ */
894
+ async readSmartContractQuery(contractIdOrAddress, functionSelector, payerAccountId, options) {
895
+ this.logger.info(
896
+ `Reading smart contract ${contractIdOrAddress} with selector ${functionSelector}`
1201
897
  );
1202
- }
1203
- async adapters() {
1204
- const raw = await this.requestJson("/adapters", {
1205
- method: "GET"
898
+ const toAddress = contractIdOrAddress.startsWith("0x") ? contractIdOrAddress : `0x${AccountId.fromString(contractIdOrAddress).toSolidityAddress()}`;
899
+ const fromAddress = payerAccountId.startsWith("0x") ? payerAccountId : `0x${AccountId.fromString(payerAccountId).toSolidityAddress()}`;
900
+ const body = {
901
+ block: options?.block || "latest",
902
+ data: functionSelector,
903
+ estimate: options?.estimate || false,
904
+ from: fromAddress,
905
+ to: toAddress,
906
+ gas: options?.gas,
907
+ gasPrice: options?.gasPrice,
908
+ value: options?.value || 0
909
+ };
910
+ Object.keys(body).forEach((key) => {
911
+ const K = key;
912
+ if (body[K] === void 0) {
913
+ delete body[K];
914
+ }
1206
915
  });
1207
- return this.parseWithSchema(
1208
- raw,
1209
- adaptersResponseSchema,
1210
- "adapters response"
1211
- );
1212
- }
1213
- async facets(adapter) {
1214
- const params = new URLSearchParams();
1215
- if (adapter) {
1216
- params.set("adapter", adapter);
916
+ try {
917
+ const url = this.constructUrl("/api/v1/contracts/call");
918
+ const response = await this._fetchWithRetry(
919
+ url,
920
+ {
921
+ method: "POST",
922
+ body: JSON.stringify(body),
923
+ headers: {
924
+ "Content-Type": "application/json"
925
+ }
926
+ }
927
+ );
928
+ return response;
929
+ } catch (error) {
930
+ this.logger.error(
931
+ `Error reading smart contract ${contractIdOrAddress}: ${error.message}`
932
+ );
933
+ return null;
1217
934
  }
1218
- const suffix = params.size > 0 ? `?${params.toString()}` : "";
1219
- const raw = await this.requestJson(`/search/facets${suffix}`, {
1220
- method: "GET"
1221
- });
1222
- return this.parseWithSchema(
1223
- raw,
1224
- searchFacetsResponseSchema,
1225
- "search facets response"
1226
- );
1227
935
  }
1228
- async createSession(payload, allowHistoryAutoTopUp = true) {
1229
- const body = {};
1230
- if ("uaid" in payload && payload.uaid) {
1231
- body.uaid = payload.uaid;
936
+ /**
937
+ * Retrieves outstanding token airdrops sent by an account.
938
+ * @param accountId The ID of the account that sent the airdrops.
939
+ * @param options Optional parameters for filtering airdrops.
940
+ * @returns A promise that resolves to an array of TokenAirdrop or null.
941
+ */
942
+ async getOutstandingTokenAirdrops(accountId, options) {
943
+ this.logger.info(
944
+ `Getting outstanding token airdrops sent by account ${accountId}`
945
+ );
946
+ let endpoint = `/api/v1/accounts/${accountId}/airdrops/outstanding`;
947
+ const params = new URLSearchParams();
948
+ if (options?.limit) {
949
+ params.append("limit", options.limit.toString());
1232
950
  }
1233
- if ("agentUrl" in payload && payload.agentUrl) {
1234
- body.agentUrl = payload.agentUrl;
951
+ if (options?.order) {
952
+ params.append("order", options.order);
1235
953
  }
1236
- if (payload.auth) {
1237
- body.auth = serialiseAuthConfig(payload.auth);
954
+ if (options?.receiverId) {
955
+ params.append("receiver.id", options.receiverId);
1238
956
  }
1239
- if (payload.historyTtlSeconds !== void 0) {
1240
- body.historyTtlSeconds = payload.historyTtlSeconds;
957
+ if (options?.serialNumber) {
958
+ params.append("serialnumber", options.serialNumber);
1241
959
  }
1242
- if (payload.encryptionRequested !== void 0) {
1243
- body.encryptionRequested = payload.encryptionRequested;
960
+ if (options?.tokenId) {
961
+ params.append("token.id", options.tokenId);
1244
962
  }
1245
- if (payload.senderUaid) {
1246
- body.senderUaid = payload.senderUaid;
963
+ const queryString = params.toString();
964
+ if (queryString) {
965
+ endpoint += `?${queryString}`;
1247
966
  }
1248
967
  try {
1249
- const raw = await this.requestJson("/chat/session", {
1250
- method: "POST",
1251
- body,
1252
- headers: { "content-type": "application/json" }
1253
- });
1254
- return this.parseWithSchema(
1255
- raw,
1256
- createSessionResponseSchema,
1257
- "chat session response"
1258
- );
968
+ const response = await this._requestWithRetry(endpoint);
969
+ return response.airdrops || [];
1259
970
  } catch (error) {
1260
- if (allowHistoryAutoTopUp && this.shouldAutoTopUpHistory(payload, error)) {
1261
- await this.executeHistoryAutoTopUp("chat.session");
1262
- return this.createSession(payload, false);
1263
- }
1264
- throw error;
1265
- }
1266
- }
1267
- async startChat(options) {
1268
- if ("uaid" in options && options.uaid) {
1269
- return this.startConversation({
1270
- uaid: options.uaid,
1271
- senderUaid: options.senderUaid,
1272
- historyTtlSeconds: options.historyTtlSeconds,
1273
- auth: options.auth,
1274
- encryption: options.encryption,
1275
- onSessionCreated: options.onSessionCreated
1276
- });
1277
- }
1278
- if ("agentUrl" in options && options.agentUrl) {
1279
- const session = await this.createSession({
1280
- agentUrl: options.agentUrl,
1281
- auth: options.auth,
1282
- historyTtlSeconds: options.historyTtlSeconds,
1283
- senderUaid: options.senderUaid
1284
- });
1285
- options.onSessionCreated?.(session.sessionId);
1286
- return this.createPlaintextConversationHandle(
1287
- session.sessionId,
1288
- session.encryption ?? null,
1289
- options.auth,
1290
- { agentUrl: options.agentUrl, uaid: options.uaid }
971
+ this.logger.error(
972
+ `Error fetching outstanding token airdrops for account ${accountId}: ${error.message}`
1291
973
  );
974
+ return null;
1292
975
  }
1293
- throw new Error("startChat requires either uaid or agentUrl");
1294
976
  }
1295
- async startConversation(options) {
1296
- const preference = options.encryption?.preference ?? "preferred";
1297
- const requestEncryption = preference !== "disabled";
1298
- if (!requestEncryption) {
1299
- const session = await this.createSession({
1300
- uaid: options.uaid,
1301
- auth: options.auth,
1302
- historyTtlSeconds: options.historyTtlSeconds,
1303
- senderUaid: options.senderUaid,
1304
- encryptionRequested: false
1305
- });
1306
- options.onSessionCreated?.(session.sessionId);
1307
- return this.createPlaintextConversationHandle(
1308
- session.sessionId,
1309
- session.encryption ?? null,
1310
- options.auth,
1311
- { uaid: options.uaid }
1312
- );
977
+ /**
978
+ * Retrieves pending token airdrops received by an account.
979
+ * @param accountId The ID of the account that received the airdrops.
980
+ * @param options Optional parameters for filtering airdrops.
981
+ * @returns A promise that resolves to an array of TokenAirdrop or null.
982
+ */
983
+ async getPendingTokenAirdrops(accountId, options) {
984
+ this.logger.info(
985
+ `Getting pending token airdrops received by account ${accountId}`
986
+ );
987
+ let endpoint = `/api/v1/accounts/${accountId}/airdrops/pending`;
988
+ const params = new URLSearchParams();
989
+ if (options?.limit) {
990
+ params.append("limit", options.limit.toString());
991
+ }
992
+ if (options?.order) {
993
+ params.append("order", options.order);
994
+ }
995
+ if (options?.senderId) {
996
+ params.append("sender.id", options.senderId);
997
+ }
998
+ if (options?.serialNumber) {
999
+ params.append("serialnumber", options.serialNumber);
1000
+ }
1001
+ if (options?.tokenId) {
1002
+ params.append("token.id", options.tokenId);
1003
+ }
1004
+ const queryString = params.toString();
1005
+ if (queryString) {
1006
+ endpoint += `?${queryString}`;
1313
1007
  }
1314
1008
  try {
1315
- const handle = await this.encryptedChatManager.startSession({
1316
- uaid: options.uaid,
1317
- senderUaid: options.senderUaid,
1318
- historyTtlSeconds: options.historyTtlSeconds,
1319
- handshakeTimeoutMs: options.encryption?.handshakeTimeoutMs,
1320
- pollIntervalMs: options.encryption?.pollIntervalMs,
1321
- onSessionCreated: (sessionId) => {
1322
- options.onSessionCreated?.(sessionId);
1323
- },
1324
- auth: options.auth
1325
- });
1326
- return handle;
1009
+ const response = await this._requestWithRetry(endpoint);
1010
+ return response.airdrops || [];
1327
1011
  } catch (error) {
1328
- if (error instanceof EncryptionUnavailableError) {
1329
- if (preference === "required") {
1330
- throw error;
1331
- }
1332
- return this.createPlaintextConversationHandle(
1333
- error.sessionId,
1334
- error.summary ?? null,
1335
- options.auth,
1336
- { uaid: options.uaid }
1337
- );
1338
- }
1339
- throw error;
1012
+ this.logger.error(
1013
+ `Error fetching pending token airdrops for account ${accountId}: ${error.message}`
1014
+ );
1015
+ return null;
1340
1016
  }
1341
1017
  }
1342
- async acceptConversation(options) {
1343
- const preference = options.encryption?.preference ?? "preferred";
1344
- if (preference === "disabled") {
1345
- return this.createPlaintextConversationHandle(options.sessionId, null);
1018
+ /**
1019
+ * Retrieves blocks from the network.
1020
+ * @param options Optional parameters for filtering blocks.
1021
+ * @returns A promise that resolves to an array of Block or null.
1022
+ */
1023
+ async getBlocks(options) {
1024
+ this.logger.info("Getting blocks from the network");
1025
+ let endpoint = `/api/v1/blocks`;
1026
+ const params = new URLSearchParams();
1027
+ if (options?.limit) {
1028
+ params.append("limit", options.limit.toString());
1029
+ }
1030
+ if (options?.order) {
1031
+ params.append("order", options.order);
1032
+ }
1033
+ if (options?.timestamp) {
1034
+ params.append("timestamp", options.timestamp);
1035
+ }
1036
+ if (options?.blockNumber) {
1037
+ params.append("block.number", options.blockNumber);
1038
+ }
1039
+ const queryString = params.toString();
1040
+ if (queryString) {
1041
+ endpoint += `?${queryString}`;
1346
1042
  }
1347
1043
  try {
1348
- const handle = await this.encryptedChatManager.acceptSession({
1349
- sessionId: options.sessionId,
1350
- responderUaid: options.responderUaid,
1351
- handshakeTimeoutMs: options.encryption?.handshakeTimeoutMs,
1352
- pollIntervalMs: options.encryption?.pollIntervalMs
1353
- });
1354
- return handle;
1044
+ const response = await this._requestWithRetry(endpoint);
1045
+ return response.blocks || [];
1355
1046
  } catch (error) {
1356
- if (error instanceof EncryptionUnavailableError && preference !== "required") {
1357
- return this.createPlaintextConversationHandle(
1358
- options.sessionId,
1359
- null,
1360
- void 0,
1361
- { uaid: options.responderUaid }
1362
- );
1363
- }
1364
- throw error;
1047
+ this.logger.error(`Error fetching blocks: ${error.message}`);
1048
+ return null;
1365
1049
  }
1366
1050
  }
1367
- async fetchHistorySnapshot(sessionId, options) {
1368
- if (!sessionId || sessionId.trim().length === 0) {
1369
- throw new Error("sessionId is required to fetch chat history");
1370
- }
1371
- const raw = await this.requestJson(
1372
- `/chat/session/${encodeURIComponent(sessionId)}/history`,
1373
- {
1374
- method: "GET"
1375
- }
1376
- );
1377
- const snapshot = this.parseWithSchema(
1378
- raw,
1379
- chatHistorySnapshotResponseSchema,
1380
- "chat history snapshot response"
1381
- );
1382
- return this.attachDecryptedHistory(sessionId, snapshot, options);
1383
- }
1384
- attachDecryptedHistory(sessionId, snapshot, options) {
1385
- const shouldDecrypt = options?.decrypt !== void 0 ? options.decrypt : this.encryptionOptions?.autoDecryptHistory === true;
1386
- if (!shouldDecrypt) {
1387
- return snapshot;
1388
- }
1389
- const context = this.resolveDecryptionContext(sessionId, options);
1390
- if (!context) {
1391
- throw new Error(
1392
- "Unable to decrypt chat history: encryption context unavailable"
1051
+ /**
1052
+ * Retrieves a specific block by number or hash.
1053
+ * @param blockNumberOrHash The block number or hash.
1054
+ * @returns A promise that resolves to a Block or null.
1055
+ */
1056
+ async getBlock(blockNumberOrHash) {
1057
+ this.logger.info(`Getting block ${blockNumberOrHash}`);
1058
+ try {
1059
+ const response = await this._requestWithRetry(
1060
+ `/api/v1/blocks/${blockNumberOrHash}`
1061
+ );
1062
+ return response;
1063
+ } catch (error) {
1064
+ this.logger.error(
1065
+ `Error fetching block ${blockNumberOrHash}: ${error.message}`
1393
1066
  );
1067
+ return null;
1394
1068
  }
1395
- const decryptedHistory = snapshot.history.map((entry) => ({
1396
- entry,
1397
- plaintext: this.decryptHistoryEntryFromContext(sessionId, entry, context)
1398
- }));
1399
- return { ...snapshot, decryptedHistory };
1400
1069
  }
1401
- registerConversationContext(context) {
1402
- const normalized = {
1403
- sessionId: context.sessionId,
1404
- sharedSecret: Buffer.from(context.sharedSecret),
1405
- identity: context.identity ? { ...context.identity } : void 0
1406
- };
1407
- const entries = this.conversationContexts.get(context.sessionId) ?? [];
1408
- const existingIndex = entries.findIndex(
1409
- (existing) => this.identitiesMatch(existing.identity, normalized.identity)
1410
- );
1411
- if (existingIndex >= 0) {
1412
- entries[existingIndex] = normalized;
1413
- } else {
1414
- entries.push(normalized);
1070
+ /**
1071
+ * Retrieves contract entities from the network.
1072
+ * @param options Optional parameters for filtering contracts.
1073
+ * @returns A promise that resolves to an array of ContractEntity or null.
1074
+ */
1075
+ async getContracts(options) {
1076
+ this.logger.info("Getting contracts from the network");
1077
+ let url = `/api/v1/contracts`;
1078
+ const params = new URLSearchParams();
1079
+ if (options?.contractId) {
1080
+ params.append("contract.id", options.contractId);
1415
1081
  }
1416
- this.conversationContexts.set(context.sessionId, entries);
1417
- }
1418
- // Exposed for EncryptedChatManager to persist decryption context
1419
- registerConversationContextForEncryption(context) {
1420
- this.registerConversationContext(context);
1421
- }
1422
- resolveDecryptionContext(sessionId, options) {
1423
- if (options?.sharedSecret) {
1424
- return {
1425
- sessionId,
1426
- sharedSecret: this.normalizeSharedSecret(options.sharedSecret),
1427
- identity: options.identity
1428
- };
1082
+ if (options?.limit) {
1083
+ params.append("limit", options.limit.toString());
1429
1084
  }
1430
- const contexts = this.conversationContexts.get(sessionId);
1431
- if (!contexts || contexts.length === 0) {
1432
- return null;
1085
+ if (options?.order) {
1086
+ params.append("order", options.order);
1433
1087
  }
1434
- if (options?.identity) {
1435
- const match = contexts.find(
1436
- (context) => this.identitiesMatch(context.identity, options.identity)
1437
- );
1438
- if (match) {
1439
- return match;
1440
- }
1088
+ const queryString = params.toString();
1089
+ if (queryString) {
1090
+ url += `?${queryString}`;
1091
+ }
1092
+ try {
1093
+ const response = await this._requestWithRetry(url);
1094
+ return response.contracts || [];
1095
+ } catch (error) {
1096
+ this.logger.error(`Error fetching contracts: ${error.message}`);
1097
+ return null;
1441
1098
  }
1442
- return contexts[0];
1443
1099
  }
1444
- decryptHistoryEntryFromContext(sessionId, entry, context) {
1445
- const envelope = entry.cipherEnvelope;
1446
- if (!envelope) {
1447
- return entry.content;
1100
+ /**
1101
+ * Retrieves a specific contract by ID or address.
1102
+ * @param contractIdOrAddress The contract ID or EVM address.
1103
+ * @param timestamp Optional timestamp for historical data.
1104
+ * @returns A promise that resolves to a ContractEntity or null.
1105
+ */
1106
+ async getContract(contractIdOrAddress, timestamp) {
1107
+ this.logger.info(`Getting contract ${contractIdOrAddress}`);
1108
+ let url = `/api/v1/contracts/${contractIdOrAddress}`;
1109
+ if (timestamp) {
1110
+ url += `?timestamp=${timestamp}`;
1448
1111
  }
1449
- const secret = Buffer.from(context.sharedSecret);
1450
1112
  try {
1451
- return this.encryption.decryptCipherEnvelope({
1452
- envelope,
1453
- sharedSecret: secret
1454
- });
1455
- } catch (_error) {
1113
+ const response = await this._requestWithRetry(url);
1114
+ return response;
1115
+ } catch (error) {
1116
+ this.logger.error(
1117
+ `Error fetching contract ${contractIdOrAddress}: ${error.message}`
1118
+ );
1456
1119
  return null;
1457
1120
  }
1458
1121
  }
1459
- identitiesMatch(a, b) {
1460
- if (!a && !b) {
1461
- return true;
1122
+ /**
1123
+ * Retrieves contract results from the network.
1124
+ * @param options Optional parameters for filtering contract results.
1125
+ * @returns A promise that resolves to an array of ContractResult or null.
1126
+ */
1127
+ async getContractResults(options) {
1128
+ this.logger.info("Getting contract results from the network");
1129
+ let url = `/api/v1/contracts/results`;
1130
+ const params = new URLSearchParams();
1131
+ if (options?.from) {
1132
+ params.append("from", options.from);
1462
1133
  }
1463
- if (!a || !b) {
1464
- return false;
1134
+ if (options?.blockHash) {
1135
+ params.append("block.hash", options.blockHash);
1465
1136
  }
1466
- if (a.uaid && b.uaid && a.uaid.toLowerCase() === b.uaid.toLowerCase()) {
1467
- return true;
1137
+ if (options?.blockNumber) {
1138
+ params.append("block.number", options.blockNumber);
1468
1139
  }
1469
- if (a.ledgerAccountId && b.ledgerAccountId && a.ledgerAccountId.toLowerCase() === b.ledgerAccountId.toLowerCase()) {
1470
- return true;
1140
+ if (options?.internal !== void 0) {
1141
+ params.append("internal", options.internal.toString());
1471
1142
  }
1472
- if (a.userId && b.userId && a.userId === b.userId) {
1473
- return true;
1143
+ if (options?.limit) {
1144
+ params.append("limit", options.limit.toString());
1474
1145
  }
1475
- if (a.email && b.email && a.email.toLowerCase() === b.email.toLowerCase()) {
1476
- return true;
1146
+ if (options?.order) {
1147
+ params.append("order", options.order);
1477
1148
  }
1478
- return false;
1479
- }
1480
- identityMatchesRecipient(recipient, identity) {
1481
- if (identity.uaid && recipient.uaid?.toLowerCase() === identity.uaid.toLowerCase()) {
1482
- return true;
1149
+ if (options?.timestamp) {
1150
+ params.append("timestamp", options.timestamp);
1483
1151
  }
1484
- if (identity.ledgerAccountId && recipient.ledgerAccountId?.toLowerCase() === identity.ledgerAccountId.toLowerCase()) {
1485
- return true;
1152
+ if (options?.transactionIndex) {
1153
+ params.append("transaction.index", options.transactionIndex.toString());
1486
1154
  }
1487
- if (identity.userId && recipient.userId === identity.userId) {
1488
- return true;
1155
+ const queryString = params.toString();
1156
+ if (queryString) {
1157
+ url += `?${queryString}`;
1489
1158
  }
1490
- if (identity.email && recipient.email?.toLowerCase() === identity.email.toLowerCase()) {
1491
- return true;
1159
+ try {
1160
+ const response = await this._requestWithRetry(url);
1161
+ return response.results || [];
1162
+ } catch (error) {
1163
+ this.logger.error(`Error fetching contract results: ${error.message}`);
1164
+ return null;
1492
1165
  }
1493
- return false;
1494
- }
1495
- createPlaintextConversationHandle(sessionId, summary, defaultAuth, context) {
1496
- const uaid = context?.uaid?.trim();
1497
- const agentUrl = context?.agentUrl?.trim();
1498
- return {
1499
- sessionId,
1500
- mode: "plaintext",
1501
- summary: summary ?? null,
1502
- send: async (options) => {
1503
- const plaintext = options.plaintext;
1504
- if (!plaintext || plaintext.trim().length === 0) {
1505
- throw new Error("plaintext is required for chat messages");
1506
- }
1507
- const message = options.message ?? plaintext;
1508
- return this.sendMessage({
1509
- sessionId,
1510
- message,
1511
- streaming: options.streaming,
1512
- auth: options.auth ?? defaultAuth,
1513
- uaid,
1514
- agentUrl
1515
- });
1516
- },
1517
- decryptHistoryEntry: (entry) => entry.content
1518
- };
1519
- }
1520
- async compactHistory(payload) {
1521
- if (!payload.sessionId || payload.sessionId.trim().length === 0) {
1522
- throw new Error("sessionId is required to compact chat history");
1523
- }
1524
- const body = {};
1525
- if (typeof payload.preserveEntries === "number" && Number.isFinite(payload.preserveEntries) && payload.preserveEntries >= 0) {
1526
- body.preserveEntries = Math.floor(payload.preserveEntries);
1527
- }
1528
- const raw = await this.requestJson(
1529
- `/chat/session/${encodeURIComponent(payload.sessionId)}/compact`,
1530
- {
1531
- method: "POST",
1532
- headers: { "content-type": "application/json" },
1533
- body
1534
- }
1535
- );
1536
- return this.parseWithSchema(
1537
- raw,
1538
- chatHistoryCompactionResponseSchema,
1539
- "chat history compaction response"
1540
- );
1541
- }
1542
- async fetchEncryptionStatus(sessionId) {
1543
- if (!sessionId || sessionId.trim().length === 0) {
1544
- throw new Error("sessionId is required for encryption status");
1545
- }
1546
- const raw = await this.requestJson(
1547
- `/chat/session/${encodeURIComponent(sessionId)}/encryption`,
1548
- {
1549
- method: "GET"
1550
- }
1551
- );
1552
- return this.parseWithSchema(
1553
- raw,
1554
- sessionEncryptionStatusResponseSchema,
1555
- "session encryption status response"
1556
- );
1557
1166
  }
1558
- async postEncryptionHandshake(sessionId, payload) {
1559
- if (!sessionId || sessionId.trim().length === 0) {
1560
- throw new Error("sessionId is required for encryption handshake");
1561
- }
1562
- const raw = await this.requestJson(
1563
- `/chat/session/${encodeURIComponent(sessionId)}/encryption-handshake`,
1564
- {
1565
- method: "POST",
1566
- headers: { "content-type": "application/json" },
1567
- body: {
1568
- role: payload.role,
1569
- keyType: payload.keyType,
1570
- ephemeralPublicKey: payload.ephemeralPublicKey,
1571
- longTermPublicKey: payload.longTermPublicKey,
1572
- signature: payload.signature,
1573
- uaid: payload.uaid,
1574
- userId: payload.userId,
1575
- ledgerAccountId: payload.ledgerAccountId,
1576
- metadata: payload.metadata
1577
- }
1578
- }
1579
- );
1580
- const response = this.parseWithSchema(
1581
- raw,
1582
- encryptionHandshakeResponseSchema,
1583
- "encryption handshake response"
1584
- );
1585
- return response.handshake;
1167
+ /**
1168
+ * Retrieves a specific contract result by transaction ID or hash.
1169
+ * @param transactionIdOrHash The transaction ID or hash.
1170
+ * @param nonce Optional nonce filter.
1171
+ * @returns A promise that resolves to a ContractResult or null.
1172
+ */
1173
+ async getContractResult(transactionIdOrHash, nonce) {
1174
+ this.logger.info(`Getting contract result for ${transactionIdOrHash}`);
1175
+ let url = `/api/v1/contracts/results/${transactionIdOrHash}`;
1176
+ if (nonce !== void 0) {
1177
+ url += `?nonce=${nonce}`;
1178
+ }
1179
+ try {
1180
+ const response = await this._requestWithRetry(url);
1181
+ return response;
1182
+ } catch (error) {
1183
+ this.logger.error(
1184
+ `Error fetching contract result for ${transactionIdOrHash}: ${error.message}`
1185
+ );
1186
+ return null;
1187
+ }
1586
1188
  }
1587
- async registerEncryptionKey(payload) {
1588
- const raw = await this.requestJson("/encryption/keys", {
1589
- method: "POST",
1590
- headers: { "content-type": "application/json" },
1591
- body: payload
1592
- });
1593
- return this.parseWithSchema(
1594
- raw,
1595
- registerEncryptionKeyResponseSchema,
1596
- "register encryption key response"
1189
+ /**
1190
+ * Retrieves contract results for a specific contract.
1191
+ * @param contractIdOrAddress The contract ID or EVM address.
1192
+ * @param options Optional parameters for filtering.
1193
+ * @returns A promise that resolves to an array of ContractResult or null.
1194
+ */
1195
+ async getContractResultsByContract(contractIdOrAddress, options) {
1196
+ this.logger.info(
1197
+ `Getting contract results for contract ${contractIdOrAddress}`
1597
1198
  );
1598
- }
1599
- async sendMessage(payload) {
1600
- const body = {
1601
- message: payload.message
1602
- };
1603
- if (payload.streaming !== void 0) {
1604
- body.streaming = payload.streaming;
1199
+ let url = `/api/v1/contracts/${contractIdOrAddress}/results`;
1200
+ const params = new URLSearchParams();
1201
+ if (options?.blockHash) {
1202
+ params.append("block.hash", options.blockHash);
1605
1203
  }
1606
- if (payload.auth) {
1607
- body.auth = serialiseAuthConfig(payload.auth);
1204
+ if (options?.blockNumber) {
1205
+ params.append("block.number", options.blockNumber);
1608
1206
  }
1609
- if ("uaid" in payload) {
1610
- body.uaid = payload.uaid;
1207
+ if (options?.from) {
1208
+ params.append("from", options.from);
1611
1209
  }
1612
- if ("sessionId" in payload && payload.sessionId) {
1613
- body.sessionId = payload.sessionId;
1210
+ if (options?.internal !== void 0) {
1211
+ params.append("internal", options.internal.toString());
1614
1212
  }
1615
- if ("agentUrl" in payload && payload.agentUrl) {
1616
- body.agentUrl = payload.agentUrl;
1213
+ if (options?.limit) {
1214
+ params.append("limit", options.limit.toString());
1617
1215
  }
1618
- let cipherEnvelope = payload.cipherEnvelope ?? null;
1619
- if (payload.encryption) {
1620
- const sessionIdForEncryption = payload.encryption.sessionId ?? (typeof body.sessionId === "string" ? body.sessionId : void 0);
1621
- if (!sessionIdForEncryption) {
1622
- throw new Error(
1623
- "sessionId is required when using encrypted chat payloads"
1624
- );
1625
- }
1626
- if (!payload.encryption.recipients?.length) {
1627
- throw new Error("recipients are required for encrypted chat payloads");
1628
- }
1629
- cipherEnvelope = this.encryption.encryptCipherEnvelope({
1630
- ...payload.encryption,
1631
- sessionId: sessionIdForEncryption
1632
- });
1633
- }
1634
- if (cipherEnvelope) {
1635
- body.cipherEnvelope = cipherEnvelope;
1636
- }
1637
- delete body.encryption;
1638
- const raw = await this.requestJson("/chat/message", {
1639
- method: "POST",
1640
- body,
1641
- headers: { "content-type": "application/json" }
1642
- });
1643
- return this.parseWithSchema(
1644
- raw,
1645
- sendMessageResponseSchema,
1646
- "chat message response"
1647
- );
1648
- }
1649
- async endSession(sessionId) {
1650
- await this.request(`/chat/session/${encodeURIComponent(sessionId)}`, {
1651
- method: "DELETE"
1652
- });
1653
- }
1654
- async generateEncryptionKeyPair(options = {}) {
1655
- this.assertNodeRuntime("generateEncryptionKeyPair");
1656
- const keyType = options.keyType ?? "secp256k1";
1657
- if (keyType !== "secp256k1") {
1658
- throw new Error("Only secp256k1 key generation is supported currently");
1659
- }
1660
- const privateKeyBytes = randomBytes(32);
1661
- const privateKey = Buffer.from(privateKeyBytes).toString("hex");
1662
- const publicKeyBytes = secp256k1.getPublicKey(privateKeyBytes, true);
1663
- const publicKey = Buffer.from(publicKeyBytes).toString("hex");
1664
- const envVar = options.envVar ?? "RB_ENCRYPTION_PRIVATE_KEY";
1665
- const resolvedPath = options.envPath ? path.resolve(options.envPath) : void 0;
1666
- if (resolvedPath) {
1667
- const fsModule = getFs();
1668
- if (!fsModule) {
1669
- throw new Error(
1670
- "File system module is not available; cannot write encryption key env file"
1671
- );
1672
- }
1673
- const envLine = `${envVar}=${privateKey}`;
1674
- if (fsModule.existsSync(resolvedPath)) {
1675
- const content = fsModule.readFileSync(resolvedPath, "utf-8");
1676
- const lineRegex = new RegExp(`^${envVar}=.*$`, "m");
1677
- if (lineRegex.test(content)) {
1678
- if (!options.overwrite) {
1679
- throw new Error(
1680
- `${envVar} already exists in ${resolvedPath}; set overwrite=true to replace it`
1681
- );
1682
- }
1683
- const updated = content.replace(lineRegex, envLine);
1684
- fsModule.writeFileSync(resolvedPath, updated);
1685
- } else {
1686
- const needsNewline = !content.endsWith("\n");
1687
- fsModule.appendFileSync(
1688
- resolvedPath,
1689
- `${needsNewline ? "\n" : ""}${envLine}
1690
- `
1691
- );
1692
- }
1693
- } else {
1694
- fsModule.writeFileSync(resolvedPath, `${envLine}
1695
- `);
1696
- }
1216
+ if (options?.order) {
1217
+ params.append("order", options.order);
1218
+ }
1219
+ if (options?.timestamp) {
1220
+ params.append("timestamp", options.timestamp);
1221
+ }
1222
+ if (options?.transactionIndex) {
1223
+ params.append("transaction.index", options.transactionIndex.toString());
1224
+ }
1225
+ const queryString = params.toString();
1226
+ if (queryString) {
1227
+ url += `?${queryString}`;
1228
+ }
1229
+ try {
1230
+ const response = await this._requestWithRetry(url);
1231
+ return response.results || [];
1232
+ } catch (error) {
1233
+ this.logger.error(
1234
+ `Error fetching contract results for ${contractIdOrAddress}: ${error.message}`
1235
+ );
1236
+ return null;
1697
1237
  }
1698
- return {
1699
- privateKey,
1700
- publicKey,
1701
- envPath: resolvedPath,
1702
- envVar
1703
- };
1704
- }
1705
- buildUrl(path2) {
1706
- const normalisedPath = path2.startsWith("/") ? path2 : `/${path2}`;
1707
- return `${this.baseUrl}${normalisedPath}`;
1708
1238
  }
1709
- buildVectorFallbackSearchParams(request) {
1710
- const params = {
1711
- q: request.query
1712
- };
1713
- let effectiveLimit;
1714
- if (typeof request.limit === "number" && Number.isFinite(request.limit)) {
1715
- effectiveLimit = request.limit;
1716
- params.limit = request.limit;
1239
+ /**
1240
+ * Retrieves contract state for a specific contract.
1241
+ * @param contractIdOrAddress The contract ID or EVM address.
1242
+ * @param options Optional parameters for filtering.
1243
+ * @returns A promise that resolves to an array of ContractState or null.
1244
+ */
1245
+ async getContractState(contractIdOrAddress, options) {
1246
+ this.logger.info(`Getting contract state for ${contractIdOrAddress}`);
1247
+ let url = `/api/v1/contracts/${contractIdOrAddress}/state`;
1248
+ const params = new URLSearchParams();
1249
+ if (options?.limit) {
1250
+ params.append("limit", options.limit.toString());
1717
1251
  }
1718
- if (typeof request.offset === "number" && Number.isFinite(request.offset) && request.offset > 0) {
1719
- const limit = effectiveLimit && effectiveLimit > 0 ? effectiveLimit : 20;
1720
- params.limit = limit;
1721
- params.page = Math.floor(request.offset / limit) + 1;
1252
+ if (options?.order) {
1253
+ params.append("order", options.order);
1722
1254
  }
1723
- if (request.filter?.registry) {
1724
- params.registry = request.filter.registry;
1255
+ if (options?.slot) {
1256
+ params.append("slot", options.slot);
1725
1257
  }
1726
- if (request.filter?.protocols?.length) {
1727
- params.protocols = [...request.filter.protocols];
1258
+ if (options?.timestamp) {
1259
+ params.append("timestamp", options.timestamp);
1728
1260
  }
1729
- if (request.filter?.adapter?.length) {
1730
- params.adapters = [...request.filter.adapter];
1261
+ const queryString = params.toString();
1262
+ if (queryString) {
1263
+ url += `?${queryString}`;
1731
1264
  }
1732
- if (request.filter?.capabilities?.length) {
1733
- params.capabilities = request.filter.capabilities.map(
1734
- (value) => typeof value === "number" ? value.toString(10) : value
1265
+ try {
1266
+ const response = await this._requestWithRetry(url);
1267
+ return response.state || [];
1268
+ } catch (error) {
1269
+ this.logger.error(
1270
+ `Error fetching contract state for ${contractIdOrAddress}: ${error.message}`
1735
1271
  );
1272
+ return null;
1736
1273
  }
1737
- if (request.filter?.type) {
1738
- params.type = request.filter.type;
1739
- }
1740
- return params;
1741
- }
1742
- convertSearchResultToVectorResponse(result) {
1743
- const hits = result.hits.map((agent) => ({
1744
- agent,
1745
- score: 0,
1746
- highlights: {}
1747
- }));
1748
- const total = result.total;
1749
- const limit = result.limit;
1750
- const page = result.page;
1751
- const totalVisible = page * limit;
1752
- const limited = total > totalVisible || page > 1;
1753
- return {
1754
- hits,
1755
- total,
1756
- took: 0,
1757
- totalAvailable: total,
1758
- visible: hits.length,
1759
- limited,
1760
- credits_used: 0
1761
- };
1762
1274
  }
1763
- async delay(ms, signal) {
1764
- if (ms <= 0) {
1765
- if (signal?.aborted) {
1766
- throw createAbortError();
1767
- }
1768
- return;
1275
+ /**
1276
+ * Retrieves contract actions for a specific transaction.
1277
+ * @param transactionIdOrHash The transaction ID or hash.
1278
+ * @param options Optional parameters for filtering.
1279
+ * @returns A promise that resolves to an array of ContractAction or null.
1280
+ */
1281
+ async getContractActions(transactionIdOrHash, options) {
1282
+ this.logger.info(`Getting contract actions for ${transactionIdOrHash}`);
1283
+ let url = `/api/v1/contracts/results/${transactionIdOrHash}/actions`;
1284
+ const params = new URLSearchParams();
1285
+ if (options?.index) {
1286
+ params.append("index", options.index);
1769
1287
  }
1770
- await new Promise((resolve, reject) => {
1771
- const timer = setTimeout(() => {
1772
- if (signal) {
1773
- signal.removeEventListener("abort", onAbort);
1774
- }
1775
- resolve();
1776
- }, ms);
1777
- const onAbort = () => {
1778
- clearTimeout(timer);
1779
- signal?.removeEventListener("abort", onAbort);
1780
- reject(createAbortError());
1781
- };
1782
- if (signal) {
1783
- if (signal.aborted) {
1784
- clearTimeout(timer);
1785
- reject(createAbortError());
1786
- return;
1787
- }
1788
- signal.addEventListener("abort", onAbort, { once: true });
1789
- }
1790
- });
1791
- }
1792
- async requestJson(path2, config) {
1793
- const response = await this.request(path2, config);
1794
- const contentType = response.headers?.get("content-type") ?? "";
1795
- if (!JSON_CONTENT_TYPE.test(contentType)) {
1796
- const body = await response.text();
1797
- throw new RegistryBrokerParseError(
1798
- "Expected JSON response from registry broker",
1799
- body
1288
+ if (options?.limit) {
1289
+ params.append("limit", options.limit.toString());
1290
+ }
1291
+ if (options?.order) {
1292
+ params.append("order", options.order);
1293
+ }
1294
+ const queryString = params.toString();
1295
+ if (queryString) {
1296
+ url += `?${queryString}`;
1297
+ }
1298
+ try {
1299
+ const response = await this._requestWithRetry(url);
1300
+ return response.actions || [];
1301
+ } catch (error) {
1302
+ this.logger.error(
1303
+ `Error fetching contract actions for ${transactionIdOrHash}: ${error.message}`
1800
1304
  );
1305
+ return null;
1801
1306
  }
1802
- return await response.json();
1803
1307
  }
1804
- async extractErrorBody(response) {
1805
- const contentType = response.headers?.get("content-type") ?? "";
1806
- if (JSON_CONTENT_TYPE.test(contentType)) {
1807
- try {
1808
- return await response.json();
1809
- } catch (error) {
1810
- return { parseError: String(error) };
1811
- }
1308
+ /**
1309
+ * Retrieves contract logs from the network.
1310
+ * @param options Optional parameters for filtering logs.
1311
+ * @returns A promise that resolves to an array of ContractLog or null.
1312
+ */
1313
+ async getContractLogs(options) {
1314
+ this.logger.info("Getting contract logs from the network");
1315
+ let url = `/api/v1/contracts/results/logs`;
1316
+ const params = new URLSearchParams();
1317
+ if (options?.index) {
1318
+ params.append("index", options.index);
1319
+ }
1320
+ if (options?.limit) {
1321
+ params.append("limit", options.limit.toString());
1322
+ }
1323
+ if (options?.order) {
1324
+ params.append("order", options.order);
1325
+ }
1326
+ if (options?.timestamp) {
1327
+ params.append("timestamp", options.timestamp);
1328
+ }
1329
+ if (options?.topic0) {
1330
+ params.append("topic0", options.topic0);
1331
+ }
1332
+ if (options?.topic1) {
1333
+ params.append("topic1", options.topic1);
1334
+ }
1335
+ if (options?.topic2) {
1336
+ params.append("topic2", options.topic2);
1337
+ }
1338
+ if (options?.topic3) {
1339
+ params.append("topic3", options.topic3);
1340
+ }
1341
+ if (options?.transactionHash) {
1342
+ params.append("transaction.hash", options.transactionHash);
1343
+ }
1344
+ const queryString = params.toString();
1345
+ if (queryString) {
1346
+ url += `?${queryString}`;
1812
1347
  }
1813
1348
  try {
1814
- return await response.text();
1349
+ const response = await this._requestWithRetry(url);
1350
+ return response.logs || [];
1815
1351
  } catch (error) {
1816
- return { parseError: String(error) };
1352
+ this.logger.error(`Error fetching contract logs: ${error.message}`);
1353
+ return null;
1817
1354
  }
1818
1355
  }
1819
- parseWithSchema(value, schema, context) {
1356
+ /**
1357
+ * Retrieves contract logs for a specific contract.
1358
+ * @param contractIdOrAddress The contract ID or EVM address.
1359
+ * @param options Optional parameters for filtering logs.
1360
+ * @returns A promise that resolves to an array of ContractLog or null.
1361
+ */
1362
+ async getContractLogsByContract(contractIdOrAddress, options) {
1363
+ this.logger.info(
1364
+ `Getting contract logs for contract ${contractIdOrAddress}`
1365
+ );
1366
+ let url = `/api/v1/contracts/${contractIdOrAddress}/results/logs`;
1367
+ const params = new URLSearchParams();
1368
+ if (options?.index) {
1369
+ params.append("index", options.index);
1370
+ }
1371
+ if (options?.limit) {
1372
+ params.append("limit", options.limit.toString());
1373
+ }
1374
+ if (options?.order) {
1375
+ params.append("order", options.order);
1376
+ }
1377
+ if (options?.timestamp) {
1378
+ params.append("timestamp", options.timestamp);
1379
+ }
1380
+ if (options?.topic0) {
1381
+ params.append("topic0", options.topic0);
1382
+ }
1383
+ if (options?.topic1) {
1384
+ params.append("topic1", options.topic1);
1385
+ }
1386
+ if (options?.topic2) {
1387
+ params.append("topic2", options.topic2);
1388
+ }
1389
+ if (options?.topic3) {
1390
+ params.append("topic3", options.topic3);
1391
+ }
1392
+ const queryString = params.toString();
1393
+ if (queryString) {
1394
+ url += `?${queryString}`;
1395
+ }
1820
1396
  try {
1821
- return schema.parse(value);
1397
+ const response = await this._requestWithRetry(url);
1398
+ return response.logs || [];
1822
1399
  } catch (error) {
1823
- throw new RegistryBrokerParseError(
1824
- `Failed to parse ${context}`,
1825
- error instanceof ZodError || error instanceof Error ? error : String(error),
1826
- value
1400
+ this.logger.error(
1401
+ `Error fetching contract logs for ${contractIdOrAddress}: ${error.message}`
1827
1402
  );
1403
+ return null;
1828
1404
  }
1829
1405
  }
1830
- assertNodeRuntime(feature) {
1831
- if (typeof process === "undefined" || !process.versions?.node) {
1832
- throw new Error(`${feature} is only available in Node.js environments`);
1406
+ /**
1407
+ * Retrieves NFT information by token ID and serial number.
1408
+ * @param tokenId The token ID.
1409
+ * @param serialNumber The serial number of the NFT.
1410
+ * @returns A promise that resolves to an NftInfo or null.
1411
+ */
1412
+ async getNftInfo(tokenId, serialNumber) {
1413
+ this.logger.info(`Getting NFT info for ${tokenId}/${serialNumber}`);
1414
+ const url = `/api/v1/tokens/${tokenId}/nfts/${serialNumber}`;
1415
+ try {
1416
+ const response = await this._requestWithRetry(url);
1417
+ return response;
1418
+ } catch (error) {
1419
+ this.logger.error(
1420
+ `Error fetching NFT info for ${tokenId}/${serialNumber}: ${error.message}`
1421
+ );
1422
+ return null;
1833
1423
  }
1834
1424
  }
1835
- createEphemeralKeyPair() {
1836
- this.assertNodeRuntime("generateEphemeralKeyPair");
1837
- const privateKeyBytes = randomBytes(32);
1838
- const publicKey = secp256k1.getPublicKey(privateKeyBytes, true);
1839
- return {
1840
- privateKey: Buffer.from(privateKeyBytes).toString("hex"),
1841
- publicKey: Buffer.from(publicKey).toString("hex")
1842
- };
1843
- }
1844
- deriveSharedSecret(options) {
1845
- this.assertNodeRuntime("deriveSharedSecret");
1846
- const privateKey = this.hexToBuffer(options.privateKey);
1847
- const peerPublicKey = this.hexToBuffer(options.peerPublicKey);
1848
- const shared = secp256k1.getSharedSecret(privateKey, peerPublicKey, true);
1849
- return createHash("sha256").update(Buffer.from(shared)).digest();
1850
- }
1851
- buildCipherEnvelope(options) {
1852
- this.assertNodeRuntime("encryptCipherEnvelope");
1853
- const sharedSecret = this.normalizeSharedSecret(options.sharedSecret);
1854
- const iv = randomBytes(12);
1855
- const cipher = createCipheriv("aes-256-gcm", sharedSecret, iv);
1856
- const aadSource = options.associatedData ?? options.sessionId;
1857
- const associatedDataEncoded = aadSource ? Buffer.from(aadSource, "utf8").toString("base64") : void 0;
1858
- if (aadSource) {
1859
- cipher.setAAD(Buffer.from(aadSource, "utf8"));
1860
- }
1861
- const ciphertext = Buffer.concat([
1862
- cipher.update(Buffer.from(options.plaintext, "utf8")),
1863
- cipher.final()
1864
- ]);
1865
- const tag = cipher.getAuthTag();
1866
- const payload = Buffer.concat([ciphertext, tag]);
1867
- return {
1868
- algorithm: "aes-256-gcm",
1869
- ciphertext: payload.toString("base64"),
1870
- nonce: iv.toString("base64"),
1871
- associatedData: associatedDataEncoded,
1872
- keyLocator: {
1873
- sessionId: options.sessionId,
1874
- revision: options.revision ?? 1
1875
- },
1876
- recipients: options.recipients.map((recipient) => ({
1877
- ...recipient,
1878
- encryptedShare: ""
1879
- }))
1880
- };
1881
- }
1882
- openCipherEnvelope(options) {
1883
- this.assertNodeRuntime("decryptCipherEnvelope");
1884
- const sharedSecret = this.normalizeSharedSecret(options.sharedSecret);
1885
- const payload = Buffer.from(options.envelope.ciphertext, "base64");
1886
- const nonce = Buffer.from(options.envelope.nonce, "base64");
1887
- const ciphertext = payload.slice(0, payload.length - 16);
1888
- const tag = payload.slice(payload.length - 16);
1889
- const decipher = createDecipheriv("aes-256-gcm", sharedSecret, nonce);
1890
- if (options.envelope.associatedData) {
1891
- decipher.setAAD(Buffer.from(options.envelope.associatedData, "base64"));
1892
- }
1893
- decipher.setAuthTag(tag);
1894
- const plaintext = Buffer.concat([
1895
- decipher.update(ciphertext),
1896
- decipher.final()
1897
- ]);
1898
- return plaintext.toString(options.encoding ?? "utf8");
1899
- }
1900
- normalizeSharedSecret(input) {
1901
- if (Buffer.isBuffer(input)) {
1902
- return Buffer.from(input);
1903
- }
1904
- if (input instanceof Uint8Array) {
1905
- return Buffer.from(input);
1425
+ /**
1426
+ * Retrieves NFTs for a specific token.
1427
+ * @param tokenId The token ID.
1428
+ * @param options Optional parameters for filtering NFTs.
1429
+ * @returns A promise that resolves to an array of NftInfo or null.
1430
+ */
1431
+ async getNftsByToken(tokenId, options) {
1432
+ this.logger.info(`Getting NFTs for token ${tokenId}`);
1433
+ let url = `/api/v1/tokens/${tokenId}/nfts`;
1434
+ const params = new URLSearchParams();
1435
+ if (options?.accountId) {
1436
+ params.append("account.id", options.accountId);
1906
1437
  }
1907
- if (typeof input === "string") {
1908
- return this.bufferFromString(input);
1438
+ if (options?.limit) {
1439
+ params.append("limit", options.limit.toString());
1909
1440
  }
1910
- throw new Error("Unsupported shared secret input");
1911
- }
1912
- bufferFromString(value) {
1913
- const trimmed = value.trim();
1914
- if (!trimmed) {
1915
- throw new Error("sharedSecret string cannot be empty");
1441
+ if (options?.order) {
1442
+ params.append("order", options.order);
1916
1443
  }
1917
- const normalized = trimmed.startsWith("0x") ? trimmed.slice(2) : trimmed;
1918
- if (/^[0-9a-fA-F]+$/.test(normalized) && normalized.length % 2 === 0) {
1919
- return Buffer.from(normalized, "hex");
1444
+ if (options?.serialNumber) {
1445
+ params.append("serialnumber", options.serialNumber);
1920
1446
  }
1921
- return Buffer.from(trimmed, "base64");
1922
- }
1923
- hexToBuffer(value) {
1924
- const normalized = value.startsWith("0x") ? value.slice(2) : value;
1925
- if (!/^[0-9a-fA-F]+$/.test(normalized) || normalized.length % 2 !== 0) {
1926
- throw new Error("Expected hex-encoded value");
1447
+ const queryString = params.toString();
1448
+ if (queryString) {
1449
+ url += `?${queryString}`;
1927
1450
  }
1928
- return Buffer.from(normalized, "hex");
1929
- }
1930
- }
1931
- const isPendingRegisterAgentResponse = (response) => response.status === "pending";
1932
- const isPartialRegisterAgentResponse = (response) => response.status === "partial" && response.success === false;
1933
- const isSuccessRegisterAgentResponse = (response) => response.success === true && response.status !== "pending";
1934
- class EncryptedChatManager {
1935
- constructor(client) {
1936
- this.client = client;
1937
- }
1938
- registerConversationContext(context) {
1939
- this.client.registerConversationContextForEncryption(context);
1940
- }
1941
- async startSession(options) {
1942
- await this.client.encryptionReady();
1943
- const session = await this.client.chat.createSession({
1944
- uaid: options.uaid,
1945
- senderUaid: options.senderUaid,
1946
- encryptionRequested: true,
1947
- historyTtlSeconds: options.historyTtlSeconds,
1948
- auth: options.auth
1949
- });
1950
- options.onSessionCreated?.(session.sessionId);
1951
- const summary = session.encryption;
1952
- if (!summary?.enabled) {
1953
- throw new EncryptionUnavailableError(
1954
- session.sessionId,
1955
- session.encryption ?? null
1451
+ try {
1452
+ const response = await this._requestWithRetry(url);
1453
+ return response.nfts || [];
1454
+ } catch (error) {
1455
+ this.logger.error(
1456
+ `Error fetching NFTs for token ${tokenId}: ${error.message}`
1956
1457
  );
1458
+ return null;
1957
1459
  }
1958
- const handle = await this.establishRequesterContext({
1959
- sessionId: session.sessionId,
1960
- summary,
1961
- senderUaid: options.senderUaid,
1962
- handshakeTimeoutMs: options.handshakeTimeoutMs,
1963
- pollIntervalMs: options.pollIntervalMs
1964
- });
1965
- return handle;
1966
- }
1967
- async acceptSession(options) {
1968
- await this.client.encryptionReady();
1969
- const summary = await this.waitForEncryptionSummary(
1970
- options.sessionId,
1971
- options.handshakeTimeoutMs,
1972
- options.pollIntervalMs
1973
- );
1974
- const handle = await this.establishResponderContext({
1975
- sessionId: options.sessionId,
1976
- summary,
1977
- responderUaid: options.responderUaid,
1978
- handshakeTimeoutMs: options.handshakeTimeoutMs,
1979
- pollIntervalMs: options.pollIntervalMs
1980
- });
1981
- return handle;
1982
- }
1983
- async establishRequesterContext(params) {
1984
- const keyPair = this.client.encryption.generateEphemeralKeyPair();
1985
- await this.client.chat.submitEncryptionHandshake(params.sessionId, {
1986
- role: "requester",
1987
- keyType: "secp256k1",
1988
- ephemeralPublicKey: keyPair.publicKey,
1989
- uaid: params.senderUaid ?? params.summary.requester?.uaid ?? void 0
1990
- });
1991
- const { summary, record } = await this.waitForHandshakeCompletion(
1992
- params.sessionId,
1993
- params.handshakeTimeoutMs,
1994
- params.pollIntervalMs
1995
- );
1996
- const responderKey = record.responder?.ephemeralPublicKey;
1997
- if (!responderKey) {
1998
- throw new Error("Responder handshake was not completed in time");
1999
- }
2000
- const sharedSecret = this.client.encryption.deriveSharedSecret({
2001
- privateKey: keyPair.privateKey,
2002
- peerPublicKey: responderKey
2003
- }).subarray();
2004
- const recipients = this.buildRecipients(summary);
2005
- return this.createHandle({
2006
- sessionId: params.sessionId,
2007
- sharedSecret,
2008
- summary,
2009
- recipients,
2010
- identity: summary.requester ?? void 0
2011
- });
2012
- }
2013
- async establishResponderContext(params) {
2014
- const keyPair = this.client.encryption.generateEphemeralKeyPair();
2015
- await this.client.chat.submitEncryptionHandshake(params.sessionId, {
2016
- role: "responder",
2017
- keyType: "secp256k1",
2018
- ephemeralPublicKey: keyPair.publicKey,
2019
- uaid: params.responderUaid ?? params.summary.responder?.uaid ?? void 0
2020
- });
2021
- const { summary, record } = await this.waitForHandshakeCompletion(
2022
- params.sessionId,
2023
- params.handshakeTimeoutMs,
2024
- params.pollIntervalMs
2025
- );
2026
- const requesterKey = record.requester?.ephemeralPublicKey;
2027
- if (!requesterKey) {
2028
- throw new Error("Requester handshake was not detected in time");
2029
- }
2030
- const sharedSecret = this.client.encryption.deriveSharedSecret({
2031
- privateKey: keyPair.privateKey,
2032
- peerPublicKey: requesterKey
2033
- }).subarray();
2034
- const recipients = this.buildRecipients(summary);
2035
- return this.createHandle({
2036
- sessionId: params.sessionId,
2037
- sharedSecret,
2038
- summary,
2039
- recipients,
2040
- identity: summary.responder ?? void 0
2041
- });
2042
1460
  }
2043
- async waitForHandshakeCompletion(sessionId, timeoutMs = 3e4, pollIntervalMs = 1e3) {
2044
- const deadline = Date.now() + timeoutMs;
2045
- while (true) {
2046
- const status = await this.client.chat.getEncryptionStatus(sessionId);
2047
- const summary = status.encryption;
2048
- const record = summary?.handshake;
2049
- if (summary && record && record.status === "complete") {
2050
- return { summary, record };
2051
- }
2052
- if (Date.now() >= deadline) {
2053
- throw new Error("Timed out waiting for encrypted handshake completion");
2054
- }
2055
- await this.delay(pollIntervalMs);
1461
+ /**
1462
+ * Retrieves network information.
1463
+ * @returns A promise that resolves to NetworkInfo or null.
1464
+ */
1465
+ async getNetworkInfo() {
1466
+ this.logger.info("Getting network information");
1467
+ const url = `/api/v1/network/nodes`;
1468
+ try {
1469
+ const response = await this._requestWithRetry(url);
1470
+ return response;
1471
+ } catch (error) {
1472
+ this.logger.error(`Error fetching network info: ${error.message}`);
1473
+ return null;
2056
1474
  }
2057
1475
  }
2058
- async waitForEncryptionSummary(sessionId, _timeoutMs = 3e4, _pollIntervalMs = 1e3) {
2059
- const status = await this.client.chat.getEncryptionStatus(sessionId);
2060
- if (!status.encryption?.enabled) {
2061
- throw new EncryptionUnavailableError(
2062
- sessionId,
2063
- status.encryption ?? null
2064
- );
1476
+ /**
1477
+ * Retrieves network fees.
1478
+ * @param timestamp Optional timestamp for historical fees.
1479
+ * @returns A promise that resolves to NetworkFees or null.
1480
+ */
1481
+ async getNetworkFees(timestamp) {
1482
+ this.logger.info("Getting network fees");
1483
+ let url = `/api/v1/network/fees`;
1484
+ if (timestamp) {
1485
+ url += `?timestamp=${timestamp}`;
1486
+ }
1487
+ try {
1488
+ const response = await this._requestWithRetry(url);
1489
+ return response;
1490
+ } catch (error) {
1491
+ this.logger.error(`Error fetching network fees: ${error.message}`);
1492
+ return null;
2065
1493
  }
2066
- return status.encryption;
2067
1494
  }
2068
- buildRecipients(summary) {
2069
- const candidates = [summary.requester, summary.responder].filter(Boolean);
2070
- const normalized = candidates.map((candidate) => {
2071
- if (!candidate) {
2072
- return null;
2073
- }
2074
- const recipient = {};
2075
- if (candidate.uaid) {
2076
- recipient.uaid = candidate.uaid;
2077
- }
2078
- if (candidate.ledgerAccountId) {
2079
- recipient.ledgerAccountId = candidate.ledgerAccountId;
2080
- }
2081
- if (candidate.userId) {
2082
- recipient.userId = candidate.userId;
2083
- }
2084
- if (candidate.email) {
2085
- recipient.email = candidate.email;
2086
- }
2087
- return recipient;
2088
- }).filter(
2089
- (entry) => Boolean(
2090
- entry?.uaid || entry?.ledgerAccountId || entry?.userId || entry?.email
2091
- )
2092
- );
2093
- if (normalized.length > 0) {
2094
- return normalized;
1495
+ /**
1496
+ * Retrieves network supply information.
1497
+ * @param timestamp Optional timestamp for historical supply data.
1498
+ * @returns A promise that resolves to NetworkSupply or null.
1499
+ */
1500
+ async getNetworkSupply(timestamp) {
1501
+ this.logger.info("Getting network supply");
1502
+ let url = `/api/v1/network/supply`;
1503
+ if (timestamp) {
1504
+ url += `?timestamp=${timestamp}`;
2095
1505
  }
2096
- if (summary.responder?.uaid) {
2097
- return [{ uaid: summary.responder.uaid }];
1506
+ try {
1507
+ const response = await this._requestWithRetry(url);
1508
+ return response;
1509
+ } catch (error) {
1510
+ this.logger.error(`Error fetching network supply: ${error.message}`);
1511
+ return null;
2098
1512
  }
2099
- return [];
2100
1513
  }
2101
- createHandle(context) {
2102
- const sharedSecret = context.sharedSecret;
2103
- const uaid = context.summary.requester?.uaid ?? context.summary.responder?.uaid ?? context.identity?.uaid;
2104
- const handle = {
2105
- sessionId: context.sessionId,
2106
- mode: "encrypted",
2107
- summary: context.summary,
2108
- send: async (options) => {
2109
- const recipients = options.recipients ?? context.recipients;
2110
- return this.client.chat.sendMessage({
2111
- sessionId: context.sessionId,
2112
- message: options.message ?? "[ciphertext omitted]",
2113
- streaming: options.streaming,
2114
- auth: options.auth,
2115
- uaid,
2116
- encryption: {
2117
- plaintext: options.plaintext,
2118
- sharedSecret: Buffer.from(sharedSecret),
2119
- recipients
2120
- }
2121
- });
2122
- },
2123
- decryptHistoryEntry: (entry) => this.decryptEntry(entry, context.identity, sharedSecret)
2124
- };
2125
- this.registerConversationContext({
2126
- sessionId: context.sessionId,
2127
- sharedSecret,
2128
- identity: context.identity
2129
- });
2130
- return handle;
2131
- }
2132
- decryptEntry(entry, identity, fallbackSecret) {
2133
- const envelope = entry.cipherEnvelope;
2134
- if (!envelope) {
2135
- return null;
1514
+ /**
1515
+ * Retrieves network stake information.
1516
+ * @param timestamp Optional timestamp for historical stake data.
1517
+ * @returns A promise that resolves to NetworkStake or null.
1518
+ */
1519
+ async getNetworkStake(timestamp) {
1520
+ this.logger.info("Getting network stake");
1521
+ let url = `/api/v1/network/stake`;
1522
+ if (timestamp) {
1523
+ url += `?timestamp=${timestamp}`;
2136
1524
  }
2137
- const secret = Buffer.from(fallbackSecret);
2138
1525
  try {
2139
- return this.client.encryption.decryptCipherEnvelope({
2140
- envelope,
2141
- sharedSecret: secret
2142
- });
2143
- } catch (_error) {
1526
+ const response = await this._requestWithRetry(url);
1527
+ return response;
1528
+ } catch (error) {
1529
+ this.logger.error(`Error fetching network stake: ${error.message}`);
2144
1530
  return null;
2145
1531
  }
2146
1532
  }
2147
- recipientMatches(candidate, target) {
2148
- if (target.uaid && candidate.uaid?.toLowerCase() === target.uaid.toLowerCase()) {
2149
- return true;
1533
+ /**
1534
+ * Retrieves opcode traces for a specific transaction.
1535
+ * @param transactionIdOrHash The transaction ID or hash.
1536
+ * @param options Optional parameters for trace details.
1537
+ * @returns A promise that resolves to an OpcodesResponse or null.
1538
+ */
1539
+ async getOpcodeTraces(transactionIdOrHash, options) {
1540
+ this.logger.info(`Getting opcode traces for ${transactionIdOrHash}`);
1541
+ let url = `/api/v1/contracts/results/${transactionIdOrHash}/opcodes`;
1542
+ const params = new URLSearchParams();
1543
+ if (options?.stack !== void 0) {
1544
+ params.append("stack", options.stack.toString());
2150
1545
  }
2151
- if (target.ledgerAccountId && candidate.ledgerAccountId?.toLowerCase() === target.ledgerAccountId.toLowerCase()) {
2152
- return true;
1546
+ if (options?.memory !== void 0) {
1547
+ params.append("memory", options.memory.toString());
2153
1548
  }
2154
- if (target.userId && candidate.userId === target.userId) {
2155
- return true;
1549
+ if (options?.storage !== void 0) {
1550
+ params.append("storage", options.storage.toString());
2156
1551
  }
2157
- if (target.email && candidate.email?.toLowerCase() === target.email.toLowerCase()) {
2158
- return true;
1552
+ const queryString = params.toString();
1553
+ if (queryString) {
1554
+ url += `?${queryString}`;
2159
1555
  }
2160
- return false;
2161
- }
2162
- async delay(ms) {
2163
- if (ms <= 0) {
2164
- return;
1556
+ try {
1557
+ const response = await this._requestWithRetry(url);
1558
+ return response;
1559
+ } catch (error) {
1560
+ this.logger.error(
1561
+ `Error fetching opcode traces for ${transactionIdOrHash}: ${error.message}`
1562
+ );
1563
+ return null;
2165
1564
  }
2166
- await new Promise((resolve) => setTimeout(resolve, ms));
2167
- }
2168
- }
2169
- class EncryptionUnavailableError extends Error {
2170
- constructor(sessionId, summary) {
2171
- super("Encryption is not enabled for this session");
2172
- this.sessionId = sessionId;
2173
- this.summary = summary;
2174
1565
  }
2175
1566
  }
2176
1567
  export {
2177
- RegistryBrokerClient,
2178
- RegistryBrokerError,
2179
- RegistryBrokerParseError,
2180
- isPartialRegisterAgentResponse,
2181
- isPendingRegisterAgentResponse,
2182
- isSuccessRegisterAgentResponse
1568
+ HederaMirrorNode
2183
1569
  };
2184
1570
  //# sourceMappingURL=standards-sdk.es127.js.map