@neus/sdk 1.0.0 → 1.0.1

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.
package/cjs/client.cjs ADDED
@@ -0,0 +1,1686 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // client.js
20
+ var client_exports = {};
21
+ __export(client_exports, {
22
+ NeusClient: () => NeusClient,
23
+ constructVerificationMessage: () => constructVerificationMessage
24
+ });
25
+ module.exports = __toCommonJS(client_exports);
26
+
27
+ // errors.js
28
+ var SDKError = class _SDKError extends Error {
29
+ constructor(message, code = "SDK_ERROR", details = {}) {
30
+ super(message);
31
+ this.name = "SDKError";
32
+ this.code = code;
33
+ this.details = details;
34
+ this.timestamp = Date.now();
35
+ if (Error.captureStackTrace) {
36
+ Error.captureStackTrace(this, _SDKError);
37
+ }
38
+ }
39
+ toJSON() {
40
+ return {
41
+ name: this.name,
42
+ message: this.message,
43
+ code: this.code,
44
+ details: this.details,
45
+ timestamp: this.timestamp
46
+ };
47
+ }
48
+ };
49
+ var ApiError = class _ApiError extends SDKError {
50
+ constructor(message, statusCode = 500, code = "API_ERROR", response = null) {
51
+ super(message, code);
52
+ this.name = "ApiError";
53
+ this.statusCode = statusCode;
54
+ this.response = response;
55
+ this.isClientError = statusCode >= 400 && statusCode < 500;
56
+ this.isServerError = statusCode >= 500;
57
+ this.isRetryable = this.isServerError || statusCode === 429;
58
+ }
59
+ static fromResponse(response, responseData) {
60
+ const statusCode = response.status;
61
+ const message = responseData?.error?.message || responseData?.message || `API request failed with status ${statusCode}`;
62
+ const code = responseData?.error?.code || "API_ERROR";
63
+ return new _ApiError(message, statusCode, code, responseData);
64
+ }
65
+ toJSON() {
66
+ return {
67
+ ...super.toJSON(),
68
+ statusCode: this.statusCode,
69
+ isClientError: this.isClientError,
70
+ isServerError: this.isServerError,
71
+ isRetryable: this.isRetryable
72
+ };
73
+ }
74
+ };
75
+ var ValidationError = class extends SDKError {
76
+ constructor(message, field = null, value = null) {
77
+ super(message, "VALIDATION_ERROR");
78
+ this.name = "ValidationError";
79
+ this.field = field;
80
+ this.value = value;
81
+ this.isRetryable = false;
82
+ }
83
+ toJSON() {
84
+ return {
85
+ ...super.toJSON(),
86
+ field: this.field,
87
+ value: this.value,
88
+ isRetryable: this.isRetryable
89
+ };
90
+ }
91
+ };
92
+ var NetworkError = class _NetworkError extends SDKError {
93
+ constructor(message, code = "NETWORK_ERROR", originalError = null) {
94
+ super(message, code);
95
+ this.name = "NetworkError";
96
+ this.originalError = originalError;
97
+ this.isRetryable = true;
98
+ }
99
+ static isNetworkError(error) {
100
+ return error instanceof _NetworkError || error.name === "TypeError" && error.message.includes("fetch") || error.name === "AbortError" || error.code === "ENOTFOUND" || error.code === "ECONNREFUSED" || error.code === "ETIMEDOUT";
101
+ }
102
+ toJSON() {
103
+ return {
104
+ ...super.toJSON(),
105
+ isRetryable: this.isRetryable,
106
+ originalError: this.originalError ? {
107
+ name: this.originalError.name,
108
+ message: this.originalError.message,
109
+ code: this.originalError.code
110
+ } : null
111
+ };
112
+ }
113
+ };
114
+ var ConfigurationError = class extends SDKError {
115
+ constructor(message, configKey = null) {
116
+ super(message, "CONFIGURATION_ERROR");
117
+ this.name = "ConfigurationError";
118
+ this.configKey = configKey;
119
+ this.isRetryable = false;
120
+ }
121
+ toJSON() {
122
+ return {
123
+ ...super.toJSON(),
124
+ configKey: this.configKey,
125
+ isRetryable: this.isRetryable
126
+ };
127
+ }
128
+ };
129
+
130
+ // utils.js
131
+ function deterministicStringify(obj) {
132
+ if (obj === null || obj === void 0) {
133
+ return JSON.stringify(obj);
134
+ }
135
+ if (typeof obj !== "object") {
136
+ return JSON.stringify(obj);
137
+ }
138
+ if (Array.isArray(obj)) {
139
+ return "[" + obj.map((item) => deterministicStringify(item)).join(",") + "]";
140
+ }
141
+ const sortedKeys = Object.keys(obj).sort();
142
+ const pairs = sortedKeys.map(
143
+ (key) => JSON.stringify(key) + ":" + deterministicStringify(obj[key])
144
+ );
145
+ return "{" + pairs.join(",") + "}";
146
+ }
147
+ function constructVerificationMessage({ walletAddress, signedTimestamp, data, verifierIds, chainId, chain }) {
148
+ if (!walletAddress || typeof walletAddress !== "string") {
149
+ throw new SDKError("walletAddress is required and must be a string", "INVALID_WALLET_ADDRESS");
150
+ }
151
+ if (!signedTimestamp || typeof signedTimestamp !== "number") {
152
+ throw new SDKError("signedTimestamp is required and must be a number", "INVALID_TIMESTAMP");
153
+ }
154
+ if (!data || typeof data !== "object") {
155
+ throw new SDKError("data is required and must be an object", "INVALID_DATA");
156
+ }
157
+ if (!Array.isArray(verifierIds) || verifierIds.length === 0) {
158
+ throw new SDKError("verifierIds is required and must be a non-empty array", "INVALID_VERIFIER_IDS");
159
+ }
160
+ const chainContext = typeof chain === "string" && chain.length > 0 ? chain : chainId;
161
+ if (!chainContext) {
162
+ throw new SDKError("chainId is required (or provide chain for preview mode)", "INVALID_CHAIN_CONTEXT");
163
+ }
164
+ if (chainContext === chainId && typeof chainId !== "number") {
165
+ throw new SDKError("chainId must be a number when provided", "INVALID_CHAIN_ID");
166
+ }
167
+ if (chainContext === chain && (typeof chain !== "string" || !chain.includes(":"))) {
168
+ throw new SDKError('chain must be a "namespace:reference" string', "INVALID_CHAIN");
169
+ }
170
+ const namespace = typeof chain === "string" && chain.includes(":") ? chain.split(":")[0] : "eip155";
171
+ const normalizedWalletAddress = namespace === "eip155" ? walletAddress.toLowerCase() : walletAddress;
172
+ const dataString = deterministicStringify(data);
173
+ const messageComponents = [
174
+ "NEUS Verification Request",
175
+ `Wallet: ${normalizedWalletAddress}`,
176
+ `Chain: ${chainContext}`,
177
+ `Verifiers: ${verifierIds.join(",")}`,
178
+ `Data: ${dataString}`,
179
+ `Timestamp: ${signedTimestamp}`
180
+ ];
181
+ return messageComponents.join("\n");
182
+ }
183
+ function validateWalletAddress(address) {
184
+ if (!address || typeof address !== "string") {
185
+ return false;
186
+ }
187
+ return /^0x[a-fA-F0-9]{40}$/.test(address);
188
+ }
189
+ var NEUS_CONSTANTS = {
190
+ // Hub chain (where all verifications occur)
191
+ HUB_CHAIN_ID: 84532,
192
+ // Supported target chains for cross-chain propagation
193
+ TESTNET_CHAINS: [
194
+ 11155111,
195
+ // Ethereum Sepolia
196
+ 11155420,
197
+ // Optimism Sepolia
198
+ 421614,
199
+ // Arbitrum Sepolia
200
+ 80002
201
+ // Polygon Amoy
202
+ ],
203
+ // API endpoints
204
+ API_BASE_URL: "https://api.neus.network",
205
+ API_VERSION: "v1",
206
+ // Timeouts and limits
207
+ SIGNATURE_MAX_AGE_MS: 5 * 60 * 1e3,
208
+ // 5 minutes
209
+ REQUEST_TIMEOUT_MS: 30 * 1e3,
210
+ // 30 seconds
211
+ // Default verifier set for quick starts
212
+ DEFAULT_VERIFIERS: [
213
+ "ownership-basic",
214
+ "nft-ownership",
215
+ "token-holding"
216
+ ]
217
+ };
218
+
219
+ // client.js
220
+ var validateVerifierData = (verifierId, data) => {
221
+ if (!data || typeof data !== "object") {
222
+ return { valid: false, error: "Data object is required" };
223
+ }
224
+ const ownerField = verifierId === "nft-ownership" || verifierId === "token-holding" ? "ownerAddress" : "owner";
225
+ if (data[ownerField] && !validateWalletAddress(data[ownerField])) {
226
+ return { valid: false, error: `Invalid ${ownerField} address` };
227
+ }
228
+ switch (verifierId) {
229
+ case "ownership-basic":
230
+ if (!data.owner || !validateWalletAddress(data.owner)) {
231
+ return { valid: false, error: "owner (wallet address) is required" };
232
+ }
233
+ if (data.reference !== void 0) {
234
+ if (!data.reference || typeof data.reference !== "object") {
235
+ return { valid: false, error: "reference must be an object when provided" };
236
+ }
237
+ if (!data.reference.type || typeof data.reference.type !== "string") {
238
+ return { valid: false, error: "reference.type is required when reference is provided" };
239
+ }
240
+ }
241
+ if (!data.content && !data.contentHash) {
242
+ if (!data.reference || typeof data.reference !== "object") {
243
+ return { valid: false, error: "reference is required when neither content nor contentHash is provided" };
244
+ }
245
+ if (!data.reference.id || typeof data.reference.id !== "string") {
246
+ return { valid: false, error: "reference.id is required when neither content nor contentHash is provided" };
247
+ }
248
+ if (!data.reference.type || typeof data.reference.type !== "string") {
249
+ return { valid: false, error: "reference.type is required when neither content nor contentHash is provided" };
250
+ }
251
+ }
252
+ break;
253
+ case "nft-ownership":
254
+ if (!data.contractAddress || data.tokenId === null || data.tokenId === void 0 || typeof data.chainId !== "number") {
255
+ return { valid: false, error: "contractAddress, tokenId, and chainId are required" };
256
+ }
257
+ if (data.tokenType !== void 0 && data.tokenType !== null) {
258
+ const tt = String(data.tokenType).toLowerCase();
259
+ if (tt !== "erc721" && tt !== "erc1155") {
260
+ return { valid: false, error: "tokenType must be one of: erc721, erc1155" };
261
+ }
262
+ }
263
+ if (data.blockNumber !== void 0 && data.blockNumber !== null && !Number.isInteger(data.blockNumber)) {
264
+ return { valid: false, error: "blockNumber must be an integer when provided" };
265
+ }
266
+ if (data.ownerAddress && !validateWalletAddress(data.ownerAddress)) {
267
+ return { valid: false, error: "Invalid ownerAddress" };
268
+ }
269
+ if (!validateWalletAddress(data.contractAddress)) {
270
+ return { valid: false, error: "Invalid contractAddress" };
271
+ }
272
+ break;
273
+ case "token-holding":
274
+ if (!data.contractAddress || data.minBalance === null || data.minBalance === void 0 || typeof data.chainId !== "number") {
275
+ return { valid: false, error: "contractAddress, minBalance, and chainId are required" };
276
+ }
277
+ if (data.blockNumber !== void 0 && data.blockNumber !== null && !Number.isInteger(data.blockNumber)) {
278
+ return { valid: false, error: "blockNumber must be an integer when provided" };
279
+ }
280
+ if (data.ownerAddress && !validateWalletAddress(data.ownerAddress)) {
281
+ return { valid: false, error: "Invalid ownerAddress" };
282
+ }
283
+ if (!validateWalletAddress(data.contractAddress)) {
284
+ return { valid: false, error: "Invalid contractAddress" };
285
+ }
286
+ break;
287
+ case "ownership-dns-txt":
288
+ if (!data.domain || typeof data.domain !== "string") {
289
+ return { valid: false, error: "domain is required" };
290
+ }
291
+ if (data.walletAddress && !validateWalletAddress(data.walletAddress)) {
292
+ return { valid: false, error: "Invalid walletAddress" };
293
+ }
294
+ break;
295
+ case "wallet-link":
296
+ if (!data.primaryWalletAddress || !validateWalletAddress(data.primaryWalletAddress)) {
297
+ return { valid: false, error: "primaryWalletAddress is required" };
298
+ }
299
+ if (!data.secondaryWalletAddress || !validateWalletAddress(data.secondaryWalletAddress)) {
300
+ return { valid: false, error: "secondaryWalletAddress is required" };
301
+ }
302
+ if (!data.signature || typeof data.signature !== "string") {
303
+ return { valid: false, error: "signature is required (signed by secondary wallet)" };
304
+ }
305
+ if (typeof data.chainId !== "number") {
306
+ return { valid: false, error: "chainId is required" };
307
+ }
308
+ if (typeof data.signedTimestamp !== "number") {
309
+ return { valid: false, error: "signedTimestamp is required" };
310
+ }
311
+ break;
312
+ case "contract-ownership":
313
+ if (!data.contractAddress || !validateWalletAddress(data.contractAddress)) {
314
+ return { valid: false, error: "contractAddress is required" };
315
+ }
316
+ if (data.walletAddress && !validateWalletAddress(data.walletAddress)) {
317
+ return { valid: false, error: "Invalid walletAddress" };
318
+ }
319
+ if (typeof data.chainId !== "number") {
320
+ return { valid: false, error: "chainId is required" };
321
+ }
322
+ break;
323
+ case "agent-identity":
324
+ if (!data.agentId || typeof data.agentId !== "string" || data.agentId.length < 1 || data.agentId.length > 128) {
325
+ return { valid: false, error: "agentId is required (1-128 chars)" };
326
+ }
327
+ if (!data.agentWallet || !validateWalletAddress(data.agentWallet)) {
328
+ return { valid: false, error: "agentWallet is required" };
329
+ }
330
+ if (data.agentType && !["ai", "bot", "service", "automation", "agent"].includes(data.agentType)) {
331
+ return { valid: false, error: "agentType must be one of: ai, bot, service, automation, agent" };
332
+ }
333
+ break;
334
+ case "agent-delegation":
335
+ if (!data.controllerWallet || !validateWalletAddress(data.controllerWallet)) {
336
+ return { valid: false, error: "controllerWallet is required" };
337
+ }
338
+ if (!data.agentWallet || !validateWalletAddress(data.agentWallet)) {
339
+ return { valid: false, error: "agentWallet is required" };
340
+ }
341
+ if (data.scope && (typeof data.scope !== "string" || data.scope.length > 128)) {
342
+ return { valid: false, error: "scope must be a string (max 128 chars)" };
343
+ }
344
+ if (data.expiresAt && (typeof data.expiresAt !== "number" || data.expiresAt < Date.now())) {
345
+ return { valid: false, error: "expiresAt must be a future timestamp" };
346
+ }
347
+ break;
348
+ case "ai-content-moderation":
349
+ if (!data.content || typeof data.content !== "string") {
350
+ return { valid: false, error: "content is required" };
351
+ }
352
+ if (!data.contentType || typeof data.contentType !== "string") {
353
+ return { valid: false, error: "contentType (MIME type) is required" };
354
+ }
355
+ {
356
+ const contentType = String(data.contentType).split(";")[0].trim().toLowerCase();
357
+ const validTypes = [
358
+ "image/jpeg",
359
+ "image/png",
360
+ "image/webp",
361
+ "image/gif",
362
+ "text/plain",
363
+ "text/markdown",
364
+ "text/x-markdown",
365
+ "application/json",
366
+ "application/xml"
367
+ ];
368
+ if (!validTypes.includes(contentType)) {
369
+ return { valid: false, error: `contentType must be one of: ${validTypes.join(", ")}` };
370
+ }
371
+ }
372
+ if (data.content.length > 13653334) {
373
+ return { valid: false, error: "content exceeds 10MB limit" };
374
+ }
375
+ break;
376
+ case "ownership-pseudonym":
377
+ if (!data.pseudonymId || typeof data.pseudonymId !== "string") {
378
+ return { valid: false, error: "pseudonymId is required" };
379
+ }
380
+ if (!/^[a-z0-9._-]{3,64}$/.test(data.pseudonymId.trim().toLowerCase())) {
381
+ return { valid: false, error: "pseudonymId must be 3-64 characters, lowercase alphanumeric with dots, underscores, or hyphens" };
382
+ }
383
+ if (data.namespace && typeof data.namespace === "string") {
384
+ if (!/^[a-z0-9._-]{1,64}$/.test(data.namespace.trim().toLowerCase())) {
385
+ return { valid: false, error: "namespace must be 1-64 characters, lowercase alphanumeric with dots, underscores, or hyphens" };
386
+ }
387
+ }
388
+ break;
389
+ case "wallet-risk":
390
+ if (data.walletAddress && !validateWalletAddress(data.walletAddress)) {
391
+ return { valid: false, error: "Invalid walletAddress" };
392
+ }
393
+ break;
394
+ }
395
+ return { valid: true };
396
+ };
397
+ var NeusClient = class {
398
+ constructor(config = {}) {
399
+ this.config = {
400
+ timeout: 3e4,
401
+ enableLogging: false,
402
+ ...config
403
+ };
404
+ this.baseUrl = this.config.apiUrl || "https://api.neus.network";
405
+ try {
406
+ const url = new URL(this.baseUrl);
407
+ if (url.hostname.endsWith("neus.network") && url.protocol === "http:") {
408
+ url.protocol = "https:";
409
+ }
410
+ this.baseUrl = url.toString().replace(/\/$/, "");
411
+ } catch {
412
+ }
413
+ this.config.apiUrl = this.baseUrl;
414
+ this.defaultHeaders = {
415
+ "Content-Type": "application/json",
416
+ "Accept": "application/json",
417
+ "X-Neus-Sdk": "js"
418
+ };
419
+ if (typeof this.config.apiKey === "string" && this.config.apiKey.trim().length > 0) {
420
+ this.defaultHeaders["Authorization"] = `Bearer ${this.config.apiKey.trim()}`;
421
+ }
422
+ try {
423
+ if (typeof window !== "undefined" && window.location && window.location.origin) {
424
+ this.defaultHeaders["X-Client-Origin"] = window.location.origin;
425
+ }
426
+ } catch {
427
+ }
428
+ }
429
+ // ============================================================================
430
+ // CORE VERIFICATION METHODS
431
+ // ============================================================================
432
+ /**
433
+ * VERIFY - Standard verification (auto or manual)
434
+ *
435
+ * Create proofs with complete control over the verification process.
436
+ * If signature and walletAddress are omitted but verifier/content are provided,
437
+ * this method performs the wallet flow inline (no aliases, no secondary methods).
438
+ *
439
+ * @param {Object} params - Verification parameters
440
+ * @param {Array<string>} [params.verifierIds] - Array of verifier IDs (manual path)
441
+ * @param {Object} [params.data] - Verification data object (manual path)
442
+ * @param {string} [params.walletAddress] - Wallet address that signed the request (manual path)
443
+ * @param {string} [params.signature] - EIP-191 signature (manual path)
444
+ * @param {number} [params.signedTimestamp] - Unix timestamp when signature was created (manual path)
445
+ * @param {number} [params.chainId] - Chain ID for verification context (optional, managed by protocol)
446
+ * @param {Object} [params.options] - Additional options
447
+ * @param {string} [params.verifier] - Verifier ID (auto path)
448
+ * @param {string} [params.content] - Content/description (auto path)
449
+ * @param {Object} [params.wallet] - Optional injected wallet/provider (auto path)
450
+ * @returns {Promise<Object>} Verification result with qHash
451
+ *
452
+ * @example
453
+ * const proof = await client.verify({
454
+ * verifierIds: ['ownership-basic'],
455
+ * data: {
456
+ * content: "My content",
457
+ * owner: walletAddress, // or ownerAddress for nft-ownership/token-holding
458
+ * reference: { type: 'content', id: 'my-unique-identifier' }
459
+ * },
460
+ * walletAddress: '0x...',
461
+ * signature: '0x...',
462
+ * signedTimestamp: Date.now(),
463
+ * options: { targetChains: [421614, 11155111] }
464
+ * });
465
+ */
466
+ /**
467
+ * Create a verification proof
468
+ *
469
+ * @param {Object} params - Verification parameters
470
+ * @param {string} [params.verifier] - Verifier ID (e.g., 'ownership-basic')
471
+ * @param {string} [params.content] - Content to verify
472
+ * @param {Object} [params.data] - Structured verification data
473
+ * @param {Object} [params.wallet] - Wallet provider
474
+ * @param {Object} [params.options] - Additional options
475
+ * @returns {Promise<Object>} Verification result with qHash
476
+ *
477
+ * @example
478
+ * // Simple ownership proof
479
+ * const proof = await client.verify({
480
+ * verifier: 'ownership-basic',
481
+ * content: 'Hello World',
482
+ * wallet: window.ethereum
483
+ * });
484
+ */
485
+ async verify(params) {
486
+ if ((!params?.signature || !params?.walletAddress) && (params?.verifier || params?.content || params?.data)) {
487
+ const { content, verifier = "ownership-basic", data: data2 = null, wallet = null, options: options2 = {} } = params;
488
+ if (verifier === "ownership-basic" && !data2 && (!content || typeof content !== "string")) {
489
+ throw new ValidationError("content is required and must be a string (or use data param with owner + reference)");
490
+ }
491
+ const validVerifiers = [
492
+ "ownership-basic",
493
+ "ownership-pseudonym",
494
+ // Pseudonymous identity (public)
495
+ "nft-ownership",
496
+ "token-holding",
497
+ "ownership-dns-txt",
498
+ "wallet-link",
499
+ "contract-ownership",
500
+ "wallet-risk",
501
+ // Wallet risk assessment (public)
502
+ // AI & Agent verifiers (ERC-8004 aligned)
503
+ "agent-identity",
504
+ "agent-delegation",
505
+ "ai-content-moderation"
506
+ ];
507
+ if (!validVerifiers.includes(verifier)) {
508
+ throw new ValidationError(`Invalid verifier '${verifier}'. Must be one of: ${validVerifiers.join(", ")}.`);
509
+ }
510
+ const requiresDataParam = [
511
+ "ownership-dns-txt",
512
+ "wallet-link",
513
+ "contract-ownership",
514
+ "ownership-pseudonym",
515
+ "wallet-risk",
516
+ "agent-identity",
517
+ "agent-delegation",
518
+ "ai-content-moderation"
519
+ ];
520
+ if (requiresDataParam.includes(verifier)) {
521
+ if (!data2 || typeof data2 !== "object") {
522
+ throw new ValidationError(`${verifier} requires explicit data parameter. Cannot use auto-path.`);
523
+ }
524
+ }
525
+ let walletAddress2, provider;
526
+ if (wallet) {
527
+ walletAddress2 = wallet.address || wallet.selectedAddress;
528
+ provider = wallet.provider || wallet;
529
+ } else {
530
+ if (typeof window === "undefined" || !window.ethereum) {
531
+ throw new ConfigurationError("No Web3 wallet detected. Please install MetaMask or provide wallet parameter.");
532
+ }
533
+ await window.ethereum.request({ method: "eth_requestAccounts" });
534
+ provider = window.ethereum;
535
+ const accounts = await provider.request({ method: "eth_accounts" });
536
+ walletAddress2 = accounts[0];
537
+ }
538
+ let verificationData;
539
+ if (verifier === "ownership-basic") {
540
+ if (data2 && typeof data2 === "object") {
541
+ verificationData = {
542
+ owner: data2.owner || walletAddress2,
543
+ reference: data2.reference,
544
+ ...data2.content && { content: data2.content },
545
+ ...data2.contentHash && { contentHash: data2.contentHash },
546
+ ...data2.provenance && { provenance: data2.provenance }
547
+ };
548
+ } else {
549
+ verificationData = {
550
+ content,
551
+ owner: walletAddress2,
552
+ reference: { type: "other" }
553
+ };
554
+ }
555
+ } else if (verifier === "token-holding") {
556
+ if (!data2?.contractAddress) {
557
+ throw new ValidationError("token-holding requires contractAddress in data parameter");
558
+ }
559
+ if (data2?.minBalance === null || data2?.minBalance === void 0) {
560
+ throw new ValidationError("token-holding requires minBalance in data parameter");
561
+ }
562
+ if (typeof data2?.chainId !== "number") {
563
+ throw new ValidationError("token-holding requires chainId (number) in data parameter");
564
+ }
565
+ verificationData = {
566
+ ownerAddress: walletAddress2,
567
+ contractAddress: data2.contractAddress,
568
+ minBalance: data2.minBalance,
569
+ chainId: data2.chainId
570
+ };
571
+ } else if (verifier === "nft-ownership") {
572
+ if (!data2?.contractAddress) {
573
+ throw new ValidationError("nft-ownership requires contractAddress in data parameter");
574
+ }
575
+ if (data2?.tokenId === null || data2?.tokenId === void 0) {
576
+ throw new ValidationError("nft-ownership requires tokenId in data parameter");
577
+ }
578
+ if (typeof data2?.chainId !== "number") {
579
+ throw new ValidationError("nft-ownership requires chainId (number) in data parameter");
580
+ }
581
+ verificationData = {
582
+ ownerAddress: walletAddress2,
583
+ contractAddress: data2.contractAddress,
584
+ tokenId: data2.tokenId,
585
+ chainId: data2.chainId,
586
+ tokenType: data2?.tokenType || "erc721"
587
+ };
588
+ } else if (verifier === "ownership-dns-txt") {
589
+ if (!data2?.domain) {
590
+ throw new ValidationError("ownership-dns-txt requires domain in data parameter");
591
+ }
592
+ verificationData = {
593
+ domain: data2.domain,
594
+ walletAddress: walletAddress2
595
+ };
596
+ } else if (verifier === "wallet-link") {
597
+ if (!data2?.secondaryWalletAddress) {
598
+ throw new ValidationError("wallet-link requires secondaryWalletAddress in data parameter");
599
+ }
600
+ if (!data2?.signature) {
601
+ throw new ValidationError("wallet-link requires signature in data parameter (signed by secondary wallet)");
602
+ }
603
+ if (typeof data2?.chainId !== "number") {
604
+ throw new ValidationError("wallet-link requires chainId (number) in data parameter");
605
+ }
606
+ verificationData = {
607
+ primaryWalletAddress: walletAddress2,
608
+ secondaryWalletAddress: data2.secondaryWalletAddress,
609
+ signature: data2.signature,
610
+ chainId: data2.chainId,
611
+ signedTimestamp: data2?.signedTimestamp || Date.now()
612
+ };
613
+ } else if (verifier === "contract-ownership") {
614
+ if (!data2?.contractAddress) {
615
+ throw new ValidationError("contract-ownership requires contractAddress in data parameter");
616
+ }
617
+ if (typeof data2?.chainId !== "number") {
618
+ throw new ValidationError("contract-ownership requires chainId (number) in data parameter");
619
+ }
620
+ verificationData = {
621
+ contractAddress: data2.contractAddress,
622
+ walletAddress: walletAddress2,
623
+ chainId: data2.chainId,
624
+ ...data2?.method && { method: data2.method }
625
+ };
626
+ } else if (verifier === "agent-identity") {
627
+ if (!data2?.agentId) {
628
+ throw new ValidationError("agent-identity requires agentId in data parameter");
629
+ }
630
+ verificationData = {
631
+ agentId: data2.agentId,
632
+ agentWallet: data2?.agentWallet || walletAddress2,
633
+ ...data2?.agentLabel && { agentLabel: data2.agentLabel },
634
+ ...data2?.agentType && { agentType: data2.agentType },
635
+ ...data2?.description && { description: data2.description },
636
+ ...data2?.capabilities && { capabilities: data2.capabilities }
637
+ };
638
+ } else if (verifier === "agent-delegation") {
639
+ if (!data2?.agentWallet) {
640
+ throw new ValidationError("agent-delegation requires agentWallet in data parameter");
641
+ }
642
+ verificationData = {
643
+ controllerWallet: data2?.controllerWallet || walletAddress2,
644
+ agentWallet: data2.agentWallet,
645
+ ...data2?.agentId && { agentId: data2.agentId },
646
+ ...data2?.scope && { scope: data2.scope },
647
+ ...data2?.permissions && { permissions: data2.permissions },
648
+ ...data2?.maxSpend && { maxSpend: data2.maxSpend },
649
+ ...data2?.expiresAt && { expiresAt: data2.expiresAt }
650
+ };
651
+ } else if (verifier === "ai-content-moderation") {
652
+ if (!data2?.content) {
653
+ throw new ValidationError("ai-content-moderation requires content (base64) in data parameter");
654
+ }
655
+ if (!data2?.contentType) {
656
+ throw new ValidationError("ai-content-moderation requires contentType (MIME type) in data parameter");
657
+ }
658
+ verificationData = {
659
+ content: data2.content,
660
+ contentType: data2.contentType,
661
+ ...data2?.provider && { provider: data2.provider }
662
+ };
663
+ } else if (verifier === "ownership-pseudonym") {
664
+ if (!data2?.pseudonymId) {
665
+ throw new ValidationError("ownership-pseudonym requires pseudonymId in data parameter");
666
+ }
667
+ verificationData = {
668
+ pseudonymId: data2.pseudonymId,
669
+ ...data2?.namespace && { namespace: data2.namespace },
670
+ ...data2?.displayName && { displayName: data2.displayName },
671
+ ...data2?.metadata && { metadata: data2.metadata }
672
+ };
673
+ } else if (verifier === "wallet-risk") {
674
+ verificationData = {
675
+ walletAddress: data2?.walletAddress || walletAddress2,
676
+ ...data2?.provider && { provider: data2.provider },
677
+ // Mainnet-first semantics: if caller doesn't provide chainId, default to Ethereum mainnet (1).
678
+ // This avoids accidental testnet semantics for risk providers.
679
+ chainId: typeof data2?.chainId === "number" && Number.isFinite(data2.chainId) ? data2.chainId : 1,
680
+ ...data2?.includeDetails !== void 0 && { includeDetails: data2.includeDetails }
681
+ };
682
+ } else {
683
+ verificationData = data2 ? {
684
+ content,
685
+ owner: walletAddress2,
686
+ ...data2
687
+ } : {
688
+ content,
689
+ owner: walletAddress2
690
+ };
691
+ }
692
+ const signedTimestamp2 = Date.now();
693
+ const verifierIds2 = [verifier];
694
+ const message = constructVerificationMessage({
695
+ walletAddress: walletAddress2,
696
+ signedTimestamp: signedTimestamp2,
697
+ data: verificationData,
698
+ verifierIds: verifierIds2,
699
+ chainId: NEUS_CONSTANTS.HUB_CHAIN_ID
700
+ // Protocol-managed chain
701
+ });
702
+ let signature2;
703
+ try {
704
+ const toHexUtf8 = (s) => {
705
+ try {
706
+ const enc = new TextEncoder();
707
+ const bytes = enc.encode(s);
708
+ let hex = "0x";
709
+ for (let i = 0; i < bytes.length; i++)
710
+ hex += bytes[i].toString(16).padStart(2, "0");
711
+ return hex;
712
+ } catch {
713
+ let hex = "0x";
714
+ for (let i = 0; i < s.length; i++)
715
+ hex += s.charCodeAt(i).toString(16).padStart(2, "0");
716
+ return hex;
717
+ }
718
+ };
719
+ const isFarcasterWallet = (() => {
720
+ if (typeof window === "undefined")
721
+ return false;
722
+ try {
723
+ const w = window;
724
+ const fc = w.farcaster;
725
+ if (!fc || !fc.context)
726
+ return false;
727
+ const fcProvider = fc.provider || fc.walletProvider || fc.context && fc.context.walletProvider;
728
+ if (fcProvider === provider)
729
+ return true;
730
+ if (w.mini && w.mini.wallet === provider && fc && fc.context)
731
+ return true;
732
+ if (w.ethereum === provider && fc && fc.context)
733
+ return true;
734
+ } catch {
735
+ }
736
+ return false;
737
+ })();
738
+ if (isFarcasterWallet) {
739
+ try {
740
+ const hexMsg = toHexUtf8(message);
741
+ signature2 = await provider.request({ method: "personal_sign", params: [hexMsg, walletAddress2] });
742
+ } catch (e) {
743
+ }
744
+ }
745
+ if (!signature2) {
746
+ try {
747
+ signature2 = await provider.request({ method: "personal_sign", params: [message, walletAddress2] });
748
+ } catch (e) {
749
+ const msg = String(e && (e.message || e.reason) || e || "").toLowerCase();
750
+ const errCode = e && (e.code || e.error && e.error.code) || null;
751
+ const needsHex = /byte|bytes|invalid byte sequence|encoding|non-hex/i.test(msg);
752
+ const methodUnsupported = /method.*not.*supported|unsupported|not implemented|method not found|unknown method|does not support/i.test(msg) || errCode === -32601 || errCode === 4200 || msg.includes("personal_sign") && msg.includes("not") || msg.includes("request method") && msg.includes("not supported");
753
+ if (methodUnsupported) {
754
+ this._log("personal_sign not supported; attempting eth_sign fallback");
755
+ try {
756
+ const enc = new TextEncoder();
757
+ const bytes = enc.encode(message);
758
+ const prefix = `Ethereum Signed Message:
759
+ ${bytes.length}`;
760
+ const full = new Uint8Array(prefix.length + bytes.length);
761
+ for (let i = 0; i < prefix.length; i++)
762
+ full[i] = prefix.charCodeAt(i);
763
+ full.set(bytes, prefix.length);
764
+ let payloadHex = "0x";
765
+ for (let i = 0; i < full.length; i++)
766
+ payloadHex += full[i].toString(16).padStart(2, "0");
767
+ try {
768
+ if (typeof window !== "undefined")
769
+ window.__NEUS_ALLOW_ETH_SIGN__ = true;
770
+ } catch {
771
+ }
772
+ signature2 = await provider.request({ method: "eth_sign", params: [walletAddress2, payloadHex], neusAllowEthSign: true });
773
+ try {
774
+ if (typeof window !== "undefined")
775
+ delete window.__NEUS_ALLOW_ETH_SIGN__;
776
+ } catch {
777
+ }
778
+ } catch (fallbackErr) {
779
+ this._log("eth_sign fallback failed", { message: fallbackErr?.message || String(fallbackErr) });
780
+ try {
781
+ if (typeof window !== "undefined")
782
+ delete window.__NEUS_ALLOW_ETH_SIGN__;
783
+ } catch {
784
+ }
785
+ throw e;
786
+ }
787
+ } else if (needsHex) {
788
+ this._log("Retrying personal_sign with hex-encoded message");
789
+ const hexMsg = toHexUtf8(message);
790
+ signature2 = await provider.request({ method: "personal_sign", params: [hexMsg, walletAddress2] });
791
+ } else {
792
+ throw e;
793
+ }
794
+ }
795
+ }
796
+ } catch (error) {
797
+ if (error.code === 4001) {
798
+ throw new ValidationError("User rejected the signature request. Signature is required to create proofs.");
799
+ }
800
+ throw new ValidationError(`Failed to sign verification message: ${error.message}`);
801
+ }
802
+ return this.verify({
803
+ verifierIds: verifierIds2,
804
+ data: verificationData,
805
+ walletAddress: walletAddress2,
806
+ signature: signature2,
807
+ signedTimestamp: signedTimestamp2,
808
+ options: options2
809
+ });
810
+ }
811
+ const {
812
+ verifierIds,
813
+ data,
814
+ walletAddress,
815
+ signature,
816
+ signedTimestamp,
817
+ chainId,
818
+ chain,
819
+ signatureMethod,
820
+ options = {}
821
+ } = params;
822
+ const resolvedChainId = chainId || (chain ? null : NEUS_CONSTANTS.HUB_CHAIN_ID);
823
+ const normalizeVerifierId = (id) => {
824
+ if (typeof id !== "string")
825
+ return id;
826
+ const match = id.match(/^(.*)@\d+$/);
827
+ return match ? match[1] : id;
828
+ };
829
+ const normalizedVerifierIds = Array.isArray(verifierIds) ? verifierIds.map(normalizeVerifierId) : [];
830
+ if (!normalizedVerifierIds || normalizedVerifierIds.length === 0) {
831
+ throw new ValidationError("verifierIds array is required");
832
+ }
833
+ if (!data || typeof data !== "object") {
834
+ throw new ValidationError("data object is required");
835
+ }
836
+ if (!walletAddress || typeof walletAddress !== "string") {
837
+ throw new ValidationError("walletAddress is required");
838
+ }
839
+ if (!signature) {
840
+ throw new ValidationError("signature is required");
841
+ }
842
+ if (!signedTimestamp || typeof signedTimestamp !== "number") {
843
+ throw new ValidationError("signedTimestamp is required");
844
+ }
845
+ if (resolvedChainId !== null && typeof resolvedChainId !== "number") {
846
+ throw new ValidationError("chainId must be a number");
847
+ }
848
+ for (const verifierId of normalizedVerifierIds) {
849
+ const validation = validateVerifierData(verifierId, data);
850
+ if (!validation.valid) {
851
+ throw new ValidationError(`Validation failed for verifier '${verifierId}': ${validation.error}`);
852
+ }
853
+ }
854
+ const optionsPayload = {
855
+ ...options && typeof options === "object" ? options : {},
856
+ targetChains: Array.isArray(options?.targetChains) ? options.targetChains : [],
857
+ // Privacy and storage options (defaults)
858
+ privacyLevel: options?.privacyLevel || "private",
859
+ publicDisplay: options?.publicDisplay || false,
860
+ storeOriginalContent: options?.storeOriginalContent || false
861
+ };
862
+ if (typeof options?.enableIpfs === "boolean")
863
+ optionsPayload.enableIpfs = options.enableIpfs;
864
+ const requestData = {
865
+ verifierIds: normalizedVerifierIds,
866
+ data,
867
+ walletAddress,
868
+ signature,
869
+ signedTimestamp,
870
+ ...resolvedChainId !== null && { chainId: resolvedChainId },
871
+ ...chain && { chain },
872
+ ...signatureMethod && { signatureMethod },
873
+ options: optionsPayload
874
+ };
875
+ const response = await this._makeRequest("POST", "/api/v1/verification", requestData);
876
+ if (!response.success) {
877
+ throw new ApiError(`Verification failed: ${response.error?.message || "Unknown error"}`, response.error);
878
+ }
879
+ return this._formatResponse(response);
880
+ }
881
+ // ============================================================================
882
+ // STATUS AND UTILITY METHODS
883
+ // ============================================================================
884
+ /**
885
+ * Get verification status
886
+ *
887
+ * @param {string} qHash - Verification ID (qHash or proofId)
888
+ * @returns {Promise<Object>} Verification status and data
889
+ *
890
+ * @example
891
+ * const result = await client.getStatus('0x...');
892
+ * console.log('Status:', result.status);
893
+ */
894
+ async getStatus(qHash) {
895
+ if (!qHash || typeof qHash !== "string") {
896
+ throw new ValidationError("qHash is required");
897
+ }
898
+ const response = await this._makeRequest("GET", `/api/v1/verification/status/${qHash}`);
899
+ if (!response.success) {
900
+ throw new ApiError(`Failed to get status: ${response.error?.message || "Unknown error"}`, response.error);
901
+ }
902
+ return this._formatResponse(response);
903
+ }
904
+ /**
905
+ * Get private proof status with wallet signature
906
+ *
907
+ * @param {string} qHash - Verification ID
908
+ * @param {Object} wallet - Wallet provider (window.ethereum or ethers Wallet)
909
+ * @returns {Promise<Object>} Private verification status and data
910
+ *
911
+ * @example
912
+ * // Access private proof
913
+ * const privateData = await client.getPrivateStatus(qHash, window.ethereum);
914
+ */
915
+ async getPrivateStatus(qHash, wallet = null) {
916
+ if (!qHash || typeof qHash !== "string") {
917
+ throw new ValidationError("qHash is required");
918
+ }
919
+ if (!wallet) {
920
+ if (typeof window === "undefined" || !window.ethereum) {
921
+ throw new ConfigurationError("No wallet provider available");
922
+ }
923
+ wallet = window.ethereum;
924
+ }
925
+ let walletAddress, provider;
926
+ if (wallet.address) {
927
+ walletAddress = wallet.address;
928
+ provider = wallet;
929
+ } else if (wallet.selectedAddress || wallet.request) {
930
+ provider = wallet;
931
+ if (wallet.selectedAddress) {
932
+ walletAddress = wallet.selectedAddress;
933
+ } else {
934
+ const accounts = await provider.request({ method: "eth_accounts" });
935
+ if (!accounts || accounts.length === 0) {
936
+ throw new ConfigurationError("No wallet accounts available");
937
+ }
938
+ walletAddress = accounts[0];
939
+ }
940
+ } else {
941
+ throw new ConfigurationError("Invalid wallet provider");
942
+ }
943
+ const signedTimestamp = Date.now();
944
+ const message = constructVerificationMessage({
945
+ walletAddress,
946
+ signedTimestamp,
947
+ data: { action: "access_private_proof", qHash },
948
+ verifierIds: ["ownership-basic"],
949
+ chainId: NEUS_CONSTANTS.HUB_CHAIN_ID
950
+ });
951
+ let signature;
952
+ try {
953
+ if (provider.signMessage) {
954
+ signature = await provider.signMessage(message);
955
+ } else {
956
+ signature = await provider.request({
957
+ method: "personal_sign",
958
+ params: [message, walletAddress]
959
+ });
960
+ }
961
+ } catch (error) {
962
+ if (error.code === 4001) {
963
+ throw new ValidationError("User rejected signature request");
964
+ }
965
+ throw new ValidationError(`Failed to sign message: ${error.message}`);
966
+ }
967
+ const response = await this._makeRequest("GET", `/api/v1/verification/status/${qHash}`, null, {
968
+ "x-wallet-address": walletAddress,
969
+ "x-signature": signature,
970
+ "x-signed-timestamp": signedTimestamp.toString()
971
+ });
972
+ if (!response.success) {
973
+ throw new ApiError(
974
+ `Failed to access private proof: ${response.error?.message || "Unauthorized"}`,
975
+ response.error
976
+ );
977
+ }
978
+ return this._formatResponse(response);
979
+ }
980
+ /**
981
+ * Check API health
982
+ *
983
+ * @returns {Promise<boolean>} True if API is healthy
984
+ */
985
+ async isHealthy() {
986
+ try {
987
+ const response = await this._makeRequest("GET", "/api/v1/health");
988
+ return response.success === true;
989
+ } catch {
990
+ return false;
991
+ }
992
+ }
993
+ /**
994
+ * List available verifiers
995
+ *
996
+ * @returns {Promise<string[]>} Array of verifier IDs
997
+ */
998
+ async getVerifiers() {
999
+ const response = await this._makeRequest("GET", "/api/v1/verification/verifiers");
1000
+ if (!response.success) {
1001
+ throw new ApiError(`Failed to get verifiers: ${response.error?.message || "Unknown error"}`, response.error);
1002
+ }
1003
+ return Array.isArray(response.data) ? response.data : [];
1004
+ }
1005
+ /**
1006
+ * POLL PROOF STATUS - Wait for verification completion
1007
+ *
1008
+ * Polls the verification status until it reaches a terminal state (completed or failed).
1009
+ * Useful for providing real-time feedback to users during verification.
1010
+ *
1011
+ * @param {string} qHash - Verification ID to poll
1012
+ * @param {Object} [options] - Polling options
1013
+ * @param {number} [options.interval=5000] - Polling interval in ms
1014
+ * @param {number} [options.timeout=120000] - Total timeout in ms
1015
+ * @param {Function} [options.onProgress] - Progress callback function
1016
+ * @returns {Promise<Object>} Final verification status
1017
+ *
1018
+ * @example
1019
+ * const finalStatus = await client.pollProofStatus(qHash, {
1020
+ * interval: 3000,
1021
+ * timeout: 60000,
1022
+ * onProgress: (status) => {
1023
+ * console.log('Current status:', status.status);
1024
+ * if (status.crosschain) {
1025
+ * console.log(`Cross-chain: ${status.crosschain.finalized}/${status.crosschain.totalChains}`);
1026
+ * }
1027
+ * }
1028
+ * });
1029
+ */
1030
+ async pollProofStatus(qHash, options = {}) {
1031
+ const {
1032
+ interval = 5e3,
1033
+ timeout = 12e4,
1034
+ onProgress
1035
+ } = options;
1036
+ if (!qHash || typeof qHash !== "string") {
1037
+ throw new ValidationError("qHash is required");
1038
+ }
1039
+ const startTime = Date.now();
1040
+ while (Date.now() - startTime < timeout) {
1041
+ try {
1042
+ const status = await this.getStatus(qHash);
1043
+ if (onProgress && typeof onProgress === "function") {
1044
+ onProgress(status.data || status);
1045
+ }
1046
+ const currentStatus = status.data?.status || status.status;
1047
+ if (this._isTerminalStatus(currentStatus)) {
1048
+ this._log("Verification completed", { status: currentStatus, duration: Date.now() - startTime });
1049
+ return status;
1050
+ }
1051
+ await new Promise((resolve) => setTimeout(resolve, interval));
1052
+ } catch (error) {
1053
+ this._log("Status poll error", error.message);
1054
+ if (error instanceof ValidationError) {
1055
+ throw error;
1056
+ }
1057
+ await new Promise((resolve) => setTimeout(resolve, interval));
1058
+ }
1059
+ }
1060
+ throw new NetworkError(`Polling timeout after ${timeout}ms`, "POLLING_TIMEOUT");
1061
+ }
1062
+ /**
1063
+ * DETECT CHAIN ID - Get current wallet chain
1064
+ *
1065
+ * @returns {Promise<number>} Current chain ID
1066
+ */
1067
+ async detectChainId() {
1068
+ if (typeof window === "undefined" || !window.ethereum) {
1069
+ throw new ConfigurationError("No Web3 wallet detected");
1070
+ }
1071
+ try {
1072
+ const chainId = await window.ethereum.request({ method: "eth_chainId" });
1073
+ return parseInt(chainId, 16);
1074
+ } catch (error) {
1075
+ throw new NetworkError(`Failed to detect chain ID: ${error.message}`);
1076
+ }
1077
+ }
1078
+ /** Revoke your own proof (owner-signed) */
1079
+ async revokeOwnProof(qHash, wallet) {
1080
+ if (!qHash || typeof qHash !== "string") {
1081
+ throw new ValidationError("qHash is required");
1082
+ }
1083
+ const address = wallet?.address || await this._getWalletAddress();
1084
+ const signedTimestamp = Date.now();
1085
+ const hubChainId = NEUS_CONSTANTS.HUB_CHAIN_ID;
1086
+ const message = constructVerificationMessage({
1087
+ walletAddress: address,
1088
+ signedTimestamp,
1089
+ data: { action: "revoke_proof", qHash },
1090
+ verifierIds: ["ownership-basic"],
1091
+ chainId: hubChainId
1092
+ });
1093
+ let signature;
1094
+ try {
1095
+ const toHexUtf8 = (s) => {
1096
+ const enc = new TextEncoder();
1097
+ const bytes = enc.encode(s);
1098
+ let hex = "0x";
1099
+ for (let i = 0; i < bytes.length; i++)
1100
+ hex += bytes[i].toString(16).padStart(2, "0");
1101
+ return hex;
1102
+ };
1103
+ const isFarcasterWallet = (() => {
1104
+ if (typeof window === "undefined")
1105
+ return false;
1106
+ try {
1107
+ const w = window;
1108
+ const fc = w.farcaster;
1109
+ if (!fc || !fc.context)
1110
+ return false;
1111
+ const fcProvider = fc.provider || fc.walletProvider || fc.context && fc.context.walletProvider;
1112
+ if (fcProvider === w.ethereum)
1113
+ return true;
1114
+ if (w.mini && w.mini.wallet === w.ethereum && fc && fc.context)
1115
+ return true;
1116
+ if (w.ethereum && fc && fc.context)
1117
+ return true;
1118
+ } catch {
1119
+ }
1120
+ return false;
1121
+ })();
1122
+ if (isFarcasterWallet) {
1123
+ try {
1124
+ const hexMsg = toHexUtf8(message);
1125
+ signature = await window.ethereum.request({ method: "personal_sign", params: [hexMsg, address] });
1126
+ } catch {
1127
+ }
1128
+ }
1129
+ if (!signature) {
1130
+ signature = await window.ethereum.request({ method: "personal_sign", params: [message, address] });
1131
+ }
1132
+ } catch (error) {
1133
+ if (error.code === 4001) {
1134
+ throw new ValidationError("User rejected revocation signature");
1135
+ }
1136
+ throw new ValidationError(`Failed to sign revocation: ${error.message}`);
1137
+ }
1138
+ const res = await fetch(`${this.config.apiUrl}/api/v1/proofs/${qHash}/revoke-self`, {
1139
+ method: "POST",
1140
+ // SECURITY: Do not put proof signatures into Authorization headers.
1141
+ headers: { "Content-Type": "application/json" },
1142
+ body: JSON.stringify({ walletAddress: address, signature, signedTimestamp })
1143
+ });
1144
+ const json = await res.json();
1145
+ if (!json.success) {
1146
+ throw new ApiError(json.error?.message || "Failed to revoke proof", json.error);
1147
+ }
1148
+ return true;
1149
+ }
1150
+ // ============================================================================
1151
+ // GATE & LOOKUP METHODS
1152
+ // ============================================================================
1153
+ /**
1154
+ * GET PROOFS BY WALLET - Fetch proofs for a wallet address
1155
+ *
1156
+ * @param {string} walletAddress - Wallet address (0x...) or DID (did:pkh:...)
1157
+ * @param {Object} [options] - Filter options
1158
+ * @param {number} [options.limit] - Max results (default: 50; higher limits require owner access)
1159
+ * @param {number} [options.offset] - Pagination offset (default: 0)
1160
+ * @returns {Promise<Object>} Proofs result
1161
+ *
1162
+ * @example
1163
+ * const result = await client.getProofsByWallet('0x...', {
1164
+ * limit: 50,
1165
+ * offset: 0
1166
+ * });
1167
+ */
1168
+ async getProofsByWallet(walletAddress, options = {}) {
1169
+ if (!walletAddress || typeof walletAddress !== "string") {
1170
+ throw new ValidationError("walletAddress is required");
1171
+ }
1172
+ const id = walletAddress.trim();
1173
+ const pathId = /^0x[a-fA-F0-9]{40}$/i.test(id) ? id.toLowerCase() : id;
1174
+ const qs = [];
1175
+ if (options.limit)
1176
+ qs.push(`limit=${encodeURIComponent(String(options.limit))}`);
1177
+ if (options.offset)
1178
+ qs.push(`offset=${encodeURIComponent(String(options.offset))}`);
1179
+ const query = qs.length ? `?${qs.join("&")}` : "";
1180
+ const response = await this._makeRequest(
1181
+ "GET",
1182
+ `/api/v1/proofs/byWallet/${encodeURIComponent(pathId)}${query}`
1183
+ );
1184
+ if (!response.success) {
1185
+ throw new ApiError(`Failed to get proofs: ${response.error?.message || "Unknown error"}`, response.error);
1186
+ }
1187
+ const proofs = response.data?.proofs || response.data || response.proofs || [];
1188
+ return {
1189
+ success: true,
1190
+ proofs: Array.isArray(proofs) ? proofs : [],
1191
+ totalCount: response.data?.totalCount ?? proofs.length,
1192
+ hasMore: Boolean(response.data?.hasMore),
1193
+ nextOffset: response.data?.nextOffset ?? null
1194
+ };
1195
+ }
1196
+ /**
1197
+ * Get proofs by wallet (owner access)
1198
+ *
1199
+ * Signs an owner-access intent and requests private proofs via signature headers.
1200
+ *
1201
+ * @param {string} walletAddress - Wallet address (0x...) or DID (did:pkh:...)
1202
+ * @param {Object} [options]
1203
+ * @param {number} [options.limit] - Max results (server enforces caps)
1204
+ * @param {number} [options.offset] - Pagination offset
1205
+ * @param {Object} [wallet] - Optional injected wallet/provider (MetaMask/ethers Wallet)
1206
+ */
1207
+ async getPrivateProofsByWallet(walletAddress, options = {}, wallet = null) {
1208
+ if (!walletAddress || typeof walletAddress !== "string") {
1209
+ throw new ValidationError("walletAddress is required");
1210
+ }
1211
+ const id = walletAddress.trim();
1212
+ const pathId = /^0x[a-fA-F0-9]{40}$/i.test(id) ? id.toLowerCase() : id;
1213
+ if (!wallet) {
1214
+ if (typeof window === "undefined" || !window.ethereum) {
1215
+ throw new ConfigurationError("No wallet provider available");
1216
+ }
1217
+ wallet = window.ethereum;
1218
+ }
1219
+ let signerWalletAddress, provider;
1220
+ if (wallet.address) {
1221
+ signerWalletAddress = wallet.address;
1222
+ provider = wallet;
1223
+ } else if (wallet.selectedAddress || wallet.request) {
1224
+ provider = wallet;
1225
+ if (wallet.selectedAddress) {
1226
+ signerWalletAddress = wallet.selectedAddress;
1227
+ } else {
1228
+ const accounts = await provider.request({ method: "eth_accounts" });
1229
+ if (!accounts || accounts.length === 0) {
1230
+ throw new ConfigurationError("No wallet accounts available");
1231
+ }
1232
+ signerWalletAddress = accounts[0];
1233
+ }
1234
+ } else {
1235
+ throw new ConfigurationError("Invalid wallet provider");
1236
+ }
1237
+ const signedTimestamp = Date.now();
1238
+ const message = constructVerificationMessage({
1239
+ walletAddress: signerWalletAddress,
1240
+ signedTimestamp,
1241
+ data: { action: "access_private_proofs_by_wallet", walletAddress: signerWalletAddress.toLowerCase() },
1242
+ verifierIds: ["ownership-basic"],
1243
+ chainId: NEUS_CONSTANTS.HUB_CHAIN_ID
1244
+ });
1245
+ let signature;
1246
+ try {
1247
+ if (provider.signMessage) {
1248
+ signature = await provider.signMessage(message);
1249
+ } else {
1250
+ signature = await provider.request({
1251
+ method: "personal_sign",
1252
+ params: [message, signerWalletAddress]
1253
+ });
1254
+ }
1255
+ } catch (error) {
1256
+ if (error.code === 4001) {
1257
+ throw new ValidationError("User rejected signature request");
1258
+ }
1259
+ throw new ValidationError(`Failed to sign message: ${error.message}`);
1260
+ }
1261
+ const qs = [];
1262
+ if (options.limit)
1263
+ qs.push(`limit=${encodeURIComponent(String(options.limit))}`);
1264
+ if (options.offset)
1265
+ qs.push(`offset=${encodeURIComponent(String(options.offset))}`);
1266
+ const query = qs.length ? `?${qs.join("&")}` : "";
1267
+ const response = await this._makeRequest("GET", `/api/v1/proofs/byWallet/${encodeURIComponent(pathId)}${query}`, null, {
1268
+ "x-wallet-address": signerWalletAddress,
1269
+ "x-signature": signature,
1270
+ "x-signed-timestamp": signedTimestamp.toString()
1271
+ });
1272
+ if (!response.success) {
1273
+ throw new ApiError(`Failed to get proofs: ${response.error?.message || "Unauthorized"}`, response.error);
1274
+ }
1275
+ const proofs = response.data?.proofs || response.data || response.proofs || [];
1276
+ return {
1277
+ success: true,
1278
+ proofs: Array.isArray(proofs) ? proofs : [],
1279
+ totalCount: response.data?.totalCount ?? proofs.length,
1280
+ hasMore: Boolean(response.data?.hasMore),
1281
+ nextOffset: response.data?.nextOffset ?? null
1282
+ };
1283
+ }
1284
+ /**
1285
+ * LOOKUP MODE (API) - Non-persistent server-to-server checks
1286
+ *
1287
+ * Runs `external_lookup` verifiers without minting/storing a proof.
1288
+ * Requires an enterprise API key (server-side only).
1289
+ *
1290
+ * @param {Object} params
1291
+ * @param {string} params.apiKey - Enterprise API key (sk_live_... or sk_test_...)
1292
+ * @param {Array<string>} params.verifierIds - Verifiers to run (external_lookup only)
1293
+ * @param {string} params.targetWalletAddress - Wallet to evaluate
1294
+ * @param {Object} [params.data] - Verifier input data (e.g., contractAddress/tokenId/chainId)
1295
+ * @returns {Promise<Object>} API response ({ success, data })
1296
+ */
1297
+ async lookup(params = {}) {
1298
+ const apiKey = (params.apiKey || "").toString().trim();
1299
+ if (!apiKey || !(apiKey.startsWith("sk_live_") || apiKey.startsWith("sk_test_"))) {
1300
+ throw new ValidationError("lookup requires apiKey (sk_live_* or sk_test_*)");
1301
+ }
1302
+ const verifierIds = Array.isArray(params.verifierIds) ? params.verifierIds.map((v) => String(v).trim()).filter(Boolean) : [];
1303
+ if (verifierIds.length === 0) {
1304
+ throw new ValidationError("lookup requires verifierIds (non-empty array)");
1305
+ }
1306
+ const targetWalletAddress = (params.targetWalletAddress || "").toString().trim();
1307
+ if (!targetWalletAddress || !/^0x[a-fA-F0-9]{40}$/i.test(targetWalletAddress)) {
1308
+ throw new ValidationError("lookup requires a valid targetWalletAddress (0x...)");
1309
+ }
1310
+ const body = {
1311
+ verifierIds,
1312
+ targetWalletAddress,
1313
+ data: params.data && typeof params.data === "object" ? params.data : {}
1314
+ };
1315
+ const response = await this._makeRequest("POST", "/api/v1/verification/lookup", body, {
1316
+ Authorization: `Bearer ${apiKey}`
1317
+ });
1318
+ if (!response.success) {
1319
+ throw new ApiError(`Lookup failed: ${response.error?.message || "Unknown error"}`, response.error);
1320
+ }
1321
+ return response;
1322
+ }
1323
+ /**
1324
+ * GATE CHECK (API) - Minimal eligibility check
1325
+ *
1326
+ * Calls the public gate endpoint and returns a **minimal** yes/no response
1327
+ * against **public + discoverable** proofs only.
1328
+ *
1329
+ * Prefer this over `checkGate()` for server-side integrations that want the
1330
+ * smallest, most stable surface area (and do NOT need full proof payloads).
1331
+ *
1332
+ * @param {Object} params - Gate check query params
1333
+ * @param {string} params.address - Wallet address to check (0x...)
1334
+ * @param {Array<string>|string} [params.verifierIds] - Verifier IDs to match (array or comma-separated)
1335
+ * @param {boolean} [params.requireAll] - Require all verifierIds on a single proof
1336
+ * @param {number} [params.minCount] - Minimum number of matching proofs
1337
+ * @param {number} [params.sinceDays] - Optional time window in days
1338
+ * @param {number} [params.since] - Optional unix timestamp in ms (lower bound)
1339
+ * @param {number} [params.limit] - Max rows to scan (server may clamp)
1340
+ * @param {string} [params.select] - Comma-separated projections (handle,provider,profileUrl,traits.<key>)
1341
+ * @returns {Promise<Object>} API response ({ success, data })
1342
+ */
1343
+ async gateCheck(params = {}) {
1344
+ const address = (params.address || "").toString();
1345
+ if (!address || !/^0x[a-fA-F0-9]{40}$/i.test(address)) {
1346
+ throw new ValidationError("Valid address is required");
1347
+ }
1348
+ const qs = new URLSearchParams();
1349
+ qs.set("address", address);
1350
+ const setIfPresent = (key, value) => {
1351
+ if (value === void 0 || value === null)
1352
+ return;
1353
+ const str = typeof value === "string" ? value : String(value);
1354
+ if (str.length === 0)
1355
+ return;
1356
+ qs.set(key, str);
1357
+ };
1358
+ const setBoolIfPresent = (key, value) => {
1359
+ if (value === void 0 || value === null)
1360
+ return;
1361
+ qs.set(key, value ? "true" : "false");
1362
+ };
1363
+ const setCsvIfPresent = (key, value) => {
1364
+ if (value === void 0 || value === null)
1365
+ return;
1366
+ if (Array.isArray(value)) {
1367
+ const items = value.map((v) => String(v).trim()).filter(Boolean);
1368
+ if (items.length)
1369
+ qs.set(key, items.join(","));
1370
+ return;
1371
+ }
1372
+ setIfPresent(key, value);
1373
+ };
1374
+ setCsvIfPresent("verifierIds", params.verifierIds);
1375
+ setBoolIfPresent("requireAll", params.requireAll);
1376
+ setIfPresent("minCount", params.minCount);
1377
+ setIfPresent("sinceDays", params.sinceDays);
1378
+ setIfPresent("since", params.since);
1379
+ setIfPresent("limit", params.limit);
1380
+ setCsvIfPresent("select", params.select);
1381
+ setIfPresent("referenceType", params.referenceType);
1382
+ setIfPresent("referenceId", params.referenceId);
1383
+ setIfPresent("tag", params.tag);
1384
+ setCsvIfPresent("tags", params.tags);
1385
+ setIfPresent("contentType", params.contentType);
1386
+ setIfPresent("content", params.content);
1387
+ setIfPresent("contentHash", params.contentHash);
1388
+ setIfPresent("contractAddress", params.contractAddress);
1389
+ setIfPresent("tokenId", params.tokenId);
1390
+ setIfPresent("chainId", params.chainId);
1391
+ setIfPresent("domain", params.domain);
1392
+ setIfPresent("minBalance", params.minBalance);
1393
+ setIfPresent("provider", params.provider);
1394
+ setIfPresent("handle", params.handle);
1395
+ setIfPresent("ownerAddress", params.ownerAddress);
1396
+ setIfPresent("riskLevel", params.riskLevel);
1397
+ setBoolIfPresent("sanctioned", params.sanctioned);
1398
+ setBoolIfPresent("poisoned", params.poisoned);
1399
+ setIfPresent("primaryWalletAddress", params.primaryWalletAddress);
1400
+ setIfPresent("secondaryWalletAddress", params.secondaryWalletAddress);
1401
+ setIfPresent("verificationMethod", params.verificationMethod);
1402
+ setIfPresent("traitPath", params.traitPath);
1403
+ setIfPresent("traitGte", params.traitGte);
1404
+ const response = await this._makeRequest("GET", `/api/v1/proofs/gate/check?${qs.toString()}`);
1405
+ if (!response.success) {
1406
+ throw new ApiError(`Gate check failed: ${response.error?.message || "Unknown error"}`, response.error);
1407
+ }
1408
+ return response;
1409
+ }
1410
+ /**
1411
+ * CHECK GATE - Evaluate requirements against existing proofs
1412
+ *
1413
+ * Gate-first verification: checks if wallet has valid proofs satisfying requirements.
1414
+ * Returns which requirements are missing/expired.
1415
+ *
1416
+ * @param {Object} params - Gate check parameters
1417
+ * @param {string} params.walletAddress - Target wallet
1418
+ * @param {Array<Object>} params.requirements - Array of gate requirements
1419
+ * @param {string} params.requirements[].verifierId - Required verifier ID
1420
+ * @param {number} [params.requirements[].maxAgeMs] - Max proof age in ms (TTL)
1421
+ * @param {boolean} [params.requirements[].optional] - If true, not required for gate satisfaction
1422
+ * @param {number} [params.requirements[].minCount] - Minimum proofs needed (default: 1)
1423
+ * @param {Object} [params.requirements[].match] - Verifier data match criteria
1424
+ * Supports nested fields: 'reference.type', 'reference.id', 'content', 'contentHash', 'input.*', 'license.*'
1425
+ * Supports verifier-specific:
1426
+ * - NFT/Token: 'contractAddress', 'tokenId', 'chainId', 'ownerAddress', 'minBalance'
1427
+ * - DNS: 'domain', 'walletAddress'
1428
+ * - Wallet-link: 'primaryWalletAddress', 'secondaryWalletAddress', 'chainId'
1429
+ * - Contract-ownership: 'contractAddress', 'chainId', 'owner', 'verificationMethod'
1430
+ * Note: contentHash matching uses approximation in SDK; for exact SHA-256 matching, use backend API
1431
+ * @param {Array} [params.proofs] - Pre-fetched proofs (skip API call)
1432
+ * @returns {Promise<Object>} Gate result with satisfied, missing, existing
1433
+ *
1434
+ * @example
1435
+ * // Basic gate check
1436
+ * const result = await client.checkGate({
1437
+ * walletAddress: '0x...',
1438
+ * requirements: [
1439
+ * { verifierId: 'nft-ownership', match: { contractAddress: '0x...' } }
1440
+ * ]
1441
+ * });
1442
+ */
1443
+ async checkGate(params) {
1444
+ const { walletAddress, requirements, proofs: preloadedProofs } = params;
1445
+ if (!walletAddress || !/^0x[a-fA-F0-9]{40}$/i.test(walletAddress)) {
1446
+ throw new ValidationError("Valid walletAddress is required");
1447
+ }
1448
+ if (!Array.isArray(requirements) || requirements.length === 0) {
1449
+ throw new ValidationError("requirements array is required and must not be empty");
1450
+ }
1451
+ let proofs = preloadedProofs;
1452
+ if (!proofs) {
1453
+ const result = await this.getProofsByWallet(walletAddress, { limit: 100 });
1454
+ proofs = result.proofs;
1455
+ }
1456
+ const now = Date.now();
1457
+ const existing = {};
1458
+ const missing = [];
1459
+ for (const req of requirements) {
1460
+ const { verifierId, maxAgeMs, optional = false, minCount = 1, match } = req;
1461
+ const matchingProofs = (proofs || []).filter((proof) => {
1462
+ const verifiedVerifiers = proof.verifiedVerifiers || [];
1463
+ const verifier = verifiedVerifiers.find(
1464
+ (v) => v.verifierId === verifierId && v.verified === true
1465
+ );
1466
+ if (!verifier)
1467
+ return false;
1468
+ if (proof.revokedAt)
1469
+ return false;
1470
+ if (maxAgeMs) {
1471
+ const proofTimestamp = proof.createdAt || proof.signedTimestamp || 0;
1472
+ const proofAge = now - proofTimestamp;
1473
+ if (proofAge > maxAgeMs)
1474
+ return false;
1475
+ }
1476
+ if (match && typeof match === "object") {
1477
+ const data = verifier.data || {};
1478
+ const input = data.input || {};
1479
+ for (const [key, expected] of Object.entries(match)) {
1480
+ let actualValue = null;
1481
+ if (key.includes(".")) {
1482
+ const parts = key.split(".");
1483
+ let current = data;
1484
+ if (parts[0] === "input" && input) {
1485
+ current = input;
1486
+ parts.shift();
1487
+ }
1488
+ for (const part of parts) {
1489
+ if (current && typeof current === "object" && part in current) {
1490
+ current = current[part];
1491
+ } else {
1492
+ current = void 0;
1493
+ break;
1494
+ }
1495
+ }
1496
+ actualValue = current;
1497
+ } else {
1498
+ actualValue = input[key] || data[key];
1499
+ }
1500
+ if (key === "content" && actualValue === void 0) {
1501
+ actualValue = data.reference?.id || data.content;
1502
+ }
1503
+ if (actualValue === void 0) {
1504
+ if (key === "contractAddress") {
1505
+ actualValue = input.contractAddress || data.contractAddress;
1506
+ } else if (key === "tokenId") {
1507
+ actualValue = input.tokenId || data.tokenId;
1508
+ } else if (key === "chainId") {
1509
+ actualValue = input.chainId || data.chainId;
1510
+ } else if (key === "ownerAddress") {
1511
+ actualValue = input.ownerAddress || data.owner || data.walletAddress;
1512
+ } else if (key === "minBalance") {
1513
+ actualValue = input.minBalance || data.onChainData?.requiredMinBalance || data.minBalance;
1514
+ } else if (key === "primaryWalletAddress") {
1515
+ actualValue = data.primaryWalletAddress;
1516
+ } else if (key === "secondaryWalletAddress") {
1517
+ actualValue = data.secondaryWalletAddress;
1518
+ } else if (key === "verificationMethod") {
1519
+ actualValue = data.verificationMethod;
1520
+ } else if (key === "domain") {
1521
+ actualValue = data.domain;
1522
+ }
1523
+ }
1524
+ if (key === "contentHash" && actualValue === void 0 && data.content) {
1525
+ try {
1526
+ let hash = 0;
1527
+ const str = String(data.content);
1528
+ for (let i = 0; i < str.length; i++) {
1529
+ const char = str.charCodeAt(i);
1530
+ hash = (hash << 5) - hash + char;
1531
+ hash = hash & hash;
1532
+ }
1533
+ actualValue = "0x" + Math.abs(hash).toString(16).padStart(64, "0").substring(0, 66);
1534
+ } catch {
1535
+ actualValue = String(data.content);
1536
+ }
1537
+ }
1538
+ let normalizedActual = actualValue;
1539
+ let normalizedExpected = expected;
1540
+ if (actualValue === void 0 || actualValue === null) {
1541
+ return false;
1542
+ }
1543
+ if (key === "chainId" || key === "tokenId" && (typeof actualValue === "number" || !isNaN(Number(actualValue)))) {
1544
+ normalizedActual = Number(actualValue);
1545
+ normalizedExpected = Number(expected);
1546
+ if (isNaN(normalizedActual) || isNaN(normalizedExpected))
1547
+ return false;
1548
+ } else if (typeof actualValue === "string" && (actualValue.startsWith("0x") || actualValue.length > 20)) {
1549
+ normalizedActual = actualValue.toLowerCase();
1550
+ normalizedExpected = typeof expected === "string" ? String(expected).toLowerCase() : expected;
1551
+ } else {
1552
+ normalizedActual = actualValue;
1553
+ normalizedExpected = expected;
1554
+ }
1555
+ if (normalizedActual !== normalizedExpected) {
1556
+ return false;
1557
+ }
1558
+ }
1559
+ }
1560
+ return true;
1561
+ });
1562
+ if (matchingProofs.length >= minCount) {
1563
+ const sorted = matchingProofs.sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));
1564
+ existing[verifierId] = sorted[0];
1565
+ } else if (!optional) {
1566
+ missing.push(req);
1567
+ }
1568
+ }
1569
+ return {
1570
+ satisfied: missing.length === 0,
1571
+ missing,
1572
+ existing,
1573
+ allProofs: proofs
1574
+ };
1575
+ }
1576
+ // ============================================================================
1577
+ // PRIVATE UTILITY METHODS
1578
+ // ============================================================================
1579
+ /**
1580
+ * Get connected wallet address
1581
+ * @private
1582
+ */
1583
+ async _getWalletAddress() {
1584
+ if (typeof window === "undefined" || !window.ethereum) {
1585
+ throw new ConfigurationError("No Web3 wallet detected");
1586
+ }
1587
+ const accounts = await window.ethereum.request({ method: "eth_accounts" });
1588
+ if (!accounts || accounts.length === 0) {
1589
+ throw new ConfigurationError("No wallet accounts available");
1590
+ }
1591
+ return accounts[0];
1592
+ }
1593
+ /**
1594
+ * Make HTTP request to API
1595
+ * @private
1596
+ */
1597
+ async _makeRequest(method, endpoint, data = null, headersOverride = null) {
1598
+ const url = `${this.baseUrl}${endpoint}`;
1599
+ const controller = new AbortController();
1600
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
1601
+ const options = {
1602
+ method,
1603
+ headers: { ...this.defaultHeaders, ...headersOverride || {} },
1604
+ signal: controller.signal
1605
+ };
1606
+ if (data && (method === "POST" || method === "PUT" || method === "PATCH")) {
1607
+ options.body = JSON.stringify(data);
1608
+ }
1609
+ this._log(`${method} ${endpoint}`, data ? { requestBodyKeys: Object.keys(data) } : {});
1610
+ try {
1611
+ const response = await fetch(url, options);
1612
+ clearTimeout(timeoutId);
1613
+ let responseData;
1614
+ try {
1615
+ responseData = await response.json();
1616
+ } catch {
1617
+ responseData = { error: { message: "Invalid JSON response" } };
1618
+ }
1619
+ if (!response.ok) {
1620
+ throw ApiError.fromResponse(response, responseData);
1621
+ }
1622
+ return responseData;
1623
+ } catch (error) {
1624
+ clearTimeout(timeoutId);
1625
+ if (error.name === "AbortError") {
1626
+ throw new NetworkError(`Request timeout after ${this.config.timeout}ms`);
1627
+ }
1628
+ if (error instanceof ApiError) {
1629
+ throw error;
1630
+ }
1631
+ throw new NetworkError(`Network error: ${error.message}`);
1632
+ }
1633
+ }
1634
+ /**
1635
+ * Format API response for consistent structure
1636
+ * @private
1637
+ */
1638
+ _formatResponse(response) {
1639
+ const qHash = response?.data?.qHash || response?.qHash || response?.data?.resource?.qHash || response?.data?.id;
1640
+ const status = response?.data?.status || response?.status || response?.data?.resource?.status || (response?.success ? "completed" : "unknown");
1641
+ return {
1642
+ success: response.success,
1643
+ qHash,
1644
+ status,
1645
+ data: response.data,
1646
+ message: response.message,
1647
+ timestamp: Date.now(),
1648
+ statusUrl: qHash ? `${this.baseUrl}/api/v1/verification/status/${qHash}` : null
1649
+ };
1650
+ }
1651
+ /**
1652
+ * Check if status is terminal (completed or failed)
1653
+ * @private
1654
+ */
1655
+ _isTerminalStatus(status) {
1656
+ const terminalStates = [
1657
+ "verified",
1658
+ "verified_crosschain_propagated",
1659
+ "completed_all_successful",
1660
+ "failed",
1661
+ "error",
1662
+ "rejected",
1663
+ "cancelled"
1664
+ ];
1665
+ return typeof status === "string" && terminalStates.some((state) => status.includes(state));
1666
+ }
1667
+ /** SDK logging (opt-in via config.enableLogging) */
1668
+ _log(message, data = {}) {
1669
+ if (this.config.enableLogging) {
1670
+ try {
1671
+ const prefix = "[neus/sdk]";
1672
+ if (data && Object.keys(data).length > 0) {
1673
+ console.log(prefix, message, data);
1674
+ } else {
1675
+ console.log(prefix, message);
1676
+ }
1677
+ } catch {
1678
+ }
1679
+ }
1680
+ }
1681
+ };
1682
+ // Annotate the CommonJS export names for ESM import in node:
1683
+ 0 && (module.exports = {
1684
+ NeusClient,
1685
+ constructVerificationMessage
1686
+ });