@hashgraphonline/standards-sdk 0.1.136-fix-hol-env.canary.a285980.31 → 0.1.137-feat-hcs-21.canary.5802d65.32

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