@hashgraphonline/standards-sdk 0.0.114 → 0.0.116

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 (96) hide show
  1. package/README.md +4 -2
  2. package/dist/cjs/hcs-10/base-client.d.ts +2 -0
  3. package/dist/cjs/hcs-10/base-client.d.ts.map +1 -1
  4. package/dist/cjs/hcs-10/sdk.d.ts +10 -2
  5. package/dist/cjs/hcs-10/sdk.d.ts.map +1 -1
  6. package/dist/cjs/hcs-10/types.d.ts +2 -0
  7. package/dist/cjs/hcs-10/types.d.ts.map +1 -1
  8. package/dist/cjs/hcs-11/client.d.ts +4 -0
  9. package/dist/cjs/hcs-11/client.d.ts.map +1 -1
  10. package/dist/cjs/hcs-11/types.d.ts +1 -0
  11. package/dist/cjs/hcs-11/types.d.ts.map +1 -1
  12. package/dist/cjs/{index-CHar8dVv-CO7x6bkg.cjs → index-CHar8dVv-BQYxSvOg.cjs} +2 -2
  13. package/dist/cjs/{index-CHar8dVv-CO7x6bkg.cjs.map → index-CHar8dVv-BQYxSvOg.cjs.map} +1 -1
  14. package/dist/cjs/index-qpugvUCd.cjs +11 -0
  15. package/dist/cjs/index-qpugvUCd.cjs.map +1 -0
  16. package/dist/cjs/standards-sdk.cjs +1 -1
  17. package/dist/cjs/utils/index.d.ts +1 -0
  18. package/dist/cjs/utils/index.d.ts.map +1 -1
  19. package/dist/cjs/utils/key-type-detector.d.ts +14 -0
  20. package/dist/cjs/utils/key-type-detector.d.ts.map +1 -0
  21. package/dist/es/hcs-10/base-client.d.ts +2 -0
  22. package/dist/es/hcs-10/base-client.d.ts.map +1 -1
  23. package/dist/es/hcs-10/sdk.d.ts +10 -2
  24. package/dist/es/hcs-10/sdk.d.ts.map +1 -1
  25. package/dist/es/hcs-10/types.d.ts +2 -0
  26. package/dist/es/hcs-10/types.d.ts.map +1 -1
  27. package/dist/es/hcs-11/client.d.ts +4 -0
  28. package/dist/es/hcs-11/client.d.ts.map +1 -1
  29. package/dist/es/hcs-11/types.d.ts +1 -0
  30. package/dist/es/hcs-11/types.d.ts.map +1 -1
  31. package/dist/es/standards-sdk.es.js +6 -4
  32. package/dist/es/standards-sdk.es.js.map +1 -1
  33. package/dist/es/standards-sdk.es13.js +42 -5
  34. package/dist/es/standards-sdk.es13.js.map +1 -1
  35. package/dist/es/standards-sdk.es14.js.map +1 -1
  36. package/dist/es/standards-sdk.es16.js +1 -1
  37. package/dist/es/standards-sdk.es19.js +6 -6
  38. package/dist/es/standards-sdk.es20.js +23 -400
  39. package/dist/es/standards-sdk.es20.js.map +1 -1
  40. package/dist/es/standards-sdk.es21.js +380 -1506
  41. package/dist/es/standards-sdk.es21.js.map +1 -1
  42. package/dist/es/standards-sdk.es22.js +1511 -133
  43. package/dist/es/standards-sdk.es22.js.map +1 -1
  44. package/dist/es/standards-sdk.es23.js +155 -7
  45. package/dist/es/standards-sdk.es23.js.map +1 -1
  46. package/dist/es/standards-sdk.es24.js +7 -7190
  47. package/dist/es/standards-sdk.es24.js.map +1 -1
  48. package/dist/es/standards-sdk.es25.js +7190 -2
  49. package/dist/es/standards-sdk.es25.js.map +1 -1
  50. package/dist/es/standards-sdk.es26.js +2 -501
  51. package/dist/es/standards-sdk.es26.js.map +1 -1
  52. package/dist/es/standards-sdk.es27.js +457 -65
  53. package/dist/es/standards-sdk.es27.js.map +1 -1
  54. package/dist/es/standards-sdk.es28.js +80 -37
  55. package/dist/es/standards-sdk.es28.js.map +1 -1
  56. package/dist/es/standards-sdk.es29.js +33 -223
  57. package/dist/es/standards-sdk.es29.js.map +1 -1
  58. package/dist/es/standards-sdk.es30.js +184 -101
  59. package/dist/es/standards-sdk.es30.js.map +1 -1
  60. package/dist/es/standards-sdk.es31.js +167 -5
  61. package/dist/es/standards-sdk.es31.js.map +1 -1
  62. package/dist/es/standards-sdk.es32.js +8 -7132
  63. package/dist/es/standards-sdk.es32.js.map +1 -1
  64. package/dist/es/standards-sdk.es33.js +7134 -41
  65. package/dist/es/standards-sdk.es33.js.map +1 -1
  66. package/dist/es/standards-sdk.es34.js +45 -0
  67. package/dist/es/standards-sdk.es34.js.map +1 -0
  68. package/dist/es/standards-sdk.es5.js +4 -1
  69. package/dist/es/standards-sdk.es5.js.map +1 -1
  70. package/dist/es/standards-sdk.es7.js +294 -121
  71. package/dist/es/standards-sdk.es7.js.map +1 -1
  72. package/dist/es/standards-sdk.es8.js +2 -2
  73. package/dist/es/standards-sdk.es9.js +1 -1
  74. package/dist/es/utils/index.d.ts +1 -0
  75. package/dist/es/utils/index.d.ts.map +1 -1
  76. package/dist/es/utils/key-type-detector.d.ts +14 -0
  77. package/dist/es/utils/key-type-detector.d.ts.map +1 -0
  78. package/dist/umd/hcs-10/base-client.d.ts +2 -0
  79. package/dist/umd/hcs-10/base-client.d.ts.map +1 -1
  80. package/dist/umd/hcs-10/sdk.d.ts +10 -2
  81. package/dist/umd/hcs-10/sdk.d.ts.map +1 -1
  82. package/dist/umd/hcs-10/types.d.ts +2 -0
  83. package/dist/umd/hcs-10/types.d.ts.map +1 -1
  84. package/dist/umd/hcs-11/client.d.ts +4 -0
  85. package/dist/umd/hcs-11/client.d.ts.map +1 -1
  86. package/dist/umd/hcs-11/types.d.ts +1 -0
  87. package/dist/umd/hcs-11/types.d.ts.map +1 -1
  88. package/dist/umd/standards-sdk.umd.js +8 -8
  89. package/dist/umd/standards-sdk.umd.js.map +1 -1
  90. package/dist/umd/utils/index.d.ts +1 -0
  91. package/dist/umd/utils/index.d.ts.map +1 -1
  92. package/dist/umd/utils/key-type-detector.d.ts +14 -0
  93. package/dist/umd/utils/key-type-detector.d.ts.map +1 -0
  94. package/package.json +3 -3
  95. package/dist/cjs/index-C8CnOC88.cjs +0 -11
  96. package/dist/cjs/index-C8CnOC88.cjs.map +0 -1
@@ -1,1536 +1,410 @@
1
- import { PublicKey, Timestamp, AccountId } from "@hashgraph/sdk";
2
- import axios from "axios";
1
+ import { I as InscriptionSDK } from "./standards-sdk.es25.js";
3
2
  import { Logger } from "./standards-sdk.es15.js";
4
- import { proto } from "@hashgraph/proto";
5
- class HederaMirrorNode {
6
- constructor(network, logger, config) {
7
- this.maxRetries = 3;
8
- this.initialDelayMs = 1e3;
9
- this.maxDelayMs = 3e4;
10
- this.backoffFactor = 2;
11
- this.network = network;
12
- this.apiKey = config?.apiKey;
13
- this.customHeaders = config?.headers || {};
14
- this.baseUrl = config?.customUrl || this.getMirrorNodeUrl();
15
- this.logger = logger || new Logger({
16
- level: "debug",
17
- module: "MirrorNode"
18
- });
19
- this.isServerEnvironment = typeof window === "undefined";
20
- if (config?.customUrl) {
21
- this.logger.info(`Using custom mirror node URL: ${config.customUrl}`);
22
- }
23
- if (config?.apiKey) {
24
- this.logger.info("Using API key for mirror node requests");
25
- }
26
- }
27
- /**
28
- * Configures the retry mechanism for API requests.
29
- * @param config The retry configuration.
30
- */
31
- configureRetry(config) {
32
- this.maxRetries = config.maxRetries ?? this.maxRetries;
33
- this.initialDelayMs = config.initialDelayMs ?? this.initialDelayMs;
34
- this.maxDelayMs = config.maxDelayMs ?? this.maxDelayMs;
35
- this.backoffFactor = config.backoffFactor ?? this.backoffFactor;
36
- this.logger.info(
37
- `Retry configuration updated: maxRetries=${this.maxRetries}, initialDelayMs=${this.initialDelayMs}, maxDelayMs=${this.maxDelayMs}, backoffFactor=${this.backoffFactor}`
38
- );
39
- }
40
- /**
41
- * Updates the mirror node configuration.
42
- * @param config The new mirror node configuration.
43
- */
44
- configureMirrorNode(config) {
45
- if (config.customUrl) {
46
- this.baseUrl = config.customUrl;
47
- this.logger.info(`Updated mirror node URL: ${config.customUrl}`);
48
- }
49
- if (config.apiKey) {
50
- this.apiKey = config.apiKey;
51
- this.logger.info("Updated API key for mirror node requests");
52
- }
53
- if (config.headers) {
54
- this.customHeaders = { ...this.customHeaders, ...config.headers };
55
- this.logger.info("Updated custom headers for mirror node requests");
56
- }
57
- }
58
- /**
59
- * Constructs a full URL for API requests, handling custom providers with API keys in the path.
60
- * @param endpoint The API endpoint (e.g., '/api/v1/accounts/0.0.123')
61
- * @returns The full URL for the request
62
- */
63
- constructUrl(endpoint) {
64
- if (this.baseUrl.includes("<API-KEY>") && this.apiKey) {
65
- const baseUrlWithKey = this.baseUrl.replace("<API-KEY>", this.apiKey);
66
- return endpoint.startsWith("/") ? `${baseUrlWithKey}${endpoint}` : `${baseUrlWithKey}/${endpoint}`;
67
- }
68
- return endpoint.startsWith("/") ? `${this.baseUrl}${endpoint}` : `${this.baseUrl}/${endpoint}`;
69
- }
70
- getMirrorNodeUrl() {
71
- return this.network === "mainnet" ? "https://mainnet-public.mirrornode.hedera.com" : "https://testnet.mirrornode.hedera.com";
72
- }
73
- getBaseUrl() {
74
- return this.baseUrl;
75
- }
76
- /**
77
- * Retrieves the public key for a given account ID from the mirror node.
78
- * @param accountId The ID of the account to retrieve the public key for.
79
- * @returns A promise that resolves to the public key for the given account.
80
- * @throws An error if the account ID is invalid or the public key cannot be retrieved.
81
- */
82
- async getPublicKey(accountId) {
83
- this.logger.info(`Getting public key for account ${accountId}`);
84
- const accountInfo = await this.requestAccount(accountId);
85
- try {
86
- if (!accountInfo || !accountInfo.key) {
87
- throw new Error(
88
- `Failed to retrieve public key for account ID: ${accountId}`
89
- );
90
- }
91
- return PublicKey.fromString(accountInfo.key.key);
92
- } catch (e) {
93
- const error = e;
94
- const logMessage = `Error fetching public key from Mirror Node: ${error.message}`;
95
- this.logger.error(logMessage);
96
- throw new Error(logMessage);
97
- }
98
- }
99
- /**
100
- * Retrieves the memo for a given account ID from the mirror node.
101
- * @param accountId The ID of the account to retrieve the memo for.
102
- * @returns A promise that resolves to the memo for the given account.
103
- * @throws An error if the account ID is invalid or the memo cannot be retrieved.
104
- */
105
- async getAccountMemo(accountId) {
106
- this.logger.info(`Getting account memo for account ID: ${accountId}`);
107
- try {
108
- const accountInfo = await this._requestWithRetry(
109
- `/api/v1/accounts/${accountId}`
110
- );
111
- if (accountInfo?.memo) {
112
- return accountInfo.memo;
113
- }
114
- this.logger.warn(`No memo found for account ${accountId}`);
115
- return null;
116
- } catch (e) {
117
- const error = e;
118
- this.logger.error(
119
- `Failed to get account memo for ${accountId} after retries: ${error.message}`
120
- );
121
- return null;
122
- }
123
- }
124
- /**
125
- * Retrieves topic information for a given topic ID from the mirror node.
126
- * @param topicId The ID of the topic to retrieve information for.
127
- * @returns A promise that resolves to the topic information.
128
- * @throws An error if the topic ID is invalid or the information cannot be retrieved.
129
- */
130
- async getTopicInfo(topicId) {
131
- try {
132
- this.logger.debug(`Fetching topic info for ${topicId}`);
133
- const data = await this._requestWithRetry(
134
- `/api/v1/topics/${topicId}`
135
- );
136
- return data;
137
- } catch (e) {
138
- const error = e;
139
- const logMessage = `Error retrieving topic information for ${topicId} after retries: ${error.message}`;
140
- this.logger.error(logMessage);
141
- throw new Error(logMessage);
142
- }
143
- }
144
- /**
145
- * Retrieves custom fees for a given topic ID from the mirror node.
146
- * @param topicId The ID of the topic to retrieve custom fees for.
147
- * @returns A promise that resolves to the custom fees for the given topic.
148
- * @throws An error if the topic ID is invalid or the custom fees cannot be retrieved.
149
- */
150
- async getTopicFees(topicId) {
151
- try {
152
- const topicInfo = await this.getTopicInfo(topicId);
153
- return topicInfo.custom_fees;
154
- } catch (e) {
155
- const error = e;
156
- const logMessage = `Error retrieving topic fees: ${error.message}`;
157
- this.logger.error(logMessage);
158
- return null;
159
- }
160
- }
161
- /**
162
- * Retrieves the current HBAR price from the mirror node.
163
- * @param date The date to retrieve the HBAR price for.
164
- * @returns A promise that resolves to the HBAR price for the given date.
165
- * @throws An error if the date is invalid or the price cannot be retrieved.
166
- */
167
- async getHBARPrice(date) {
168
- try {
169
- const timestamp = Timestamp.fromDate(date).toString();
170
- this.logger.debug(`Fetching HBAR price for timestamp ${timestamp}`);
171
- const response = await this._requestWithRetry(
172
- `/api/v1/network/exchangerate?timestamp=${timestamp}`
173
- );
174
- const usdPrice = Number(response?.current_rate?.cent_equivalent) / Number(response?.current_rate?.hbar_equivalent) / 100;
175
- return usdPrice;
176
- } catch (e) {
177
- const error = e;
178
- const logMessage = `Error retrieving HBAR price: ${error.message}`;
179
- this.logger.error(logMessage);
180
- return null;
181
- }
182
- }
183
- /**
184
- * Retrieves token information for a given token ID from the mirror node.
185
- * @param tokenId The ID of the token to retrieve information for.
186
- * @returns A promise that resolves to the token information.
187
- * @throws An error if the token ID is invalid or the information cannot be retrieved.
188
- */
189
- async getTokenInfo(tokenId) {
190
- this.logger.debug(`Fetching token info for ${tokenId}`);
191
- try {
192
- const data = await this._requestWithRetry(
193
- `/api/v1/tokens/${tokenId}`
194
- );
195
- if (data) {
196
- this.logger.trace(`Token info found for ${tokenId}:`, data);
197
- return data;
198
- }
199
- this.logger.warn(`No token info found for ${tokenId}`);
200
- return null;
201
- } catch (e) {
202
- const error = e;
203
- const logMessage = `Error fetching token info for ${tokenId}: ${error.message}`;
204
- this.logger.error(logMessage);
205
- return null;
206
- }
207
- }
208
- /**
209
- * Retrieves messages for a given topic ID from the mirror node.
210
- * @param topicId The ID of the topic to retrieve messages for.
211
- * @returns A promise that resolves to the messages for the given topic.
212
- * @throws An error if the topic ID is invalid or the messages cannot be retrieved.
213
- */
214
- async getTopicMessages(topicId) {
215
- this.logger.trace(`Querying messages for topic ${topicId}`);
216
- let nextEndpoint = `/api/v1/topics/${topicId}/messages`;
217
- const messages = [];
218
- while (nextEndpoint) {
219
- try {
220
- const data = await this._requestWithRetry(nextEndpoint);
221
- if (data.messages && data.messages.length > 0) {
222
- for (const message of data.messages) {
223
- try {
224
- if (!message.message) {
225
- continue;
226
- }
227
- let messageContent;
228
- try {
229
- if (this.isServerEnvironment) {
230
- messageContent = Buffer.from(
231
- message.message,
232
- "base64"
233
- ).toString("utf-8");
234
- } else {
235
- messageContent = new TextDecoder().decode(
236
- Uint8Array.from(
237
- atob(message.message),
238
- (c) => c.charCodeAt(0)
239
- )
240
- );
241
- }
242
- } catch (error) {
243
- const logMessage = `Error decoding message: ${error}`;
244
- this.logger.error(logMessage);
245
- continue;
246
- }
247
- let messageJson;
248
- try {
249
- messageJson = JSON.parse(messageContent);
250
- } catch (error) {
251
- const logMessage = `Invalid JSON message content: ${messageContent}`;
252
- this.logger.error(logMessage);
253
- continue;
254
- }
255
- messageJson.sequence_number = message.sequence_number;
256
- messages.push({
257
- ...messageJson,
258
- consensus_timestamp: message.consensus_timestamp,
259
- sequence_number: message.sequence_number,
260
- created: new Date(Number(message.consensus_timestamp) * 1e3)
261
- });
262
- } catch (error) {
263
- const logMessage = `Error processing message: ${error.message}`;
264
- this.logger.error(logMessage);
265
- }
3
+ import { ProgressReporter } from "./standards-sdk.es17.js";
4
+ async function inscribe(input, clientConfig, options, existingSDK) {
5
+ const logger = Logger.getInstance({
6
+ module: "Inscriber",
7
+ ...options.logging
8
+ });
9
+ logger.info("Starting inscription process", {
10
+ type: input.type,
11
+ mode: options.mode || "file",
12
+ ...input.type === "url" ? { url: input.url } : {},
13
+ ...input.type === "file" ? { path: input.path } : {},
14
+ ...input.type === "buffer" ? { fileName: input.fileName, bufferSize: input.buffer.byteLength } : {}
15
+ });
16
+ try {
17
+ if (options.mode === "hashinal" && options.metadata) {
18
+ validateHashinalMetadata(options.metadata, logger);
19
+ }
20
+ let sdk;
21
+ if (existingSDK) {
22
+ logger.debug("Using existing InscriptionSDK instance");
23
+ sdk = existingSDK;
24
+ } else if (options.apiKey) {
25
+ logger.debug("Initializing InscriptionSDK with API key");
26
+ sdk = new InscriptionSDK({
27
+ apiKey: options.apiKey,
28
+ network: clientConfig.network || "mainnet"
29
+ });
30
+ } else {
31
+ logger.debug("Initializing InscriptionSDK with server auth");
32
+ sdk = await InscriptionSDK.createWithAuth({
33
+ type: "server",
34
+ accountId: clientConfig.accountId,
35
+ privateKey: clientConfig.privateKey,
36
+ network: clientConfig.network || "mainnet"
37
+ });
38
+ }
39
+ const baseRequest = {
40
+ holderId: clientConfig.accountId,
41
+ metadata: options.metadata || {},
42
+ tags: options.tags || [],
43
+ mode: options.mode || "file",
44
+ chunkSize: options.chunkSize
45
+ };
46
+ let request;
47
+ switch (input.type) {
48
+ case "url":
49
+ request = {
50
+ ...baseRequest,
51
+ file: {
52
+ type: "url",
53
+ url: input.url
266
54
  }
267
- }
268
- nextEndpoint = data.links?.next || "";
269
- } catch (e) {
270
- const error = e;
271
- const logMessage = `Error querying topic messages for topic ${topicId} (endpoint: ${nextEndpoint}) after retries: ${error.message}`;
272
- this.logger.error(logMessage);
273
- throw new Error(logMessage);
274
- }
275
- }
276
- return messages;
277
- }
278
- /**
279
- * Requests account information for a given account ID from the mirror node.
280
- * @param accountId The ID of the account to retrieve information for.
281
- * @returns A promise that resolves to the account information.
282
- * @throws An error if the account ID is invalid or the information cannot be retrieved.
283
- */
284
- async requestAccount(accountId) {
285
- try {
286
- this.logger.debug(`Requesting account info for ${accountId}`);
287
- const data = await this._requestWithRetry(
288
- `/api/v1/accounts/${accountId}`
289
- );
290
- if (!data) {
291
- throw new Error(
292
- `No data received from mirror node for account: ${accountId}`
293
- );
294
- }
295
- return data;
296
- } catch (e) {
297
- const error = e;
298
- const logMessage = `Failed to fetch account ${accountId} after retries: ${error.message}`;
299
- this.logger.error(logMessage);
300
- throw new Error(logMessage);
301
- }
302
- }
303
- /**
304
- * Checks if a user has access to a given key list.
305
- * @param keyBytes The key list to check access for.
306
- * @param userPublicKey The public key of the user to check access for.
307
- * @returns A promise that resolves to true if the user has access, false otherwise.
308
- */
309
- async checkKeyListAccess(keyBytes, userPublicKey) {
310
- try {
311
- const key = proto.Key.decode(keyBytes);
312
- return this.evaluateKeyAccess(key, userPublicKey);
313
- } catch (e) {
314
- const error = e;
315
- const logMessage = `Error decoding protobuf key: ${error.message}`;
316
- this.logger.error(logMessage);
317
- throw new Error(logMessage);
318
- }
319
- }
320
- /**
321
- * Evaluates the access of a given key to a user's public key.
322
- * @param key The key to evaluate access for.
323
- * @param userPublicKey The public key of the user to evaluate access for.
324
- * @returns A promise that resolves to true if the key has access, false otherwise.
325
- */
326
- async evaluateKeyAccess(key, userPublicKey) {
327
- if (key.ed25519) {
328
- return this.compareEd25519Key(key.ed25519, userPublicKey);
329
- }
330
- if (key.keyList) {
331
- return this.evaluateKeyList(key.keyList, userPublicKey);
332
- }
333
- if (key.thresholdKey && key.thresholdKey.keys) {
334
- return this.evaluateKeyList(key.thresholdKey.keys, userPublicKey);
335
- }
336
- return false;
337
- }
338
- /**
339
- * Evaluates the access of a given key list to a user's public key.
340
- * @param keyList The key list to evaluate access for.
341
- * @param userPublicKey The public key of the user to evaluate access for.
342
- * @returns A promise that resolves to true if the key list has access, false otherwise.
343
- */
344
- async evaluateKeyList(keyList, userPublicKey) {
345
- const keys = keyList.keys || [];
346
- for (const listKey of keys) {
347
- if (!listKey) continue;
348
- if (listKey.ed25519) {
349
- if (this.compareEd25519Key(listKey.ed25519, userPublicKey)) {
350
- return true;
351
- }
352
- } else if (listKey.keyList || listKey.thresholdKey) {
353
- try {
354
- const nestedKeyBytes = proto.Key.encode({
355
- ...listKey.keyList ? { keyList: listKey.keyList } : {},
356
- ...listKey.thresholdKey ? { thresholdKey: listKey.thresholdKey } : {}
357
- }).finish();
358
- const hasNestedAccess = await this.checkKeyListAccess(
359
- Buffer.from(nestedKeyBytes),
360
- userPublicKey
361
- );
362
- if (hasNestedAccess) {
363
- return true;
55
+ };
56
+ break;
57
+ case "file":
58
+ request = {
59
+ ...baseRequest,
60
+ file: {
61
+ type: "path",
62
+ path: input.path
364
63
  }
365
- } catch (e) {
366
- const error = e;
367
- const logMessage = `Error in nested key: ${error.message}`;
368
- this.logger.debug(logMessage);
369
- }
370
- }
371
- }
372
- return false;
373
- }
374
- /**
375
- * Compares an Ed25519 key with a user's public key.
376
- * @param keyData The Ed25519 key data to compare.
377
- * @param userPublicKey The public key of the user to compare with.
378
- * @returns A boolean indicating whether the key matches the user's public key.
379
- */
380
- compareEd25519Key(keyData, userPublicKey) {
381
- try {
382
- const decodedKey = PublicKey.fromBytes(Buffer.from(keyData));
383
- return decodedKey.toString() === userPublicKey.toString();
384
- } catch (e) {
385
- const error = e;
386
- const logMessage = `Error comparing Ed25519 key: ${error.message}`;
387
- this.logger.debug(logMessage);
388
- return false;
389
- }
390
- }
391
- /**
392
- * Retrieves information about a scheduled transaction
393
- * @param scheduleId The ID of the scheduled transaction
394
- * @returns A promise that resolves to the scheduled transaction information
395
- */
396
- async getScheduleInfo(scheduleId) {
397
- try {
398
- this.logger.info(
399
- `Getting information for scheduled transaction ${scheduleId}`
400
- );
401
- const data = await this._requestWithRetry(
402
- `/api/v1/schedules/${scheduleId}`
403
- );
404
- if (data) {
405
- return data;
64
+ };
65
+ break;
66
+ case "buffer":
67
+ request = {
68
+ ...baseRequest,
69
+ file: {
70
+ type: "base64",
71
+ base64: Buffer.from(input.buffer).toString("base64"),
72
+ fileName: input.fileName,
73
+ mimeType: input.mimeType
74
+ }
75
+ };
76
+ break;
77
+ }
78
+ if (options.mode === "hashinal") {
79
+ request.metadataObject = options.metadata;
80
+ request.creator = options.metadata?.creator || clientConfig.accountId;
81
+ request.description = options.metadata?.description;
82
+ if (options.jsonFileURL) {
83
+ request.jsonFileURL = options.jsonFileURL;
406
84
  }
407
- this.logger.warn(
408
- `No schedule info found for ${scheduleId} after retries.`
409
- );
410
- return null;
411
- } catch (error) {
412
- this.logger.error(
413
- `Error fetching schedule info for ${scheduleId} after retries: ${error.message}`
414
- );
415
- return null;
416
85
  }
417
- }
418
- /**
419
- * Checks the status of a scheduled transaction
420
- * @param scheduleId The schedule ID to check
421
- * @returns Status of the scheduled transaction
422
- */
423
- async getScheduledTransactionStatus(scheduleId) {
424
- try {
425
- this.logger.info(
426
- `Checking status of scheduled transaction ${scheduleId}`
427
- );
428
- const scheduleInfo = await this.getScheduleInfo(scheduleId);
429
- if (!scheduleInfo) {
430
- throw new Error(`Schedule ${scheduleId} not found`);
431
- }
86
+ logger.debug("Preparing to inscribe content", {
87
+ type: input.type,
88
+ mode: options.mode || "file",
89
+ holderId: clientConfig.accountId
90
+ });
91
+ const result = await sdk.inscribeAndExecute(request, clientConfig);
92
+ logger.info("Starting to inscribe.", {
93
+ type: input.type,
94
+ mode: options.mode || "file",
95
+ transactionId: result.jobId
96
+ });
97
+ if (options.waitForConfirmation) {
98
+ logger.debug("Waiting for inscription confirmation", {
99
+ transactionId: result.jobId,
100
+ maxAttempts: options.waitMaxAttempts,
101
+ intervalMs: options.waitIntervalMs
102
+ });
103
+ const inscription = await waitForInscriptionConfirmation(
104
+ sdk,
105
+ result.jobId,
106
+ options.waitMaxAttempts,
107
+ options.waitIntervalMs,
108
+ options.progressCallback
109
+ );
110
+ logger.info("Inscription confirmation received", {
111
+ transactionId: result.jobId
112
+ });
432
113
  return {
433
- executed: Boolean(scheduleInfo.executed_timestamp),
434
- executedDate: scheduleInfo.executed_timestamp ? new Date(Number(scheduleInfo.executed_timestamp) * 1e3) : void 0,
435
- deleted: scheduleInfo.deleted || false
114
+ confirmed: true,
115
+ result,
116
+ inscription,
117
+ sdk
436
118
  };
437
- } catch (error) {
438
- this.logger.error(
439
- `Error checking scheduled transaction status: ${error}`
440
- );
441
- throw error;
442
- }
443
- }
444
- /**
445
- * Retrieves details for a given transaction ID or hash from the mirror node.
446
- * @param transactionIdOrHash The ID or hash of the transaction.
447
- * @returns A promise that resolves to the transaction details.
448
- * @throws An error if the transaction ID/hash is invalid or details cannot be retrieved.
449
- */
450
- async getTransaction(transactionIdOrHash) {
451
- this.logger.info(
452
- `Getting transaction details for ID/hash: ${transactionIdOrHash}`
453
- );
454
- try {
455
- const response = await this._requestWithRetry(`/api/v1/transactions/${transactionIdOrHash}`);
456
- if (response?.transactions?.length > 0) {
457
- this.logger.trace(
458
- `Transaction details found for ${transactionIdOrHash}:`,
459
- response.transactions[0]
460
- );
461
- return response.transactions[0];
462
- }
463
- this.logger.warn(
464
- `No transaction details found for ${transactionIdOrHash} or unexpected response structure.`
465
- );
466
- return null;
467
- } catch (e) {
468
- const error = e;
469
- this.logger.error(
470
- `Failed to get transaction details for ${transactionIdOrHash} after retries: ${error.message}`
471
- );
472
- return null;
473
119
  }
474
- }
475
- /**
476
- * Private helper to make GET requests with retry logic using Axios.
477
- */
478
- async _requestWithRetry(endpoint, axiosConfig) {
479
- let attempt = 0;
480
- let delay = this.initialDelayMs;
481
- const url = this.constructUrl(endpoint);
482
- const config = {
483
- ...axiosConfig,
484
- headers: {
485
- ...this.customHeaders,
486
- ...axiosConfig?.headers
487
- }
120
+ return {
121
+ confirmed: false,
122
+ result,
123
+ sdk
488
124
  };
489
- if (this.apiKey) {
490
- config.headers = {
491
- ...config.headers,
492
- Authorization: `Bearer ${this.apiKey}`,
493
- "X-API-Key": this.apiKey
494
- };
495
- }
496
- while (attempt < this.maxRetries) {
497
- try {
498
- const response = await axios.get(url, config);
499
- return response.data;
500
- } catch (error) {
501
- attempt++;
502
- const isLastAttempt = attempt >= this.maxRetries;
503
- const statusCode = error.response?.status;
504
- if (statusCode && statusCode >= 400 && statusCode < 500 && statusCode !== 429) {
505
- this.logger.error(
506
- `Client error for ${url} (status ${statusCode}): ${error.message}. Not retrying.`
507
- );
508
- throw error;
509
- }
510
- if (isLastAttempt) {
511
- this.logger.error(
512
- `Max retries (${this.maxRetries}) reached for ${url}. Last error: ${error.message}`
513
- );
514
- throw error;
515
- }
516
- this.logger.warn(
517
- `Attempt ${attempt}/${this.maxRetries} failed for ${url}: ${error.message}. Retrying in ${delay}ms...`
518
- );
519
- await new Promise((resolve) => setTimeout(resolve, delay));
520
- delay = Math.min(delay * this.backoffFactor, this.maxDelayMs);
521
- }
522
- }
523
- throw new Error(
524
- `Failed to fetch data from ${url} after ${this.maxRetries} attempts.`
525
- );
125
+ } catch (error) {
126
+ logger.error("Error during inscription process", error);
127
+ throw error;
526
128
  }
527
- /**
528
- * Private helper to make fetch requests with retry logic.
529
- */
530
- async _fetchWithRetry(url, fetchOptions) {
531
- let attempt = 0;
532
- let delay = this.initialDelayMs;
533
- const headers = {
534
- ...this.customHeaders
535
- };
536
- if (fetchOptions?.headers) {
537
- if (fetchOptions.headers instanceof Headers) {
538
- fetchOptions.headers.forEach((value, key) => {
539
- headers[key] = value;
540
- });
541
- } else if (Array.isArray(fetchOptions.headers)) {
542
- fetchOptions.headers.forEach(([key, value]) => {
543
- headers[key] = value;
544
- });
545
- } else {
546
- Object.assign(headers, fetchOptions.headers);
547
- }
548
- }
549
- if (this.apiKey) {
550
- headers["Authorization"] = `Bearer ${this.apiKey}`;
551
- headers["X-API-Key"] = this.apiKey;
552
- }
553
- const options = {
554
- ...fetchOptions,
555
- headers
129
+ }
130
+ async function inscribeWithSigner(input, signer, options, existingSDK) {
131
+ const logger = Logger.getInstance({
132
+ module: "Inscriber",
133
+ ...options.logging
134
+ });
135
+ logger.info("Starting inscription process with signer", {
136
+ type: input.type,
137
+ mode: options.mode || "file",
138
+ ...input.type === "url" ? { url: input.url } : {},
139
+ ...input.type === "file" ? { path: input.path } : {},
140
+ ...input.type === "buffer" ? { fileName: input.fileName, bufferSize: input.buffer.byteLength } : {}
141
+ });
142
+ try {
143
+ if (options.mode === "hashinal" && options.metadata) {
144
+ validateHashinalMetadata(options.metadata, logger);
145
+ }
146
+ const accountId = signer.getAccountId().toString();
147
+ logger.debug("Using account ID from signer", { accountId });
148
+ let sdk;
149
+ if (existingSDK) {
150
+ logger.debug("Using existing InscriptionSDK instance");
151
+ sdk = existingSDK;
152
+ } else if (options.apiKey) {
153
+ logger.debug("Initializing InscriptionSDK with API key");
154
+ sdk = new InscriptionSDK({
155
+ apiKey: options.apiKey,
156
+ network: options.network || "mainnet"
157
+ });
158
+ } else {
159
+ logger.debug("Initializing InscriptionSDK with client auth");
160
+ sdk = await InscriptionSDK.createWithAuth({
161
+ type: "client",
162
+ accountId,
163
+ signer,
164
+ network: options.network || "mainnet"
165
+ });
166
+ }
167
+ const baseRequest = {
168
+ holderId: accountId,
169
+ metadata: options.metadata || {},
170
+ tags: options.tags || [],
171
+ mode: options.mode || "file",
172
+ chunkSize: options.chunkSize
556
173
  };
557
- while (attempt < this.maxRetries) {
558
- try {
559
- const request = await fetch(url, options);
560
- if (!request.ok) {
561
- if (request.status >= 400 && request.status < 500 && request.status !== 429) {
562
- this.logger.error(
563
- `Client error for ${url} (status ${request.status}): ${request.statusText}. Not retrying.`
564
- );
565
- throw new Error(
566
- `Fetch failed with status ${request.status}: ${request.statusText} for URL: ${url}`
567
- );
174
+ let request;
175
+ switch (input.type) {
176
+ case "url":
177
+ request = {
178
+ ...baseRequest,
179
+ file: {
180
+ type: "url",
181
+ url: input.url
568
182
  }
569
- throw new Error(
570
- `Fetch failed with status ${request.status}: ${request.statusText} for URL: ${url}`
571
- );
572
- }
573
- const response = await request.json();
574
- return response;
575
- } catch (error) {
576
- attempt++;
577
- if (attempt >= this.maxRetries) {
578
- this.logger.error(
579
- `Max retries (${this.maxRetries}) reached for ${url}. Last error: ${error.message}`
580
- );
581
- throw error;
582
- }
583
- this.logger.warn(
584
- `Attempt ${attempt}/${this.maxRetries} failed for ${url}: ${error.message}. Retrying in ${delay}ms...`
585
- );
586
- await new Promise((resolve) => setTimeout(resolve, delay));
587
- delay = Math.min(delay * this.backoffFactor, this.maxDelayMs);
588
- }
589
- }
590
- throw new Error(
591
- `Failed to fetch data from ${url} after ${this.maxRetries} attempts.`
592
- );
593
- }
594
- /**
595
- * Retrieves the numerical balance (in HBAR) for a given account ID.
596
- * @param accountId The ID of the account.
597
- * @returns A promise that resolves to the HBAR balance or null if an error occurs.
598
- */
599
- async getAccountBalance(accountId) {
600
- this.logger.info(`Getting balance for account ${accountId}`);
601
- try {
602
- const accountInfo = await this.requestAccount(accountId);
603
- if (accountInfo && accountInfo.balance) {
604
- const hbarBalance = accountInfo.balance.balance / 1e8;
605
- return hbarBalance;
606
- }
607
- this.logger.warn(
608
- `Could not retrieve balance for account ${accountId} from account info.`
609
- );
610
- return null;
611
- } catch (error) {
612
- this.logger.error(
613
- `Error fetching numerical balance for account ${accountId}: ${error.message}`
614
- );
615
- return null;
616
- }
617
- }
618
- /**
619
- * Retrieves messages for a given topic ID with optional filters.
620
- * @param topicId The ID of the topic.
621
- * @param sequenceNumber Filter by sequence number (e.g., "gt:10", "lte:20").
622
- * @param startTime Filter by consensus timestamp (e.g., "gt:1629400000.000000000").
623
- * @param endTime Filter by consensus timestamp (e.g., "lt:1629500000.000000000").
624
- * @param limit The maximum number of messages to return.
625
- * @returns A promise that resolves to an array of HCSMessages or null.
626
- */
627
- async getTopicMessagesByFilter(topicId, options) {
628
- this.logger.trace(
629
- `Querying messages for topic ${topicId} with filters: ${JSON.stringify(
630
- options
631
- )}`
632
- );
633
- let nextUrl = `/api/v1/topics/${topicId}/messages`;
634
- const params = new URLSearchParams();
635
- if (options?.limit) {
636
- params.append("limit", options.limit.toString());
637
- }
638
- if (options?.sequenceNumber) {
639
- params.append("sequencenumber", options.sequenceNumber);
640
- }
641
- if (options?.startTime) {
642
- params.append("timestamp", `gte:${options.startTime}`);
643
- }
644
- if (options?.endTime) {
645
- params.append("timestamp", `lt:${options.endTime}`);
646
- }
647
- if (options?.order) {
648
- params.append("order", options.order);
649
- }
650
- const queryString = params.toString();
651
- if (queryString) {
652
- nextUrl += `?${queryString}`;
653
- }
654
- const messages = [];
655
- let pagesFetched = 0;
656
- const maxPages = 10;
657
- try {
658
- while (nextUrl && pagesFetched < maxPages) {
659
- pagesFetched++;
660
- const data = await this._requestWithRetry(nextUrl);
661
- if (data.messages && data.messages.length > 0) {
662
- for (const message of data.messages) {
663
- try {
664
- if (!message.message) {
665
- continue;
666
- }
667
- let messageContent;
668
- if (this.isServerEnvironment) {
669
- messageContent = Buffer.from(
670
- message.message,
671
- "base64"
672
- ).toString("utf-8");
673
- } else {
674
- messageContent = new TextDecoder().decode(
675
- Uint8Array.from(atob(message.message), (c) => c.charCodeAt(0))
676
- );
677
- }
678
- let messageJson = {};
679
- try {
680
- messageJson = JSON.parse(messageContent);
681
- } catch (parseError) {
682
- this.logger.debug(
683
- `Message content is not valid JSON, using raw: ${messageContent}`
684
- );
685
- messageJson = { raw_content: messageContent };
686
- }
687
- const parsedContent = messageJson;
688
- const hcsMsg = {
689
- ...parsedContent,
690
- consensus_timestamp: message.consensus_timestamp,
691
- sequence_number: message.sequence_number,
692
- payer_account_id: message.payer_account_id,
693
- topic_id: message.topic_id,
694
- running_hash: message.running_hash,
695
- running_hash_version: message.running_hash_version,
696
- chunk_info: message.chunk_info,
697
- created: new Date(
698
- Number(message.consensus_timestamp.split(".")[0]) * 1e3 + Number(message.consensus_timestamp.split(".")[1] || 0) / 1e6
699
- ),
700
- payer: message.payer_account_id
701
- };
702
- messages.push(hcsMsg);
703
- } catch (error) {
704
- this.logger.error(
705
- `Error processing individual message: ${error.message}`
706
- );
707
- }
183
+ };
184
+ break;
185
+ case "file":
186
+ request = {
187
+ ...baseRequest,
188
+ file: {
189
+ type: "path",
190
+ path: input.path
708
191
  }
709
- }
710
- if (options?.limit && messages.length >= options.limit) break;
711
- nextUrl = data.links?.next ? `${data.links.next}` : "";
712
- }
713
- return messages;
714
- } catch (e) {
715
- const error = e;
716
- this.logger.error(
717
- `Error querying filtered topic messages for ${topicId}: ${error.message}`
718
- );
719
- return null;
720
- }
721
- }
722
- /**
723
- * Retrieves token balances for a given account ID.
724
- * @param accountId The ID of the account.
725
- * @param limit The maximum number of tokens to return.
726
- * @returns A promise that resolves to an array of AccountTokenBalance or null.
727
- */
728
- async getAccountTokens(accountId, limit = 100) {
729
- this.logger.info(`Getting tokens for account ${accountId}`);
730
- let allTokens = [];
731
- let endpoint = `/api/v1/accounts/${accountId}/tokens?limit=${limit}`;
732
- try {
733
- for (let i = 0; i < 10 && endpoint; i++) {
734
- const response = await this._requestWithRetry(endpoint);
735
- if (response && response.tokens) {
736
- allTokens = allTokens.concat(response.tokens);
737
- }
738
- endpoint = response.links?.next || "";
739
- if (!endpoint || limit && allTokens.length >= limit) {
740
- if (limit && allTokens.length > limit) {
741
- allTokens = allTokens.slice(0, limit);
192
+ };
193
+ break;
194
+ case "buffer":
195
+ request = {
196
+ ...baseRequest,
197
+ file: {
198
+ type: "base64",
199
+ base64: Buffer.from(input.buffer).toString("base64"),
200
+ fileName: input.fileName,
201
+ mimeType: input.mimeType
742
202
  }
743
- break;
744
- }
745
- }
746
- return allTokens;
747
- } catch (error) {
748
- this.logger.error(
749
- `Error fetching tokens for account ${accountId}: ${error.message}`
750
- );
751
- return null;
752
- }
753
- }
754
- /**
755
- * Retrieves transaction details by consensus timestamp.
756
- * @param timestamp The consensus timestamp of the transaction (e.g., "1629400000.000000000").
757
- * @returns A promise that resolves to the transaction details or null.
758
- */
759
- async getTransactionByTimestamp(timestamp) {
760
- this.logger.info(`Getting transaction by timestamp: ${timestamp}`);
761
- try {
762
- const response = await this._requestWithRetry(`/api/v1/transactions?timestamp=${timestamp}&limit=1`);
763
- return response.transactions;
764
- } catch (error) {
765
- this.logger.error(
766
- `Error fetching transaction by timestamp ${timestamp}: ${error}`
767
- );
768
- return [];
769
- }
770
- }
771
- /**
772
- * Retrieves NFTs for a given account ID, optionally filtered by token ID.
773
- * @param accountId The ID of the account.
774
- * @param tokenId Optional ID of the token to filter NFTs by.
775
- * @param limit The maximum number of NFTs to return per page (API has its own max).
776
- * @returns A promise that resolves to an array of NftDetail or null.
777
- */
778
- async getAccountNfts(accountId, tokenId, limit = 100) {
779
- this.logger.info(
780
- `Getting NFTs for account ${accountId}${tokenId ? ` for token ${tokenId}` : ""}`
781
- );
782
- let allNfts = [];
783
- let endpoint = `/api/v1/accounts/${accountId}/nfts?limit=${limit}`;
784
- if (tokenId) {
785
- endpoint += `&token.id=${tokenId}`;
786
- }
787
- try {
788
- for (let i = 0; i < 10 && endpoint; i++) {
789
- const response = await this._requestWithRetry(endpoint);
790
- if (response && response.nfts) {
791
- const nftsWithUri = response.nfts.map((nft) => {
792
- let tokenUri = void 0;
793
- if (nft.metadata) {
794
- try {
795
- if (this.isServerEnvironment) {
796
- tokenUri = Buffer.from(nft.metadata, "base64").toString(
797
- "utf-8"
798
- );
799
- } else {
800
- tokenUri = new TextDecoder().decode(
801
- Uint8Array.from(atob(nft.metadata), (c) => c.charCodeAt(0))
802
- );
803
- }
804
- } catch (e) {
805
- this.logger.warn(
806
- `Failed to decode metadata for NFT ${nft.token_id} SN ${nft.serial_number}: ${e.message}`
807
- );
808
- }
809
- }
810
- return { ...nft, token_uri: tokenUri };
811
- });
812
- allNfts = allNfts.concat(nftsWithUri);
813
- }
814
- endpoint = response.links?.next || "";
815
- if (!endpoint) break;
816
- }
817
- return allNfts;
818
- } catch (error) {
819
- this.logger.error(
820
- `Error fetching NFTs for account ${accountId}: ${error.message}`
821
- );
822
- return null;
823
- }
824
- }
825
- /**
826
- * Validates NFT ownership by checking if a specific serial number of a token ID exists for an account.
827
- * @param accountId The ID of the account.
828
- * @param tokenId The ID of the NFT's token.
829
- * @param serialNumber The serial number of the NFT.
830
- * @returns A promise that resolves to the NftDetail if owned, or null otherwise.
831
- */
832
- async validateNFTOwnership(accountId, tokenId, serialNumber) {
833
- this.logger.info(
834
- `Validating ownership of NFT ${tokenId} SN ${serialNumber} for account ${accountId}`
835
- );
836
- try {
837
- const nfts = await this.getAccountNfts(accountId, tokenId);
838
- if (nfts) {
839
- const foundNft = nfts.find(
840
- (nft) => nft.token_id === tokenId && nft.serial_number === serialNumber
841
- );
842
- return foundNft || null;
203
+ };
204
+ break;
205
+ }
206
+ if (options.mode === "hashinal") {
207
+ request.metadataObject = options.metadata;
208
+ request.creator = options.metadata?.creator || accountId;
209
+ request.description = options.metadata?.description;
210
+ if (options.jsonFileURL) {
211
+ request.jsonFileURL = options.jsonFileURL;
843
212
  }
844
- return null;
845
- } catch (error) {
846
- this.logger.error(`Error validating NFT ownership: ${error.message}`);
847
- return null;
848
213
  }
849
- }
850
- /**
851
- * Performs a read-only query against a smart contract (eth_call like).
852
- * @param contractIdOrAddress The contract ID (e.g., "0.0.123") or EVM address (e.g., "0x...").
853
- * @param functionSelector The function selector and encoded parameters (e.g., "0xabcdef12...").
854
- * @param payerAccountId The account ID of the payer (not strictly payer for read-only, but often required as 'from').
855
- * @param estimate Whether this is an estimate call. Mirror node might not support this directly in /contracts/call for true estimation.
856
- * @param block Block parameter, e.g., "latest", "pending", or block number.
857
- * @param value The value in tinybars to send with the call (for payable view/pure functions, usually 0).
858
- * @returns A promise that resolves to the contract call query response or null.
859
- */
860
- async readSmartContractQuery(contractIdOrAddress, functionSelector, payerAccountId, options) {
861
- this.logger.info(
862
- `Reading smart contract ${contractIdOrAddress} with selector ${functionSelector}`
863
- );
864
- const toAddress = contractIdOrAddress.startsWith("0x") ? contractIdOrAddress : `0x${AccountId.fromString(contractIdOrAddress).toSolidityAddress()}`;
865
- const fromAddress = payerAccountId.startsWith("0x") ? payerAccountId : `0x${AccountId.fromString(payerAccountId).toSolidityAddress()}`;
866
- const body = {
867
- block: options?.block || "latest",
868
- data: functionSelector,
869
- estimate: options?.estimate || false,
870
- from: fromAddress,
871
- to: toAddress,
872
- gas: options?.gas,
873
- gasPrice: options?.gasPrice,
874
- value: options?.value || 0
875
- };
876
- Object.keys(body).forEach((key) => {
877
- const K = key;
878
- if (body[K] === void 0) {
879
- delete body[K];
880
- }
214
+ logger.debug("Preparing to inscribe content with signer", {
215
+ type: input.type,
216
+ mode: options.mode || "file",
217
+ holderId: accountId
881
218
  });
882
- try {
883
- const url = this.constructUrl("/api/v1/contracts/call");
884
- const response = await this._fetchWithRetry(
885
- url,
886
- {
887
- method: "POST",
888
- body: JSON.stringify(body),
889
- headers: {
890
- "Content-Type": "application/json"
891
- }
892
- }
893
- );
894
- return response;
895
- } catch (error) {
896
- this.logger.error(
897
- `Error reading smart contract ${contractIdOrAddress}: ${error.message}`
898
- );
899
- return null;
900
- }
901
- }
902
- /**
903
- * Retrieves outstanding token airdrops sent by an account.
904
- * @param accountId The ID of the account that sent the airdrops.
905
- * @param options Optional parameters for filtering airdrops.
906
- * @returns A promise that resolves to an array of TokenAirdrop or null.
907
- */
908
- async getOutstandingTokenAirdrops(accountId, options) {
909
- this.logger.info(
910
- `Getting outstanding token airdrops sent by account ${accountId}`
219
+ const result = await sdk.inscribe(
220
+ {
221
+ ...request,
222
+ holderId: accountId
223
+ },
224
+ signer
911
225
  );
912
- let endpoint = `/api/v1/accounts/${accountId}/airdrops/outstanding`;
913
- const params = new URLSearchParams();
914
- if (options?.limit) {
915
- params.append("limit", options.limit.toString());
916
- }
917
- if (options?.order) {
918
- params.append("order", options.order);
919
- }
920
- if (options?.receiverId) {
921
- params.append("receiver.id", options.receiverId);
922
- }
923
- if (options?.serialNumber) {
924
- params.append("serialnumber", options.serialNumber);
925
- }
926
- if (options?.tokenId) {
927
- params.append("token.id", options.tokenId);
928
- }
929
- const queryString = params.toString();
930
- if (queryString) {
931
- endpoint += `?${queryString}`;
932
- }
933
- try {
934
- const response = await this._requestWithRetry(endpoint);
935
- return response.airdrops || [];
936
- } catch (error) {
937
- this.logger.error(
938
- `Error fetching outstanding token airdrops for account ${accountId}: ${error.message}`
939
- );
940
- return null;
941
- }
942
- }
943
- /**
944
- * Retrieves pending token airdrops received by an account.
945
- * @param accountId The ID of the account that received the airdrops.
946
- * @param options Optional parameters for filtering airdrops.
947
- * @returns A promise that resolves to an array of TokenAirdrop or null.
948
- */
949
- async getPendingTokenAirdrops(accountId, options) {
950
- this.logger.info(
951
- `Getting pending token airdrops received by account ${accountId}`
952
- );
953
- let endpoint = `/api/v1/accounts/${accountId}/airdrops/pending`;
954
- const params = new URLSearchParams();
955
- if (options?.limit) {
956
- params.append("limit", options.limit.toString());
957
- }
958
- if (options?.order) {
959
- params.append("order", options.order);
960
- }
961
- if (options?.senderId) {
962
- params.append("sender.id", options.senderId);
963
- }
964
- if (options?.serialNumber) {
965
- params.append("serialnumber", options.serialNumber);
966
- }
967
- if (options?.tokenId) {
968
- params.append("token.id", options.tokenId);
969
- }
970
- const queryString = params.toString();
971
- if (queryString) {
972
- endpoint += `?${queryString}`;
973
- }
974
- try {
975
- const response = await this._requestWithRetry(endpoint);
976
- return response.airdrops || [];
977
- } catch (error) {
978
- this.logger.error(
979
- `Error fetching pending token airdrops for account ${accountId}: ${error.message}`
980
- );
981
- return null;
982
- }
983
- }
984
- /**
985
- * Retrieves blocks from the network.
986
- * @param options Optional parameters for filtering blocks.
987
- * @returns A promise that resolves to an array of Block or null.
988
- */
989
- async getBlocks(options) {
990
- this.logger.info("Getting blocks from the network");
991
- let endpoint = `/api/v1/blocks`;
992
- const params = new URLSearchParams();
993
- if (options?.limit) {
994
- params.append("limit", options.limit.toString());
995
- }
996
- if (options?.order) {
997
- params.append("order", options.order);
998
- }
999
- if (options?.timestamp) {
1000
- params.append("timestamp", options.timestamp);
1001
- }
1002
- if (options?.blockNumber) {
1003
- params.append("block.number", options.blockNumber);
1004
- }
1005
- const queryString = params.toString();
1006
- if (queryString) {
1007
- endpoint += `?${queryString}`;
1008
- }
1009
- try {
1010
- const response = await this._requestWithRetry(endpoint);
1011
- return response.blocks || [];
1012
- } catch (error) {
1013
- this.logger.error(`Error fetching blocks: ${error.message}`);
1014
- return null;
1015
- }
1016
- }
1017
- /**
1018
- * Retrieves a specific block by number or hash.
1019
- * @param blockNumberOrHash The block number or hash.
1020
- * @returns A promise that resolves to a Block or null.
1021
- */
1022
- async getBlock(blockNumberOrHash) {
1023
- this.logger.info(`Getting block ${blockNumberOrHash}`);
1024
- try {
1025
- const response = await this._requestWithRetry(
1026
- `/api/v1/blocks/${blockNumberOrHash}`
1027
- );
1028
- return response;
1029
- } catch (error) {
1030
- this.logger.error(
1031
- `Error fetching block ${blockNumberOrHash}: ${error.message}`
1032
- );
1033
- return null;
1034
- }
1035
- }
1036
- /**
1037
- * Retrieves contract entities from the network.
1038
- * @param options Optional parameters for filtering contracts.
1039
- * @returns A promise that resolves to an array of ContractEntity or null.
1040
- */
1041
- async getContracts(options) {
1042
- this.logger.info("Getting contracts from the network");
1043
- let url = `/api/v1/contracts`;
1044
- const params = new URLSearchParams();
1045
- if (options?.contractId) {
1046
- params.append("contract.id", options.contractId);
1047
- }
1048
- if (options?.limit) {
1049
- params.append("limit", options.limit.toString());
1050
- }
1051
- if (options?.order) {
1052
- params.append("order", options.order);
1053
- }
1054
- const queryString = params.toString();
1055
- if (queryString) {
1056
- url += `?${queryString}`;
1057
- }
1058
- try {
1059
- const response = await this._requestWithRetry(url);
1060
- return response.contracts || [];
1061
- } catch (error) {
1062
- this.logger.error(`Error fetching contracts: ${error.message}`);
1063
- return null;
1064
- }
1065
- }
1066
- /**
1067
- * Retrieves a specific contract by ID or address.
1068
- * @param contractIdOrAddress The contract ID or EVM address.
1069
- * @param timestamp Optional timestamp for historical data.
1070
- * @returns A promise that resolves to a ContractEntity or null.
1071
- */
1072
- async getContract(contractIdOrAddress, timestamp) {
1073
- this.logger.info(`Getting contract ${contractIdOrAddress}`);
1074
- let url = `/api/v1/contracts/${contractIdOrAddress}`;
1075
- if (timestamp) {
1076
- url += `?timestamp=${timestamp}`;
1077
- }
1078
- try {
1079
- const response = await this._requestWithRetry(url);
1080
- return response;
1081
- } catch (error) {
1082
- this.logger.error(
1083
- `Error fetching contract ${contractIdOrAddress}: ${error.message}`
1084
- );
1085
- return null;
1086
- }
1087
- }
1088
- /**
1089
- * Retrieves contract results from the network.
1090
- * @param options Optional parameters for filtering contract results.
1091
- * @returns A promise that resolves to an array of ContractResult or null.
1092
- */
1093
- async getContractResults(options) {
1094
- this.logger.info("Getting contract results from the network");
1095
- let url = `/api/v1/contracts/results`;
1096
- const params = new URLSearchParams();
1097
- if (options?.from) {
1098
- params.append("from", options.from);
1099
- }
1100
- if (options?.blockHash) {
1101
- params.append("block.hash", options.blockHash);
1102
- }
1103
- if (options?.blockNumber) {
1104
- params.append("block.number", options.blockNumber);
1105
- }
1106
- if (options?.internal !== void 0) {
1107
- params.append("internal", options.internal.toString());
1108
- }
1109
- if (options?.limit) {
1110
- params.append("limit", options.limit.toString());
1111
- }
1112
- if (options?.order) {
1113
- params.append("order", options.order);
1114
- }
1115
- if (options?.timestamp) {
1116
- params.append("timestamp", options.timestamp);
1117
- }
1118
- if (options?.transactionIndex) {
1119
- params.append("transaction.index", options.transactionIndex.toString());
1120
- }
1121
- const queryString = params.toString();
1122
- if (queryString) {
1123
- url += `?${queryString}`;
1124
- }
1125
- try {
1126
- const response = await this._requestWithRetry(url);
1127
- return response.results || [];
1128
- } catch (error) {
1129
- this.logger.error(`Error fetching contract results: ${error.message}`);
1130
- return null;
1131
- }
1132
- }
1133
- /**
1134
- * Retrieves a specific contract result by transaction ID or hash.
1135
- * @param transactionIdOrHash The transaction ID or hash.
1136
- * @param nonce Optional nonce filter.
1137
- * @returns A promise that resolves to a ContractResult or null.
1138
- */
1139
- async getContractResult(transactionIdOrHash, nonce) {
1140
- this.logger.info(`Getting contract result for ${transactionIdOrHash}`);
1141
- let url = `/api/v1/contracts/results/${transactionIdOrHash}`;
1142
- if (nonce !== void 0) {
1143
- url += `?nonce=${nonce}`;
1144
- }
1145
- try {
1146
- const response = await this._requestWithRetry(url);
1147
- return response;
1148
- } catch (error) {
1149
- this.logger.error(
1150
- `Error fetching contract result for ${transactionIdOrHash}: ${error.message}`
1151
- );
1152
- return null;
1153
- }
1154
- }
1155
- /**
1156
- * Retrieves contract results for a specific contract.
1157
- * @param contractIdOrAddress The contract ID or EVM address.
1158
- * @param options Optional parameters for filtering.
1159
- * @returns A promise that resolves to an array of ContractResult or null.
1160
- */
1161
- async getContractResultsByContract(contractIdOrAddress, options) {
1162
- this.logger.info(
1163
- `Getting contract results for contract ${contractIdOrAddress}`
1164
- );
1165
- let url = `/api/v1/contracts/${contractIdOrAddress}/results`;
1166
- const params = new URLSearchParams();
1167
- if (options?.blockHash) {
1168
- params.append("block.hash", options.blockHash);
1169
- }
1170
- if (options?.blockNumber) {
1171
- params.append("block.number", options.blockNumber);
1172
- }
1173
- if (options?.from) {
1174
- params.append("from", options.from);
1175
- }
1176
- if (options?.internal !== void 0) {
1177
- params.append("internal", options.internal.toString());
1178
- }
1179
- if (options?.limit) {
1180
- params.append("limit", options.limit.toString());
1181
- }
1182
- if (options?.order) {
1183
- params.append("order", options.order);
1184
- }
1185
- if (options?.timestamp) {
1186
- params.append("timestamp", options.timestamp);
1187
- }
1188
- if (options?.transactionIndex) {
1189
- params.append("transaction.index", options.transactionIndex.toString());
1190
- }
1191
- const queryString = params.toString();
1192
- if (queryString) {
1193
- url += `?${queryString}`;
1194
- }
1195
- try {
1196
- const response = await this._requestWithRetry(url);
1197
- return response.results || [];
1198
- } catch (error) {
1199
- this.logger.error(
1200
- `Error fetching contract results for ${contractIdOrAddress}: ${error.message}`
1201
- );
1202
- return null;
1203
- }
1204
- }
1205
- /**
1206
- * Retrieves contract state for a specific contract.
1207
- * @param contractIdOrAddress The contract ID or EVM address.
1208
- * @param options Optional parameters for filtering.
1209
- * @returns A promise that resolves to an array of ContractState or null.
1210
- */
1211
- async getContractState(contractIdOrAddress, options) {
1212
- this.logger.info(`Getting contract state for ${contractIdOrAddress}`);
1213
- let url = `/api/v1/contracts/${contractIdOrAddress}/state`;
1214
- const params = new URLSearchParams();
1215
- if (options?.limit) {
1216
- params.append("limit", options.limit.toString());
1217
- }
1218
- if (options?.order) {
1219
- params.append("order", options.order);
1220
- }
1221
- if (options?.slot) {
1222
- params.append("slot", options.slot);
1223
- }
1224
- if (options?.timestamp) {
1225
- params.append("timestamp", options.timestamp);
1226
- }
1227
- const queryString = params.toString();
1228
- if (queryString) {
1229
- url += `?${queryString}`;
1230
- }
1231
- try {
1232
- const response = await this._requestWithRetry(url);
1233
- return response.state || [];
1234
- } catch (error) {
1235
- this.logger.error(
1236
- `Error fetching contract state for ${contractIdOrAddress}: ${error.message}`
1237
- );
1238
- return null;
1239
- }
1240
- }
1241
- /**
1242
- * Retrieves contract actions for a specific transaction.
1243
- * @param transactionIdOrHash The transaction ID or hash.
1244
- * @param options Optional parameters for filtering.
1245
- * @returns A promise that resolves to an array of ContractAction or null.
1246
- */
1247
- async getContractActions(transactionIdOrHash, options) {
1248
- this.logger.info(`Getting contract actions for ${transactionIdOrHash}`);
1249
- let url = `/api/v1/contracts/results/${transactionIdOrHash}/actions`;
1250
- const params = new URLSearchParams();
1251
- if (options?.index) {
1252
- params.append("index", options.index);
1253
- }
1254
- if (options?.limit) {
1255
- params.append("limit", options.limit.toString());
1256
- }
1257
- if (options?.order) {
1258
- params.append("order", options.order);
1259
- }
1260
- const queryString = params.toString();
1261
- if (queryString) {
1262
- url += `?${queryString}`;
1263
- }
1264
- try {
1265
- const response = await this._requestWithRetry(url);
1266
- return response.actions || [];
1267
- } catch (error) {
1268
- this.logger.error(
1269
- `Error fetching contract actions for ${transactionIdOrHash}: ${error.message}`
1270
- );
1271
- return null;
226
+ logger.info("Inscription started", {
227
+ type: input.type,
228
+ mode: options.mode || "file",
229
+ transactionId: result.jobId
230
+ });
231
+ if (options.waitForConfirmation) {
232
+ logger.debug("Waiting for inscription confirmation", {
233
+ transactionId: result.jobId,
234
+ maxAttempts: options.waitMaxAttempts,
235
+ intervalMs: options.waitIntervalMs
236
+ });
237
+ const inscription = await waitForInscriptionConfirmation(
238
+ sdk,
239
+ result.jobId,
240
+ options.waitMaxAttempts,
241
+ options.waitIntervalMs,
242
+ options.progressCallback
243
+ );
244
+ logger.info("Inscription confirmation received", {
245
+ transactionId: result.jobId
246
+ });
247
+ return {
248
+ confirmed: true,
249
+ result,
250
+ inscription,
251
+ sdk
252
+ };
1272
253
  }
254
+ return {
255
+ confirmed: false,
256
+ result,
257
+ sdk
258
+ };
259
+ } catch (error) {
260
+ logger.error("Error during inscription process", error);
261
+ throw error;
1273
262
  }
1274
- /**
1275
- * Retrieves contract logs from the network.
1276
- * @param options Optional parameters for filtering logs.
1277
- * @returns A promise that resolves to an array of ContractLog or null.
1278
- */
1279
- async getContractLogs(options) {
1280
- this.logger.info("Getting contract logs from the network");
1281
- let url = `/api/v1/contracts/results/logs`;
1282
- const params = new URLSearchParams();
1283
- if (options?.index) {
1284
- params.append("index", options.index);
1285
- }
1286
- if (options?.limit) {
1287
- params.append("limit", options.limit.toString());
1288
- }
1289
- if (options?.order) {
1290
- params.append("order", options.order);
1291
- }
1292
- if (options?.timestamp) {
1293
- params.append("timestamp", options.timestamp);
1294
- }
1295
- if (options?.topic0) {
1296
- params.append("topic0", options.topic0);
1297
- }
1298
- if (options?.topic1) {
1299
- params.append("topic1", options.topic1);
1300
- }
1301
- if (options?.topic2) {
1302
- params.append("topic2", options.topic2);
1303
- }
1304
- if (options?.topic3) {
1305
- params.append("topic3", options.topic3);
1306
- }
1307
- if (options?.transactionHash) {
1308
- params.append("transaction.hash", options.transactionHash);
1309
- }
1310
- const queryString = params.toString();
1311
- if (queryString) {
1312
- url += `?${queryString}`;
1313
- }
1314
- try {
1315
- const response = await this._requestWithRetry(url);
1316
- return response.logs || [];
1317
- } catch (error) {
1318
- this.logger.error(`Error fetching contract logs: ${error.message}`);
1319
- return null;
263
+ }
264
+ async function retrieveInscription(transactionId, options) {
265
+ const logger = Logger.getInstance({
266
+ module: "Inscriber",
267
+ ...options?.logging || {}
268
+ });
269
+ const formattedTransactionId = transactionId.includes("@") ? `${transactionId.split("@")[0]}-${transactionId.split("@")[1].replace(/\./g, "-")}` : transactionId;
270
+ logger.info("Retrieving inscription", {
271
+ originalTransactionId: transactionId,
272
+ formattedTransactionId
273
+ });
274
+ try {
275
+ let sdk;
276
+ if (options?.apiKey) {
277
+ logger.debug("Initializing InscriptionSDK with API key");
278
+ sdk = new InscriptionSDK({
279
+ apiKey: options.apiKey,
280
+ network: options.network || "mainnet"
281
+ });
282
+ } else if (options?.accountId && options?.privateKey) {
283
+ logger.debug("Initializing InscriptionSDK with server auth");
284
+ sdk = await InscriptionSDK.createWithAuth({
285
+ type: "server",
286
+ accountId: options.accountId,
287
+ privateKey: options.privateKey,
288
+ network: options.network || "mainnet"
289
+ });
290
+ } else {
291
+ const error = new Error(
292
+ "Either API key or account ID and private key are required for retrieving inscriptions"
293
+ );
294
+ logger.error("Missing authentication credentials", {
295
+ hasApiKey: Boolean(options?.apiKey),
296
+ hasAccountId: Boolean(options?.accountId),
297
+ hasPrivateKey: Boolean(options?.privateKey)
298
+ });
299
+ throw error;
1320
300
  }
301
+ logger.debug("Initialized SDK for inscription retrieval", {
302
+ formattedTransactionId,
303
+ network: options.network || "mainnet"
304
+ });
305
+ const result = await sdk.retrieveInscription(formattedTransactionId);
306
+ logger.info("Successfully retrieved inscription", {
307
+ formattedTransactionId
308
+ });
309
+ return result;
310
+ } catch (error) {
311
+ logger.error("Error retrieving inscription", {
312
+ formattedTransactionId,
313
+ error
314
+ });
315
+ throw error;
1321
316
  }
1322
- /**
1323
- * Retrieves contract logs for a specific contract.
1324
- * @param contractIdOrAddress The contract ID or EVM address.
1325
- * @param options Optional parameters for filtering logs.
1326
- * @returns A promise that resolves to an array of ContractLog or null.
1327
- */
1328
- async getContractLogsByContract(contractIdOrAddress, options) {
1329
- this.logger.info(
1330
- `Getting contract logs for contract ${contractIdOrAddress}`
317
+ }
318
+ function validateHashinalMetadata(metadata, logger) {
319
+ const requiredFields = ["name", "creator", "description", "type"];
320
+ const missingFields = requiredFields.filter((field) => !metadata[field]);
321
+ if (missingFields.length > 0) {
322
+ const error = new Error(
323
+ `Missing required Hashinal metadata fields: ${missingFields.join(", ")}`
1331
324
  );
1332
- let url = `/api/v1/contracts/${contractIdOrAddress}/results/logs`;
1333
- const params = new URLSearchParams();
1334
- if (options?.index) {
1335
- params.append("index", options.index);
1336
- }
1337
- if (options?.limit) {
1338
- params.append("limit", options.limit.toString());
1339
- }
1340
- if (options?.order) {
1341
- params.append("order", options.order);
1342
- }
1343
- if (options?.timestamp) {
1344
- params.append("timestamp", options.timestamp);
1345
- }
1346
- if (options?.topic0) {
1347
- params.append("topic0", options.topic0);
1348
- }
1349
- if (options?.topic1) {
1350
- params.append("topic1", options.topic1);
1351
- }
1352
- if (options?.topic2) {
1353
- params.append("topic2", options.topic2);
1354
- }
1355
- if (options?.topic3) {
1356
- params.append("topic3", options.topic3);
1357
- }
1358
- const queryString = params.toString();
1359
- if (queryString) {
1360
- url += `?${queryString}`;
1361
- }
1362
- try {
1363
- const response = await this._requestWithRetry(url);
1364
- return response.logs || [];
1365
- } catch (error) {
1366
- this.logger.error(
1367
- `Error fetching contract logs for ${contractIdOrAddress}: ${error.message}`
1368
- );
1369
- return null;
1370
- }
1371
- }
1372
- /**
1373
- * Retrieves NFT information by token ID and serial number.
1374
- * @param tokenId The token ID.
1375
- * @param serialNumber The serial number of the NFT.
1376
- * @returns A promise that resolves to an NftInfo or null.
1377
- */
1378
- async getNftInfo(tokenId, serialNumber) {
1379
- this.logger.info(`Getting NFT info for ${tokenId}/${serialNumber}`);
1380
- const url = `/api/v1/tokens/${tokenId}/nfts/${serialNumber}`;
1381
- try {
1382
- const response = await this._requestWithRetry(url);
1383
- return response;
1384
- } catch (error) {
1385
- this.logger.error(
1386
- `Error fetching NFT info for ${tokenId}/${serialNumber}: ${error.message}`
1387
- );
1388
- return null;
1389
- }
1390
- }
1391
- /**
1392
- * Retrieves NFTs for a specific token.
1393
- * @param tokenId The token ID.
1394
- * @param options Optional parameters for filtering NFTs.
1395
- * @returns A promise that resolves to an array of NftInfo or null.
1396
- */
1397
- async getNftsByToken(tokenId, options) {
1398
- this.logger.info(`Getting NFTs for token ${tokenId}`);
1399
- let url = `/api/v1/tokens/${tokenId}/nfts`;
1400
- const params = new URLSearchParams();
1401
- if (options?.accountId) {
1402
- params.append("account.id", options.accountId);
1403
- }
1404
- if (options?.limit) {
1405
- params.append("limit", options.limit.toString());
1406
- }
1407
- if (options?.order) {
1408
- params.append("order", options.order);
1409
- }
1410
- if (options?.serialNumber) {
1411
- params.append("serialnumber", options.serialNumber);
1412
- }
1413
- const queryString = params.toString();
1414
- if (queryString) {
1415
- url += `?${queryString}`;
1416
- }
1417
- try {
1418
- const response = await this._requestWithRetry(url);
1419
- return response.nfts || [];
1420
- } catch (error) {
1421
- this.logger.error(
1422
- `Error fetching NFTs for token ${tokenId}: ${error.message}`
1423
- );
1424
- return null;
1425
- }
1426
- }
1427
- /**
1428
- * Retrieves network information.
1429
- * @returns A promise that resolves to NetworkInfo or null.
1430
- */
1431
- async getNetworkInfo() {
1432
- this.logger.info("Getting network information");
1433
- const url = `/api/v1/network/nodes`;
1434
- try {
1435
- const response = await this._requestWithRetry(url);
1436
- return response;
1437
- } catch (error) {
1438
- this.logger.error(`Error fetching network info: ${error.message}`);
1439
- return null;
1440
- }
1441
- }
1442
- /**
1443
- * Retrieves network fees.
1444
- * @param timestamp Optional timestamp for historical fees.
1445
- * @returns A promise that resolves to NetworkFees or null.
1446
- */
1447
- async getNetworkFees(timestamp) {
1448
- this.logger.info("Getting network fees");
1449
- let url = `/api/v1/network/fees`;
1450
- if (timestamp) {
1451
- url += `?timestamp=${timestamp}`;
1452
- }
1453
- try {
1454
- const response = await this._requestWithRetry(url);
1455
- return response;
1456
- } catch (error) {
1457
- this.logger.error(`Error fetching network fees: ${error.message}`);
1458
- return null;
1459
- }
1460
- }
1461
- /**
1462
- * Retrieves network supply information.
1463
- * @param timestamp Optional timestamp for historical supply data.
1464
- * @returns A promise that resolves to NetworkSupply or null.
1465
- */
1466
- async getNetworkSupply(timestamp) {
1467
- this.logger.info("Getting network supply");
1468
- let url = `/api/v1/network/supply`;
1469
- if (timestamp) {
1470
- url += `?timestamp=${timestamp}`;
1471
- }
1472
- try {
1473
- const response = await this._requestWithRetry(url);
1474
- return response;
1475
- } catch (error) {
1476
- this.logger.error(`Error fetching network supply: ${error.message}`);
1477
- return null;
1478
- }
1479
- }
1480
- /**
1481
- * Retrieves network stake information.
1482
- * @param timestamp Optional timestamp for historical stake data.
1483
- * @returns A promise that resolves to NetworkStake or null.
1484
- */
1485
- async getNetworkStake(timestamp) {
1486
- this.logger.info("Getting network stake");
1487
- let url = `/api/v1/network/stake`;
1488
- if (timestamp) {
1489
- url += `?timestamp=${timestamp}`;
1490
- }
1491
- try {
1492
- const response = await this._requestWithRetry(url);
1493
- return response;
1494
- } catch (error) {
1495
- this.logger.error(`Error fetching network stake: ${error.message}`);
1496
- return null;
1497
- }
1498
- }
1499
- /**
1500
- * Retrieves opcode traces for a specific transaction.
1501
- * @param transactionIdOrHash The transaction ID or hash.
1502
- * @param options Optional parameters for trace details.
1503
- * @returns A promise that resolves to an OpcodesResponse or null.
1504
- */
1505
- async getOpcodeTraces(transactionIdOrHash, options) {
1506
- this.logger.info(`Getting opcode traces for ${transactionIdOrHash}`);
1507
- let url = `/api/v1/contracts/results/${transactionIdOrHash}/opcodes`;
1508
- const params = new URLSearchParams();
1509
- if (options?.stack !== void 0) {
1510
- params.append("stack", options.stack.toString());
1511
- }
1512
- if (options?.memory !== void 0) {
1513
- params.append("memory", options.memory.toString());
1514
- }
1515
- if (options?.storage !== void 0) {
1516
- params.append("storage", options.storage.toString());
1517
- }
1518
- const queryString = params.toString();
1519
- if (queryString) {
1520
- url += `?${queryString}`;
1521
- }
325
+ logger.error("Hashinal metadata validation failed", { missingFields });
326
+ throw error;
327
+ }
328
+ logger.debug("Hashinal metadata validation passed", {
329
+ name: metadata.name,
330
+ creator: metadata.creator,
331
+ description: metadata.description,
332
+ type: metadata.type,
333
+ hasAttributes: !!metadata.attributes,
334
+ hasProperties: !!metadata.properties
335
+ });
336
+ }
337
+ async function waitForInscriptionConfirmation(sdk, transactionId, maxAttempts = 30, intervalMs = 4e3, progressCallback) {
338
+ const logger = Logger.getInstance({ module: "Inscriber" });
339
+ const progressReporter = new ProgressReporter({
340
+ module: "Inscriber",
341
+ logger,
342
+ callback: progressCallback
343
+ });
344
+ try {
345
+ logger.debug("Waiting for inscription confirmation", {
346
+ transactionId,
347
+ maxAttempts,
348
+ intervalMs
349
+ });
350
+ progressReporter.preparing("Preparing for inscription confirmation", 5, {
351
+ transactionId,
352
+ maxAttempts,
353
+ intervalMs
354
+ });
1522
355
  try {
1523
- const response = await this._requestWithRetry(url);
1524
- return response;
1525
- } catch (error) {
1526
- this.logger.error(
1527
- `Error fetching opcode traces for ${transactionIdOrHash}: ${error.message}`
356
+ const waitMethod = sdk.waitForInscription.bind(sdk);
357
+ const wrappedCallback = (data) => {
358
+ const stage = data.stage || "confirming";
359
+ const message = data.message || "Processing inscription";
360
+ const percent = data.progressPercent || 50;
361
+ progressReporter.report({
362
+ stage,
363
+ message,
364
+ progressPercent: percent,
365
+ details: {}
366
+ });
367
+ };
368
+ return await waitMethod(
369
+ transactionId,
370
+ maxAttempts,
371
+ intervalMs,
372
+ true,
373
+ wrappedCallback
1528
374
  );
1529
- return null;
1530
- }
375
+ } catch (e) {
376
+ console.log(e);
377
+ logger.debug("Falling back to standard waitForInscription method", {
378
+ error: e
379
+ });
380
+ progressReporter.verifying("Verifying inscription status", 50, {
381
+ error: e
382
+ });
383
+ return await sdk.waitForInscription(
384
+ transactionId,
385
+ maxAttempts,
386
+ intervalMs,
387
+ true
388
+ );
389
+ }
390
+ } catch (error) {
391
+ logger.error("Error waiting for inscription confirmation", {
392
+ transactionId,
393
+ maxAttempts,
394
+ intervalMs,
395
+ error
396
+ });
397
+ progressReporter.failed("Inscription confirmation failed", {
398
+ transactionId,
399
+ error
400
+ });
401
+ throw error;
1531
402
  }
1532
403
  }
1533
404
  export {
1534
- HederaMirrorNode
405
+ inscribe,
406
+ inscribeWithSigner,
407
+ retrieveInscription,
408
+ waitForInscriptionConfirmation
1535
409
  };
1536
410
  //# sourceMappingURL=standards-sdk.es21.js.map