@oma3/omatrust 0.1.0-alpha.0 → 0.1.0-alpha.10

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 (36) hide show
  1. package/README.md +72 -7
  2. package/dist/identity/index.cjs +2 -3
  3. package/dist/identity/index.cjs.map +1 -1
  4. package/dist/identity/index.js +3 -4
  5. package/dist/identity/index.js.map +1 -1
  6. package/dist/index-B9KW02US.d.cts +119 -0
  7. package/dist/index-DXrwBex9.d.ts +119 -0
  8. package/dist/index.cjs +657 -93
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +2 -1
  11. package/dist/index.d.ts +2 -1
  12. package/dist/index.js +658 -94
  13. package/dist/index.js.map +1 -1
  14. package/dist/reputation/index.browser.cjs +2133 -0
  15. package/dist/reputation/index.browser.cjs.map +1 -0
  16. package/dist/reputation/index.browser.d.cts +14 -0
  17. package/dist/reputation/index.browser.d.ts +14 -0
  18. package/dist/reputation/index.browser.js +2071 -0
  19. package/dist/reputation/index.browser.js.map +1 -0
  20. package/dist/reputation/index.cjs +676 -92
  21. package/dist/reputation/index.cjs.map +1 -1
  22. package/dist/reputation/index.d.cts +2 -1
  23. package/dist/reputation/index.d.ts +2 -1
  24. package/dist/reputation/index.js +670 -94
  25. package/dist/reputation/index.js.map +1 -1
  26. package/dist/subject-ownership-CXvzEjpH.d.cts +434 -0
  27. package/dist/subject-ownership-CXvzEjpH.d.ts +434 -0
  28. package/dist/widgets/index.cjs +195 -0
  29. package/dist/widgets/index.cjs.map +1 -0
  30. package/dist/widgets/index.d.cts +134 -0
  31. package/dist/widgets/index.d.ts +134 -0
  32. package/dist/widgets/index.js +185 -0
  33. package/dist/widgets/index.js.map +1 -0
  34. package/package.json +33 -6
  35. package/dist/index-ChbJxwOA.d.cts +0 -415
  36. package/dist/index-ChbJxwOA.d.ts +0 -415
@@ -0,0 +1,2133 @@
1
+ 'use strict';
2
+
3
+ var ethers = require('ethers');
4
+ var easSdk = require('@ethereum-attestation-service/eas-sdk');
5
+ var canonicalize = require('canonicalize');
6
+
7
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
8
+
9
+ var canonicalize__default = /*#__PURE__*/_interopDefault(canonicalize);
10
+
11
+ var __defProp = Object.defineProperty;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __esm = (fn, res) => function __init() {
14
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
15
+ };
16
+ var __export = (target, all) => {
17
+ for (var name in all)
18
+ __defProp(target, name, { get: all[name], enumerable: true });
19
+ };
20
+
21
+ // src/shared/errors.ts
22
+ var OmaTrustError;
23
+ var init_errors = __esm({
24
+ "src/shared/errors.ts"() {
25
+ OmaTrustError = class extends Error {
26
+ code;
27
+ details;
28
+ constructor(code, message, details) {
29
+ super(message);
30
+ this.name = "OmaTrustError";
31
+ this.code = code;
32
+ this.details = details;
33
+ }
34
+ };
35
+ }
36
+ });
37
+
38
+ // src/shared/assert.ts
39
+ function assertString(value, name, code = "INVALID_INPUT") {
40
+ if (typeof value !== "string" || value.trim().length === 0) {
41
+ throw new OmaTrustError(code, `${name} must be a non-empty string`, { value });
42
+ }
43
+ }
44
+ var init_assert = __esm({
45
+ "src/shared/assert.ts"() {
46
+ init_errors();
47
+ }
48
+ });
49
+
50
+ // src/identity/caip.ts
51
+ function parseCaip10(input) {
52
+ assertString(input, "input", "INVALID_CAIP");
53
+ const trimmed = input.trim();
54
+ const match = trimmed.match(CAIP_10_REGEX);
55
+ if (!match?.groups) {
56
+ throw new OmaTrustError("INVALID_CAIP", "Invalid CAIP-10 format", { input });
57
+ }
58
+ const namespace = match.groups.namespace;
59
+ const reference = match.groups.reference;
60
+ const address = match.groups.address;
61
+ if (!namespace || !reference || !address) {
62
+ throw new OmaTrustError("INVALID_CAIP", "Invalid CAIP-10 components", { input });
63
+ }
64
+ return { namespace, reference, address };
65
+ }
66
+ var CAIP_10_REGEX;
67
+ var init_caip = __esm({
68
+ "src/identity/caip.ts"() {
69
+ init_errors();
70
+ init_assert();
71
+ CAIP_10_REGEX = /^(?<namespace>[a-z0-9-]+):(?<reference>[a-zA-Z0-9-]+):(?<address>.+)$/;
72
+ }
73
+ });
74
+ function isValidDid(did) {
75
+ return DID_REGEX.test(did);
76
+ }
77
+ function extractDidMethod(did) {
78
+ const match = did.match(/^did:([a-z0-9]+):/i);
79
+ return match ? match[1] : null;
80
+ }
81
+ function normalizeDomain(domain) {
82
+ assertString(domain, "domain", "INVALID_DID");
83
+ return domain.trim().toLowerCase().replace(/\.$/, "").replace(/^www\./, "");
84
+ }
85
+ function normalizeDidWeb(input) {
86
+ assertString(input, "input", "INVALID_DID");
87
+ const trimmed = input.trim();
88
+ if (trimmed.startsWith("did:") && !trimmed.startsWith("did:web:")) {
89
+ throw new OmaTrustError("INVALID_DID", "Expected did:web DID", { input });
90
+ }
91
+ const identifier = trimmed.startsWith("did:web:") ? trimmed.slice("did:web:".length) : trimmed;
92
+ const [host, ...pathParts] = identifier.split("/");
93
+ if (!host) {
94
+ throw new OmaTrustError("INVALID_DID", "Invalid did:web identifier", { input });
95
+ }
96
+ const normalizedHost = normalizeDomain(host);
97
+ const path = pathParts.length > 0 ? `/${pathParts.join("/")}` : "";
98
+ return `did:web:${normalizedHost}${path}`;
99
+ }
100
+ function normalizeDidPkh(input) {
101
+ assertString(input, "input", "INVALID_DID");
102
+ const trimmed = input.trim();
103
+ if (!trimmed.startsWith("did:pkh:")) {
104
+ throw new OmaTrustError("INVALID_DID", "Expected did:pkh DID", { input });
105
+ }
106
+ const parts = trimmed.split(":");
107
+ if (parts.length !== 5) {
108
+ throw new OmaTrustError("INVALID_DID", "Invalid did:pkh format", { input });
109
+ }
110
+ const [, , namespace, chainId, address] = parts;
111
+ if (!namespace || !chainId || !address) {
112
+ throw new OmaTrustError("INVALID_DID", "Invalid did:pkh components", { input });
113
+ }
114
+ return `did:pkh:${namespace.toLowerCase()}:${chainId}:${address.toLowerCase()}`;
115
+ }
116
+ function normalizeDidHandle(input) {
117
+ assertString(input, "input", "INVALID_DID");
118
+ const trimmed = input.trim();
119
+ if (!trimmed.startsWith("did:handle:")) {
120
+ throw new OmaTrustError("INVALID_DID", "Expected did:handle DID", { input });
121
+ }
122
+ const parts = trimmed.split(":");
123
+ if (parts.length !== 4) {
124
+ throw new OmaTrustError("INVALID_DID", "Invalid did:handle format", { input });
125
+ }
126
+ const [, , platform, username] = parts;
127
+ if (!platform || !username) {
128
+ throw new OmaTrustError("INVALID_DID", "Invalid did:handle components", { input });
129
+ }
130
+ return `did:handle:${platform.toLowerCase()}:${username}`;
131
+ }
132
+ function normalizeDidKey(input) {
133
+ assertString(input, "input", "INVALID_DID");
134
+ const trimmed = input.trim();
135
+ if (!trimmed.startsWith("did:key:")) {
136
+ throw new OmaTrustError("INVALID_DID", "Expected did:key DID", { input });
137
+ }
138
+ return trimmed;
139
+ }
140
+ function normalizeDid(input) {
141
+ assertString(input, "input", "INVALID_DID");
142
+ const trimmed = input.trim();
143
+ if (!trimmed.startsWith("did:")) {
144
+ return normalizeDidWeb(trimmed);
145
+ }
146
+ if (!isValidDid(trimmed)) {
147
+ throw new OmaTrustError("INVALID_DID", "Invalid DID format", { input });
148
+ }
149
+ const method = extractDidMethod(trimmed);
150
+ switch (method) {
151
+ case "web":
152
+ return normalizeDidWeb(trimmed);
153
+ case "pkh":
154
+ return normalizeDidPkh(trimmed);
155
+ case "handle":
156
+ return normalizeDidHandle(trimmed);
157
+ case "key":
158
+ return normalizeDidKey(trimmed);
159
+ default:
160
+ return trimmed;
161
+ }
162
+ }
163
+ function computeDidHash(did) {
164
+ const normalized = normalizeDid(did);
165
+ return ethers.keccak256(ethers.toUtf8Bytes(normalized));
166
+ }
167
+ function computeDidAddress(didHash) {
168
+ assertString(didHash, "didHash", "INVALID_DID");
169
+ if (!/^0x[0-9a-fA-F]{64}$/.test(didHash)) {
170
+ throw new OmaTrustError("INVALID_DID", "didHash must be 32-byte hex", { didHash });
171
+ }
172
+ return `0x${didHash.slice(-40).toLowerCase()}`;
173
+ }
174
+ function didToAddress(did) {
175
+ return computeDidAddress(computeDidHash(did));
176
+ }
177
+ function buildDidPkh(namespace, chainId, address) {
178
+ assertString(namespace, "namespace", "INVALID_DID");
179
+ assertString(address, "address", "INVALID_DID");
180
+ if (chainId === "" || chainId === null || chainId === void 0) {
181
+ throw new OmaTrustError("INVALID_DID", "chainId is required", { chainId });
182
+ }
183
+ return `did:pkh:${namespace.toLowerCase()}:${chainId}:${address.toLowerCase()}`;
184
+ }
185
+ function buildEvmDidPkh(chainId, address) {
186
+ return buildDidPkh("eip155", chainId, address);
187
+ }
188
+ function parseDidPkh(did) {
189
+ if (!did.startsWith("did:pkh:")) {
190
+ return null;
191
+ }
192
+ const parts = did.split(":");
193
+ if (parts.length !== 5) {
194
+ return null;
195
+ }
196
+ const [, , namespace, chainId, address] = parts;
197
+ if (!namespace || !chainId || !address) {
198
+ return null;
199
+ }
200
+ return { namespace, chainId, address };
201
+ }
202
+ function getChainIdFromDidPkh(did) {
203
+ return parseDidPkh(did)?.chainId ?? null;
204
+ }
205
+ function getAddressFromDidPkh(did) {
206
+ return parseDidPkh(did)?.address ?? null;
207
+ }
208
+ function getNamespaceFromDidPkh(did) {
209
+ return parseDidPkh(did)?.namespace ?? null;
210
+ }
211
+ function isEvmDidPkh(did) {
212
+ return getNamespaceFromDidPkh(did) === "eip155";
213
+ }
214
+ function getDomainFromDidWeb(did) {
215
+ if (!did.startsWith("did:web:")) {
216
+ return null;
217
+ }
218
+ const identifier = did.slice("did:web:".length);
219
+ const [domain] = identifier.split("/");
220
+ return domain || null;
221
+ }
222
+ function extractAddressFromDid(identifier) {
223
+ assertString(identifier, "identifier", "INVALID_DID");
224
+ if (identifier.startsWith("did:pkh:")) {
225
+ const pkh = parseDidPkh(normalizeDidPkh(identifier));
226
+ if (!pkh) {
227
+ throw new OmaTrustError("INVALID_DID", "Invalid did:pkh identifier", { identifier });
228
+ }
229
+ return pkh.address;
230
+ }
231
+ if (identifier.startsWith("did:ethr:")) {
232
+ const parts = identifier.replace("did:ethr:", "").split(":");
233
+ const address = parts.length === 1 ? parts[0] : parts[1];
234
+ if (!address || !ethers.isAddress(address)) {
235
+ throw new OmaTrustError("INVALID_DID", "Invalid did:ethr identifier", { identifier });
236
+ }
237
+ return ethers.getAddress(address);
238
+ }
239
+ if (identifier.match(/^[a-z0-9-]+:[a-zA-Z0-9-]+:0x[a-fA-F0-9]{40}$/)) {
240
+ const parsed = parseCaip10(identifier);
241
+ return parsed.address;
242
+ }
243
+ if (ethers.isAddress(identifier)) {
244
+ return ethers.getAddress(identifier);
245
+ }
246
+ throw new OmaTrustError("INVALID_DID", "Unsupported identifier format", { identifier });
247
+ }
248
+ var DID_REGEX;
249
+ var init_did = __esm({
250
+ "src/identity/did.ts"() {
251
+ init_errors();
252
+ init_assert();
253
+ init_caip();
254
+ DID_REGEX = /^did:[a-z0-9]+:.+$/i;
255
+ }
256
+ });
257
+
258
+ // src/reputation/proof/dns-txt-record.ts
259
+ function parseDnsTxtRecord(record) {
260
+ if (!record || typeof record !== "string") {
261
+ throw new OmaTrustError("INVALID_INPUT", "record must be a non-empty string", { record });
262
+ }
263
+ const entries = record.split(/[;\s]+/).map((entry) => entry.trim()).filter(Boolean);
264
+ const parsed = {};
265
+ for (const entry of entries) {
266
+ const [key, ...valueParts] = entry.split("=");
267
+ if (!key) {
268
+ continue;
269
+ }
270
+ const value = valueParts.join("=");
271
+ if (!value) {
272
+ continue;
273
+ }
274
+ parsed[key.trim()] = value.trim();
275
+ }
276
+ return {
277
+ version: parsed.v,
278
+ controller: parsed.controller,
279
+ ...parsed
280
+ };
281
+ }
282
+ function buildDnsTxtRecord(controllerDid) {
283
+ const normalized = normalizeDid(controllerDid);
284
+ return `v=1;controller=${normalized}`;
285
+ }
286
+ var init_dns_txt_record = __esm({
287
+ "src/reputation/proof/dns-txt-record.ts"() {
288
+ init_did();
289
+ init_errors();
290
+ }
291
+ });
292
+
293
+ // src/reputation/proof/dns-txt-shared.ts
294
+ var dns_txt_shared_exports = {};
295
+ __export(dns_txt_shared_exports, {
296
+ verifyDnsTxtControllerDid: () => verifyDnsTxtControllerDid
297
+ });
298
+ async function verifyDnsTxtControllerDid(domain, expectedControllerDid, options = {}) {
299
+ if (!domain || typeof domain !== "string") {
300
+ throw new OmaTrustError("INVALID_INPUT", "domain must be a non-empty string", { domain });
301
+ }
302
+ if (!options.resolveTxt) {
303
+ throw new OmaTrustError("NETWORK_ERROR", "No DNS TXT resolver was provided", { domain });
304
+ }
305
+ const expected = normalizeDid(expectedControllerDid);
306
+ const prefix = options.recordPrefix ?? "_controllers";
307
+ const host = `${prefix}.${domain.toLowerCase().replace(/\.$/, "")}`;
308
+ let records;
309
+ try {
310
+ records = await options.resolveTxt(host);
311
+ } catch (err) {
312
+ throw new OmaTrustError("NETWORK_ERROR", "Failed to resolve DNS TXT records", { domain, err });
313
+ }
314
+ for (const recordParts of records) {
315
+ const record = recordParts.join("");
316
+ const parsed = parseDnsTxtRecord(record);
317
+ if (parsed.version === "1" && parsed.controller && normalizeDid(parsed.controller) === expected) {
318
+ return { valid: true, record };
319
+ }
320
+ }
321
+ return { valid: false, reason: "No TXT record matched expected controller DID" };
322
+ }
323
+ var init_dns_txt_shared = __esm({
324
+ "src/reputation/proof/dns-txt-shared.ts"() {
325
+ init_did();
326
+ init_errors();
327
+ init_dns_txt_record();
328
+ }
329
+ });
330
+
331
+ // src/reputation/encode.ts
332
+ init_errors();
333
+ function normalizeSchema(schema) {
334
+ if (Array.isArray(schema)) {
335
+ if (schema.length === 0) {
336
+ throw new OmaTrustError("INVALID_INPUT", "schema array cannot be empty");
337
+ }
338
+ return schema;
339
+ }
340
+ if (typeof schema !== "string" || schema.trim().length === 0) {
341
+ throw new OmaTrustError("INVALID_INPUT", "schema must be a non-empty string or SchemaField[]");
342
+ }
343
+ const fields = schema.split(",").map((part) => part.trim()).filter((part) => part.length > 0).map((part) => {
344
+ const pieces = part.split(/\s+/);
345
+ if (pieces.length < 2) {
346
+ throw new OmaTrustError("INVALID_INPUT", "Invalid schema field", { part });
347
+ }
348
+ const type = pieces[0];
349
+ const name = pieces.slice(1).join(" ");
350
+ return { type, name };
351
+ });
352
+ if (fields.length === 0) {
353
+ throw new OmaTrustError("INVALID_INPUT", "No schema fields found");
354
+ }
355
+ return fields;
356
+ }
357
+ function schemaToString(schema) {
358
+ if (typeof schema === "string") {
359
+ return schema;
360
+ }
361
+ return schema.map((field) => `${field.type} ${field.name}`).join(", ");
362
+ }
363
+ function encodeAttestationData(schema, data) {
364
+ if (!data || typeof data !== "object") {
365
+ throw new OmaTrustError("INVALID_INPUT", "data must be an object");
366
+ }
367
+ const validationErrors = validateAttestationData(schema, data);
368
+ if (validationErrors.length > 0) {
369
+ const summary = validationErrors.map((error) => `Field "${error.schemaFieldName}" (${error.expectedType}) got ${error.providedType}`).join("; ");
370
+ throw new OmaTrustError("INVALID_INPUT", `Attestation data validation failed: ${summary}`, {
371
+ errors: validationErrors
372
+ });
373
+ }
374
+ const fields = normalizeSchema(schema);
375
+ const schemaString = schemaToString(fields);
376
+ const encoder = new easSdk.SchemaEncoder(schemaString);
377
+ const encoded = encoder.encodeData(
378
+ fields.map((field) => ({
379
+ name: field.name,
380
+ type: field.type,
381
+ value: data[field.name]
382
+ }))
383
+ );
384
+ return encoded;
385
+ }
386
+ function getActualType(value) {
387
+ if (value === null) {
388
+ return "null";
389
+ }
390
+ if (value === void 0) {
391
+ return "undefined";
392
+ }
393
+ if (Array.isArray(value)) {
394
+ return "array";
395
+ }
396
+ if (typeof value === "number") {
397
+ return Number.isFinite(value) ? "number" : "non-finite-number";
398
+ }
399
+ return typeof value;
400
+ }
401
+ function isNumericValue(value, allowNegative) {
402
+ if (typeof value === "bigint") {
403
+ return allowNegative || value >= 0n;
404
+ }
405
+ if (typeof value === "number") {
406
+ if (!Number.isFinite(value) || !Number.isInteger(value)) {
407
+ return false;
408
+ }
409
+ return allowNegative || value >= 0;
410
+ }
411
+ if (typeof value === "string") {
412
+ if (value.length === 0) {
413
+ return false;
414
+ }
415
+ const pattern = allowNegative ? /^-?\d+$/ : /^\d+$/;
416
+ return pattern.test(value);
417
+ }
418
+ return false;
419
+ }
420
+ function isHex(value) {
421
+ return typeof value === "string" && /^0x[0-9a-fA-F]*$/.test(value);
422
+ }
423
+ function validateFieldValue(type, value) {
424
+ const normalizedType = type.trim().toLowerCase();
425
+ const bytesNMatch = normalizedType.match(/^bytes([1-9]|[12]\d|3[0-2])$/);
426
+ if (/^uint\d*$/.test(normalizedType)) {
427
+ return isNumericValue(value, false);
428
+ }
429
+ if (/^int\d*$/.test(normalizedType)) {
430
+ return isNumericValue(value, true);
431
+ }
432
+ if (normalizedType === "string") {
433
+ return typeof value === "string";
434
+ }
435
+ if (normalizedType === "string[]") {
436
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string");
437
+ }
438
+ if (normalizedType === "bool") {
439
+ return typeof value === "boolean";
440
+ }
441
+ if (normalizedType === "address") {
442
+ return typeof value === "string" && ethers.isAddress(value);
443
+ }
444
+ if (normalizedType === "bytes") {
445
+ return isHex(value) && (value.length - 2) % 2 === 0;
446
+ }
447
+ if (bytesNMatch) {
448
+ const expectedBytes = Number(bytesNMatch[1]);
449
+ return isHex(value) && value.length === 2 + expectedBytes * 2;
450
+ }
451
+ return true;
452
+ }
453
+ function validateAttestationData(schema, data) {
454
+ if (!data || typeof data !== "object") {
455
+ return [{
456
+ schemaFieldName: "data",
457
+ expectedType: "object",
458
+ providedType: getActualType(data),
459
+ providedValue: data
460
+ }];
461
+ }
462
+ const fields = normalizeSchema(schema);
463
+ const errors = [];
464
+ for (const field of fields) {
465
+ const value = data[field.name];
466
+ const isValid = validateFieldValue(field.type, value);
467
+ if (isValid) {
468
+ continue;
469
+ }
470
+ errors.push({
471
+ schemaFieldName: field.name,
472
+ expectedType: field.type,
473
+ providedType: getActualType(value),
474
+ providedValue: value
475
+ });
476
+ }
477
+ return errors;
478
+ }
479
+ function decodeAttestationData(schema, encodedData) {
480
+ if (typeof encodedData !== "string" || !encodedData.startsWith("0x")) {
481
+ throw new OmaTrustError("INVALID_INPUT", "encodedData must be a hex string");
482
+ }
483
+ const fields = normalizeSchema(schema);
484
+ const schemaString = schemaToString(fields);
485
+ const encoder = new easSdk.SchemaEncoder(schemaString);
486
+ const decoded = encoder.decodeData(encodedData);
487
+ const result = {};
488
+ for (const item of decoded) {
489
+ const value = item.value;
490
+ if (value && typeof value === "object" && "value" in value) {
491
+ result[item.name] = value.value;
492
+ } else {
493
+ result[item.name] = value;
494
+ }
495
+ }
496
+ return result;
497
+ }
498
+ function extractExpirationTime(data) {
499
+ const value = data["expiresAt"];
500
+ if (value === void 0 || value === null) return void 0;
501
+ if (typeof value === "bigint") return value;
502
+ if (typeof value === "number") return value;
503
+ if (typeof value === "string" && /^\d+$/.test(value)) return BigInt(value);
504
+ return void 0;
505
+ }
506
+
507
+ // src/reputation/internal.ts
508
+ init_did();
509
+ var ZERO_UID = "0x0000000000000000000000000000000000000000000000000000000000000000";
510
+ function toBigIntOrDefault(value, fallback) {
511
+ if (value === void 0 || value === null) {
512
+ return fallback;
513
+ }
514
+ return typeof value === "bigint" ? value : BigInt(Math.floor(value));
515
+ }
516
+ function withAutoSubjectDidHash(schema, data) {
517
+ const fields = normalizeSchema(schema);
518
+ const hasSubjectDidHash = fields.some((field) => field.name === "subjectDidHash");
519
+ if (!hasSubjectDidHash) {
520
+ return { ...data };
521
+ }
522
+ const subject = data.subject;
523
+ if (typeof subject === "string" && subject.startsWith("did:")) {
524
+ return {
525
+ ...data,
526
+ subjectDidHash: computeDidHash(subject)
527
+ };
528
+ }
529
+ return { ...data };
530
+ }
531
+ function resolveRecipientAddress(data) {
532
+ const subject = data.subject;
533
+ if (typeof subject === "string" && subject.startsWith("did:")) {
534
+ return didToAddress(subject);
535
+ }
536
+ const subjectDidHash = data.subjectDidHash;
537
+ if (typeof subjectDidHash === "string" && /^0x[0-9a-fA-F]{64}$/.test(subjectDidHash)) {
538
+ return computeDidAddress(subjectDidHash);
539
+ }
540
+ const recipient = data.recipient;
541
+ if (typeof recipient === "string" && ethers.isAddress(recipient)) {
542
+ return ethers.getAddress(recipient);
543
+ }
544
+ return ethers.ZeroAddress;
545
+ }
546
+
547
+ // src/reputation/eas-adapter.ts
548
+ function isRecord(value) {
549
+ return Boolean(value) && typeof value === "object";
550
+ }
551
+ function isHex32(value) {
552
+ return typeof value === "string" && /^0x[0-9a-fA-F]{64}$/.test(value);
553
+ }
554
+ function getEasTransactionReceipt(tx) {
555
+ if (!isRecord(tx)) {
556
+ return void 0;
557
+ }
558
+ const candidates = [tx.receipt, tx.tx, tx.transaction];
559
+ for (const candidate of candidates) {
560
+ if (isRecord(candidate)) {
561
+ return candidate;
562
+ }
563
+ }
564
+ return void 0;
565
+ }
566
+ function getEasTransactionHash(tx) {
567
+ const receipt = getEasTransactionReceipt(tx);
568
+ if (receipt) {
569
+ const receiptHash = receipt.hash;
570
+ if (isHex32(receiptHash)) {
571
+ return receiptHash;
572
+ }
573
+ const transactionHash = receipt.transactionHash;
574
+ if (isHex32(transactionHash)) {
575
+ return transactionHash;
576
+ }
577
+ }
578
+ if (isRecord(tx) && isHex32(tx.hash)) {
579
+ return tx.hash;
580
+ }
581
+ return void 0;
582
+ }
583
+ function isEasSchemaNotFoundError(err) {
584
+ if (!isRecord(err)) {
585
+ return false;
586
+ }
587
+ const message = err.message;
588
+ if (typeof message !== "string" || message.length === 0) {
589
+ return false;
590
+ }
591
+ return /schema not found/i.test(message);
592
+ }
593
+
594
+ // src/reputation/submit.ts
595
+ init_errors();
596
+ async function submitAttestation(params) {
597
+ if (!params || typeof params !== "object") {
598
+ throw new OmaTrustError("INVALID_INPUT", "params must be provided");
599
+ }
600
+ if (!params.signer) {
601
+ throw new OmaTrustError("INVALID_INPUT", "signer is required");
602
+ }
603
+ const dataWithHash = withAutoSubjectDidHash(params.schema, params.data);
604
+ const encodedData = encodeAttestationData(params.schema, dataWithHash);
605
+ const expiration = toBigIntOrDefault(
606
+ params.expirationTime ?? extractExpirationTime(dataWithHash),
607
+ 0n
608
+ );
609
+ const recipient = resolveRecipientAddress(dataWithHash);
610
+ const eas = new easSdk.EAS(params.easContractAddress);
611
+ eas.connect(params.signer);
612
+ try {
613
+ const tx = await eas.attest({
614
+ schema: params.schemaUid,
615
+ data: {
616
+ recipient: recipient || ethers.ZeroAddress,
617
+ expirationTime: expiration,
618
+ revocable: params.revocable ?? true,
619
+ refUID: params.refUid ?? ZERO_UID,
620
+ data: encodedData,
621
+ value: toBigIntOrDefault(params.value, 0n)
622
+ }
623
+ });
624
+ const uid = await tx.wait();
625
+ const txHash = getEasTransactionHash(tx) ?? ZERO_UID;
626
+ const receipt = getEasTransactionReceipt(tx);
627
+ return {
628
+ uid,
629
+ txHash,
630
+ receipt
631
+ };
632
+ } catch (err) {
633
+ throw new OmaTrustError("NETWORK_ERROR", "Failed to submit attestation", { err });
634
+ }
635
+ }
636
+ init_errors();
637
+ async function revokeAttestation(params) {
638
+ if (!params || typeof params !== "object") {
639
+ throw new OmaTrustError("INVALID_INPUT", "params must be provided");
640
+ }
641
+ if (!params.signer) {
642
+ throw new OmaTrustError("INVALID_INPUT", "signer is required");
643
+ }
644
+ const eas = new easSdk.EAS(params.easContractAddress);
645
+ eas.connect(params.signer);
646
+ try {
647
+ const tx = await eas.revoke({
648
+ schema: params.schemaUid,
649
+ data: {
650
+ uid: params.uid,
651
+ value: toBigIntOrDefault(params.value, 0n)
652
+ }
653
+ });
654
+ await tx.wait();
655
+ const txHash = getEasTransactionHash(tx) ?? ZERO_UID;
656
+ const receipt = getEasTransactionReceipt(tx);
657
+ return {
658
+ txHash,
659
+ receipt
660
+ };
661
+ } catch (err) {
662
+ throw new OmaTrustError("NETWORK_ERROR", "Failed to revoke attestation", { err });
663
+ }
664
+ }
665
+ init_errors();
666
+ function buildDelegatedTypedData(params) {
667
+ return {
668
+ domain: {
669
+ name: "EAS",
670
+ version: "1.4.0",
671
+ chainId: params.chainId,
672
+ verifyingContract: params.easContractAddress
673
+ },
674
+ types: {
675
+ Attest: [
676
+ { name: "attester", type: "address" },
677
+ { name: "schema", type: "bytes32" },
678
+ { name: "recipient", type: "address" },
679
+ { name: "expirationTime", type: "uint64" },
680
+ { name: "revocable", type: "bool" },
681
+ { name: "refUID", type: "bytes32" },
682
+ { name: "data", type: "bytes" },
683
+ { name: "value", type: "uint256" },
684
+ { name: "nonce", type: "uint256" },
685
+ { name: "deadline", type: "uint64" }
686
+ ]
687
+ },
688
+ message: {
689
+ attester: params.attester,
690
+ schema: params.schemaUid,
691
+ recipient: params.recipient,
692
+ expirationTime: toBigIntOrDefault(params.expirationTime, 0n),
693
+ revocable: params.revocable ?? true,
694
+ refUID: params.refUid ?? ZERO_UID,
695
+ data: params.encodedData,
696
+ value: toBigIntOrDefault(params.value, 0n),
697
+ nonce: toBigIntOrDefault(params.nonce, 0n),
698
+ deadline: toBigIntOrDefault(params.deadline, BigInt(Math.floor(Date.now() / 1e3) + 600))
699
+ }
700
+ };
701
+ }
702
+ function buildDelegatedAttestationTypedData(params) {
703
+ const dataWithHash = withAutoSubjectDidHash(params.schema, params.data);
704
+ const encodedData = encodeAttestationData(params.schema, dataWithHash);
705
+ const recipient = resolveRecipientAddress(dataWithHash);
706
+ return buildDelegatedTypedData({
707
+ chainId: params.chainId,
708
+ easContractAddress: params.easContractAddress,
709
+ schemaUid: params.schemaUid,
710
+ encodedData,
711
+ recipient,
712
+ attester: params.attester,
713
+ nonce: params.nonce,
714
+ revocable: params.revocable,
715
+ expirationTime: params.expirationTime ?? extractExpirationTime(dataWithHash),
716
+ refUid: params.refUid,
717
+ value: params.value,
718
+ deadline: params.deadline
719
+ });
720
+ }
721
+ function buildDelegatedTypedDataFromEncoded(params) {
722
+ return buildDelegatedTypedData({
723
+ chainId: params.chainId,
724
+ easContractAddress: params.easContractAddress,
725
+ schemaUid: params.schemaUid,
726
+ encodedData: params.encodedData,
727
+ recipient: params.recipient,
728
+ attester: params.attester,
729
+ nonce: params.nonce,
730
+ revocable: params.revocable,
731
+ expirationTime: params.expirationTime,
732
+ refUid: params.refUid,
733
+ value: params.value,
734
+ deadline: params.deadline
735
+ });
736
+ }
737
+ function splitSignature(signature) {
738
+ try {
739
+ const parsed = ethers.Signature.from(signature);
740
+ return {
741
+ v: parsed.v,
742
+ r: parsed.r,
743
+ s: parsed.s
744
+ };
745
+ } catch (err) {
746
+ throw new OmaTrustError("INVALID_INPUT", "Invalid signature", { err });
747
+ }
748
+ }
749
+ async function prepareDelegatedAttestation(params) {
750
+ if (!params || typeof params !== "object") {
751
+ throw new OmaTrustError("INVALID_INPUT", "params are required");
752
+ }
753
+ const typedData = buildDelegatedAttestationTypedData(params);
754
+ return {
755
+ delegatedRequest: {
756
+ schema: params.schemaUid,
757
+ attester: params.attester,
758
+ easContractAddress: params.easContractAddress,
759
+ chainId: params.chainId,
760
+ ...typedData.message
761
+ },
762
+ typedData
763
+ };
764
+ }
765
+ async function submitDelegatedAttestation(params) {
766
+ if (!params.relayUrl || typeof params.relayUrl !== "string") {
767
+ throw new OmaTrustError("INVALID_INPUT", "relayUrl is required");
768
+ }
769
+ let response;
770
+ try {
771
+ const body = JSON.stringify(
772
+ {
773
+ prepared: params.prepared,
774
+ signature: params.signature,
775
+ attester: params.attester
776
+ },
777
+ (_key, value) => typeof value === "bigint" ? value.toString() : value
778
+ );
779
+ response = await fetch(params.relayUrl, {
780
+ method: "POST",
781
+ headers: {
782
+ "Content-Type": "application/json"
783
+ },
784
+ body
785
+ });
786
+ } catch (err) {
787
+ throw new OmaTrustError("NETWORK_ERROR", "Failed to submit delegated attestation", { err });
788
+ }
789
+ let payload;
790
+ try {
791
+ payload = await response.json();
792
+ } catch {
793
+ payload = {};
794
+ }
795
+ if (!response.ok) {
796
+ throw new OmaTrustError("NETWORK_ERROR", "Relay submission failed", {
797
+ status: response.status,
798
+ payload
799
+ });
800
+ }
801
+ const uid = payload.uid ?? ZERO_UID;
802
+ const txHash = payload.txHash;
803
+ const status = payload.status ?? "submitted";
804
+ return {
805
+ uid,
806
+ txHash,
807
+ status
808
+ };
809
+ }
810
+
811
+ // src/reputation/query.ts
812
+ init_did();
813
+ init_errors();
814
+ var EAS_EVENT_ABI = [
815
+ "event Attested(address indexed recipient, address indexed attester, bytes32 uid, bytes32 indexed schemaUID)"
816
+ ];
817
+ function parseEventTxHash(event) {
818
+ const txHash = event.transactionHash;
819
+ if (typeof txHash !== "string") {
820
+ return void 0;
821
+ }
822
+ return /^0x[0-9a-fA-F]{64}$/.test(txHash) ? txHash : void 0;
823
+ }
824
+ function parseAttestation(attestation, schema, txHash) {
825
+ const rawData = attestation.data ?? "0x";
826
+ const decoded = schema ? decodeAttestationData(schema, rawData) : {};
827
+ const toBigIntSafe = (value) => {
828
+ if (typeof value === "bigint") {
829
+ return value;
830
+ }
831
+ if (typeof value === "number") {
832
+ return BigInt(value);
833
+ }
834
+ if (typeof value === "string" && value.length > 0) {
835
+ return BigInt(value);
836
+ }
837
+ return 0n;
838
+ };
839
+ return {
840
+ uid: attestation.uid,
841
+ schema: attestation.schema,
842
+ attester: attestation.attester,
843
+ recipient: attestation.recipient,
844
+ txHash,
845
+ revocable: Boolean(attestation.revocable),
846
+ revocationTime: toBigIntSafe(attestation.revocationTime),
847
+ expirationTime: toBigIntSafe(attestation.expirationTime),
848
+ time: toBigIntSafe(attestation.time),
849
+ refUID: attestation.refUID,
850
+ data: decoded,
851
+ raw: schema ? void 0 : rawData
852
+ };
853
+ }
854
+ async function getAttestation(params) {
855
+ try {
856
+ const eas = new easSdk.EAS(params.easContractAddress);
857
+ eas.connect(params.provider);
858
+ const attestation = await eas.getAttestation(params.uid);
859
+ if (!attestation || !attestation.uid || String(attestation.uid) === "0x".padEnd(66, "0")) {
860
+ throw new OmaTrustError("ATTESTATION_NOT_FOUND", "Attestation not found", { uid: params.uid });
861
+ }
862
+ return parseAttestation(attestation, params.schema);
863
+ } catch (err) {
864
+ if (err instanceof OmaTrustError) {
865
+ throw err;
866
+ }
867
+ throw new OmaTrustError("NETWORK_ERROR", "Failed to read attestation", { err });
868
+ }
869
+ }
870
+ async function queryAttestationEvents(easContractAddress, provider, fromBlock, toBlock, options) {
871
+ const contract = new ethers.Contract(easContractAddress, EAS_EVENT_ABI, provider);
872
+ const filter = contract.filters.Attested(options?.recipient ?? null, options?.attester ?? null);
873
+ let events;
874
+ try {
875
+ events = await contract.queryFilter(filter, fromBlock, toBlock);
876
+ } catch (err) {
877
+ throw new OmaTrustError("NETWORK_ERROR", "Failed to query attestation events", { err });
878
+ }
879
+ const eas = new easSdk.EAS(easContractAddress);
880
+ eas.connect(provider);
881
+ const schemaFilter = options?.schemas?.map((s) => s.toLowerCase());
882
+ const results = [];
883
+ for (const event of events) {
884
+ if (!("args" in event && Array.isArray(event.args))) {
885
+ continue;
886
+ }
887
+ const args = event.args;
888
+ const uid = args?.[2];
889
+ const schemaUid = args?.[3];
890
+ if (!uid || !schemaUid) {
891
+ continue;
892
+ }
893
+ if (schemaFilter && !schemaFilter.includes(schemaUid.toLowerCase())) {
894
+ continue;
895
+ }
896
+ const attestation = await eas.getAttestation(uid);
897
+ if (!attestation || !attestation.uid) {
898
+ continue;
899
+ }
900
+ results.push(parseAttestation(attestation, void 0, parseEventTxHash(event)));
901
+ }
902
+ results.sort((a, b) => Number(b.time - a.time));
903
+ return results;
904
+ }
905
+ async function getAttestationsForDid(params) {
906
+ const provider = params.provider;
907
+ const toBlock = params.toBlock ?? await provider.getBlockNumber();
908
+ const fromBlock = params.fromBlock ?? Math.max(0, toBlock - 5e4);
909
+ return queryAttestationEvents(
910
+ params.easContractAddress,
911
+ provider,
912
+ fromBlock,
913
+ toBlock,
914
+ { recipient: didToAddress(params.did), schemas: params.schemas }
915
+ );
916
+ }
917
+ async function getAttestationsByAttester(params) {
918
+ const provider = params.provider;
919
+ const toBlock = params.toBlock ?? await provider.getBlockNumber();
920
+ const fromBlock = params.fromBlock ?? Math.max(0, toBlock - 5e4);
921
+ if (params.limit !== void 0 && params.limit <= 0) {
922
+ return [];
923
+ }
924
+ const results = await queryAttestationEvents(
925
+ params.easContractAddress,
926
+ provider,
927
+ fromBlock,
928
+ toBlock,
929
+ { attester: params.attester, schemas: params.schemas }
930
+ );
931
+ return params.limit !== void 0 ? results.slice(0, params.limit) : results;
932
+ }
933
+ async function listAttestations(params) {
934
+ const limit = params.limit ?? 20;
935
+ if (limit <= 0) {
936
+ return [];
937
+ }
938
+ const results = await getAttestationsForDid(params);
939
+ return results.slice(0, limit);
940
+ }
941
+ async function getLatestAttestations(params) {
942
+ const provider = params.provider;
943
+ const toBlock = await provider.getBlockNumber();
944
+ const fromBlock = params.fromBlock ?? Math.max(0, toBlock - 5e4);
945
+ const results = await queryAttestationEvents(
946
+ params.easContractAddress,
947
+ provider,
948
+ fromBlock,
949
+ toBlock,
950
+ { schemas: params.schemas }
951
+ );
952
+ return results.slice(0, params.limit ?? 20);
953
+ }
954
+ function deduplicateReviews(attestations) {
955
+ const seen = /* @__PURE__ */ new Map();
956
+ for (const attestation of attestations) {
957
+ const subject = String(attestation.data.subject ?? "");
958
+ const version = String(attestation.data.version ?? "");
959
+ const major = getMajorVersion(version);
960
+ const key = `${attestation.attester.toLowerCase()}|${subject}|${major}`;
961
+ if (!seen.has(key)) {
962
+ seen.set(key, attestation);
963
+ continue;
964
+ }
965
+ const current = seen.get(key);
966
+ if (attestation.time > current.time) {
967
+ seen.set(key, attestation);
968
+ }
969
+ }
970
+ return [...seen.values()];
971
+ }
972
+ function calculateAverageUserReviewRating(attestations) {
973
+ const deduped = deduplicateReviews(attestations);
974
+ const ratings = deduped.map((attestation) => attestation.data.ratingValue).filter((value) => typeof value === "number" || typeof value === "bigint").map((value) => Number(value));
975
+ if (ratings.length === 0) {
976
+ return 0;
977
+ }
978
+ const total = ratings.reduce((sum, value) => sum + value, 0);
979
+ return total / ratings.length;
980
+ }
981
+ function getMajorVersion(version) {
982
+ const match = version.match(/^(\d+)/);
983
+ if (!match) {
984
+ throw new OmaTrustError("INVALID_INPUT", "Invalid semantic version", { version });
985
+ }
986
+ return Number(match[1]);
987
+ }
988
+
989
+ // src/reputation/verify.ts
990
+ init_did();
991
+ init_errors();
992
+
993
+ // src/reputation/proof/tx-encoded-value.ts
994
+ init_did();
995
+ init_errors();
996
+ var CHAIN_CONFIGS = {
997
+ 1: {
998
+ decimals: 18,
999
+ nativeSymbol: "ETH",
1000
+ explorer: "https://etherscan.io",
1001
+ base: {
1002
+ "shared-control": 100000000000000n,
1003
+ "commercial-tx": 1000000000000n
1004
+ }
1005
+ },
1006
+ 10: {
1007
+ decimals: 18,
1008
+ nativeSymbol: "ETH",
1009
+ explorer: "https://optimistic.etherscan.io",
1010
+ base: {
1011
+ "shared-control": 100000000000000n,
1012
+ "commercial-tx": 1000000000000n
1013
+ }
1014
+ },
1015
+ 137: {
1016
+ decimals: 18,
1017
+ nativeSymbol: "POL",
1018
+ explorer: "https://polygonscan.com",
1019
+ base: {
1020
+ "shared-control": 100000000000000n,
1021
+ "commercial-tx": 1000000000000n
1022
+ }
1023
+ },
1024
+ 8453: {
1025
+ decimals: 18,
1026
+ nativeSymbol: "ETH",
1027
+ explorer: "https://basescan.org",
1028
+ base: {
1029
+ "shared-control": 100000000000000n,
1030
+ "commercial-tx": 1000000000000n
1031
+ }
1032
+ },
1033
+ 42161: {
1034
+ decimals: 18,
1035
+ nativeSymbol: "ETH",
1036
+ explorer: "https://arbiscan.io",
1037
+ base: {
1038
+ "shared-control": 100000000000000n,
1039
+ "commercial-tx": 1000000000000n
1040
+ }
1041
+ },
1042
+ 11155111: {
1043
+ decimals: 18,
1044
+ nativeSymbol: "ETH",
1045
+ explorer: "https://sepolia.etherscan.io",
1046
+ base: {
1047
+ "shared-control": 100000000000000n,
1048
+ "commercial-tx": 1000000000000n
1049
+ }
1050
+ },
1051
+ 6623: {
1052
+ decimals: 18,
1053
+ nativeSymbol: "OMA",
1054
+ explorer: "https://explorer.chain.oma3.org",
1055
+ base: {
1056
+ "shared-control": 10000000000000000n,
1057
+ "commercial-tx": 100000000000000n
1058
+ }
1059
+ },
1060
+ 66238: {
1061
+ decimals: 18,
1062
+ nativeSymbol: "OMA",
1063
+ explorer: "https://explorer.testnet.chain.oma3.org",
1064
+ base: {
1065
+ "shared-control": 10000000000000000n,
1066
+ "commercial-tx": 100000000000000n
1067
+ }
1068
+ }
1069
+ };
1070
+ var AMOUNT_DOMAIN = "OMATrust:Amount:v1";
1071
+ function getConfig(chainId) {
1072
+ const config = CHAIN_CONFIGS[chainId];
1073
+ if (!config) {
1074
+ throw new OmaTrustError("UNSUPPORTED_CHAIN", "Chain is not supported", {
1075
+ chainId,
1076
+ supported: getSupportedChainIds()
1077
+ });
1078
+ }
1079
+ return config;
1080
+ }
1081
+ function getSupportedChainIds() {
1082
+ return Object.keys(CHAIN_CONFIGS).map((id) => Number(id));
1083
+ }
1084
+ function isChainSupported(chainId) {
1085
+ return chainId in CHAIN_CONFIGS;
1086
+ }
1087
+ function getChainConstants(chainId, purpose) {
1088
+ const config = getConfig(chainId);
1089
+ const base = config.base[purpose];
1090
+ const range = base / 10n;
1091
+ return {
1092
+ base,
1093
+ range,
1094
+ decimals: config.decimals,
1095
+ nativeSymbol: config.nativeSymbol
1096
+ };
1097
+ }
1098
+ function constructSeed(subjectDidHash, counterpartyDidHash, purpose) {
1099
+ const seed = {
1100
+ domain: AMOUNT_DOMAIN,
1101
+ subjectDidHash,
1102
+ counterpartyIdHash: counterpartyDidHash,
1103
+ proofPurpose: purpose
1104
+ };
1105
+ const canonical = canonicalize__default.default(seed);
1106
+ if (!canonical) {
1107
+ throw new OmaTrustError("INVALID_INPUT", "Failed to canonicalize seed");
1108
+ }
1109
+ return ethers.toUtf8Bytes(canonical);
1110
+ }
1111
+ function hashSeed(seedBytes, chainId) {
1112
+ if (!isChainSupported(chainId)) {
1113
+ throw new OmaTrustError("UNSUPPORTED_CHAIN", "Chain is not supported", { chainId });
1114
+ }
1115
+ if (chainId === 0) {
1116
+ return ethers.sha256(seedBytes);
1117
+ }
1118
+ return ethers.keccak256(seedBytes);
1119
+ }
1120
+ function calculateTransferAmount(subject, counterparty, chainId, purpose) {
1121
+ const { base, range } = getChainConstants(chainId, purpose);
1122
+ const subjectDidHash = computeDidHash(subject);
1123
+ const counterpartyDidHash = computeDidHash(counterparty);
1124
+ const seed = constructSeed(subjectDidHash, counterpartyDidHash, purpose);
1125
+ const hashed = hashSeed(seed, chainId);
1126
+ const offset = BigInt(hashed) % range;
1127
+ return base + offset;
1128
+ }
1129
+ function calculateTransferAmountFromAddresses(subjectAddress, counterpartyAddress, chainId, purpose) {
1130
+ return calculateTransferAmount(
1131
+ buildEvmDidPkh(chainId, subjectAddress),
1132
+ buildEvmDidPkh(chainId, counterpartyAddress),
1133
+ chainId,
1134
+ purpose
1135
+ );
1136
+ }
1137
+ function createTxEncodedValueProof(chainId, txHash, purpose) {
1138
+ if (!/^0x[0-9a-fA-F]{64}$/.test(txHash)) {
1139
+ throw new OmaTrustError("INVALID_INPUT", "txHash must be a 32-byte hex string", { txHash });
1140
+ }
1141
+ return {
1142
+ proofType: "tx-encoded-value",
1143
+ proofPurpose: purpose,
1144
+ proofObject: {
1145
+ chainId: `eip155:${chainId}`,
1146
+ txHash
1147
+ },
1148
+ version: 1,
1149
+ issuedAt: Math.floor(Date.now() / 1e3)
1150
+ };
1151
+ }
1152
+ function formatTransferAmount(amount, chainId) {
1153
+ const config = getConfig(chainId);
1154
+ const normalized = typeof amount === "number" ? BigInt(Math.floor(amount)) : amount;
1155
+ return `${ethers.formatUnits(normalized, config.decimals)} ${config.nativeSymbol}`;
1156
+ }
1157
+ function getExplorerTxUrl(chainId, txHash) {
1158
+ return `${getConfig(chainId).explorer}/tx/${txHash}`;
1159
+ }
1160
+ function getExplorerAddressUrl(chainId, address) {
1161
+ return `${getConfig(chainId).explorer}/address/${address}`;
1162
+ }
1163
+
1164
+ // src/reputation/proof/did-json.ts
1165
+ init_did();
1166
+ init_errors();
1167
+ async function fetchDidDocument(domain) {
1168
+ const normalized = domain.toLowerCase().replace(/\.$/, "");
1169
+ const url = `https://${normalized}/.well-known/did.json`;
1170
+ let response;
1171
+ try {
1172
+ response = await fetch(url, { headers: { Accept: "application/json" } });
1173
+ } catch (err) {
1174
+ throw new OmaTrustError("NETWORK_ERROR", "Failed to fetch DID document", { domain, err });
1175
+ }
1176
+ if (!response.ok) {
1177
+ throw new OmaTrustError("NETWORK_ERROR", "DID document fetch failed", {
1178
+ domain,
1179
+ status: response.status
1180
+ });
1181
+ }
1182
+ const body = await response.json();
1183
+ return body;
1184
+ }
1185
+ function extractAddressesFromDidDocument(didDocument) {
1186
+ const methods = didDocument.verificationMethod;
1187
+ if (!Array.isArray(methods)) {
1188
+ return [];
1189
+ }
1190
+ const addresses = /* @__PURE__ */ new Set();
1191
+ for (const method of methods) {
1192
+ const blockchainAccountId = method.blockchainAccountId;
1193
+ if (typeof blockchainAccountId === "string") {
1194
+ try {
1195
+ addresses.add(ethers.getAddress(extractAddressFromDid(blockchainAccountId)));
1196
+ } catch {
1197
+ }
1198
+ }
1199
+ const publicKeyHex = method.publicKeyHex;
1200
+ if (typeof publicKeyHex === "string") {
1201
+ const prefixed = publicKeyHex.startsWith("0x") ? publicKeyHex : `0x${publicKeyHex}`;
1202
+ if (ethers.isAddress(prefixed)) {
1203
+ addresses.add(ethers.getAddress(prefixed));
1204
+ }
1205
+ }
1206
+ }
1207
+ return [...addresses];
1208
+ }
1209
+ function verifyDidDocumentControllerDid(didDocument, expectedControllerDid) {
1210
+ let expectedAddress;
1211
+ try {
1212
+ expectedAddress = ethers.getAddress(extractAddressFromDid(expectedControllerDid));
1213
+ } catch {
1214
+ return { valid: false, reason: "Expected controller DID does not resolve to an EVM address" };
1215
+ }
1216
+ const addresses = extractAddressesFromDidDocument(didDocument);
1217
+ if (addresses.some((address) => address.toLowerCase() === expectedAddress.toLowerCase())) {
1218
+ return { valid: true };
1219
+ }
1220
+ return {
1221
+ valid: false,
1222
+ reason: `No matching address found in DID document (expected ${expectedAddress})`
1223
+ };
1224
+ }
1225
+ async function verifyDidJsonControllerDid(domain, expectedControllerDid, options = {}) {
1226
+ if (!domain || typeof domain !== "string") {
1227
+ throw new OmaTrustError("INVALID_INPUT", "domain must be a non-empty string", { domain });
1228
+ }
1229
+ const didDocument = options.fetchDidDocument ? await options.fetchDidDocument(domain) : await fetchDidDocument(domain);
1230
+ return verifyDidDocumentControllerDid(didDocument, expectedControllerDid);
1231
+ }
1232
+
1233
+ // src/reputation/proof/eip712.ts
1234
+ init_errors();
1235
+ function buildEip712Domain(name, version, chainId, verifyingContract) {
1236
+ return { name, version, chainId, verifyingContract };
1237
+ }
1238
+ function getOmaTrustProofEip712Types() {
1239
+ return {
1240
+ primaryType: "OmaTrustProof",
1241
+ types: {
1242
+ OmaTrustProof: [
1243
+ { name: "signer", type: "address" },
1244
+ { name: "authorizedEntity", type: "string" },
1245
+ { name: "signingPurpose", type: "string" },
1246
+ { name: "creationTimestamp", type: "uint256" },
1247
+ { name: "expirationTimestamp", type: "uint256" },
1248
+ { name: "randomValue", type: "bytes32" },
1249
+ { name: "statement", type: "string" }
1250
+ ]
1251
+ }
1252
+ };
1253
+ }
1254
+ function verifyEip712Signature(typedData, signature) {
1255
+ try {
1256
+ const signer = ethers.verifyTypedData(
1257
+ typedData.domain,
1258
+ typedData.types,
1259
+ typedData.message,
1260
+ signature
1261
+ );
1262
+ return { valid: true, signer };
1263
+ } catch (err) {
1264
+ throw new OmaTrustError("INVALID_INPUT", "Failed to verify EIP-712 signature", { err });
1265
+ }
1266
+ }
1267
+
1268
+ // src/reputation/verify.ts
1269
+ init_dns_txt_record();
1270
+ function parseChainId(input) {
1271
+ if (typeof input === "number") {
1272
+ return input;
1273
+ }
1274
+ if (typeof input === "string") {
1275
+ if (input.includes(":")) {
1276
+ const [, chainId] = input.split(":");
1277
+ return Number(chainId);
1278
+ }
1279
+ return Number(input);
1280
+ }
1281
+ return NaN;
1282
+ }
1283
+ function parseProofs(attestation) {
1284
+ const rawProofs = attestation.data.proofs;
1285
+ if (!Array.isArray(rawProofs)) {
1286
+ return [];
1287
+ }
1288
+ return rawProofs.map((entry) => {
1289
+ if (typeof entry === "string") {
1290
+ try {
1291
+ return JSON.parse(entry);
1292
+ } catch {
1293
+ return null;
1294
+ }
1295
+ }
1296
+ if (entry && typeof entry === "object") {
1297
+ return entry;
1298
+ }
1299
+ return null;
1300
+ }).filter((proof) => Boolean(proof?.proofType));
1301
+ }
1302
+ function getProofPurpose(proof) {
1303
+ if (proof.proofPurpose === "commercial-tx") {
1304
+ return "commercial-tx";
1305
+ }
1306
+ return "shared-control";
1307
+ }
1308
+ function decodeJwtPayload(compactJws) {
1309
+ const parts = compactJws.split(".");
1310
+ if (parts.length !== 3) {
1311
+ throw new OmaTrustError("PROOF_VERIFICATION_FAILED", "Invalid compact JWS format");
1312
+ }
1313
+ const payloadB64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
1314
+ const padded = payloadB64.padEnd(payloadB64.length + (4 - payloadB64.length % 4) % 4, "=");
1315
+ let json;
1316
+ if (typeof atob === "function") {
1317
+ json = decodeURIComponent(
1318
+ Array.from(atob(padded)).map((char) => `%${char.charCodeAt(0).toString(16).padStart(2, "0")}`).join("")
1319
+ );
1320
+ } else {
1321
+ json = Buffer.from(padded, "base64").toString("utf8");
1322
+ }
1323
+ return JSON.parse(json);
1324
+ }
1325
+ async function verifyProof(params) {
1326
+ const { proof, provider, expectedSubject, expectedController } = params;
1327
+ try {
1328
+ switch (proof.proofType) {
1329
+ case "tx-encoded-value": {
1330
+ if (!provider) {
1331
+ return { valid: false, proofType: proof.proofType, reason: "Provider is required" };
1332
+ }
1333
+ if (!expectedSubject || !expectedController) {
1334
+ return {
1335
+ valid: false,
1336
+ proofType: proof.proofType,
1337
+ reason: "expectedSubject and expectedController are required"
1338
+ };
1339
+ }
1340
+ const proofObject = proof.proofObject;
1341
+ const chainId = parseChainId(proofObject.chainId);
1342
+ const tx = await provider.getTransaction(
1343
+ proofObject.txHash
1344
+ );
1345
+ if (!tx) {
1346
+ return { valid: false, proofType: proof.proofType, reason: "Transaction not found" };
1347
+ }
1348
+ const expectedAmount = calculateTransferAmount(
1349
+ expectedSubject,
1350
+ expectedController,
1351
+ chainId,
1352
+ getProofPurpose(proof)
1353
+ );
1354
+ const subjectAddress = ethers.getAddress(extractAddressFromDid(expectedSubject));
1355
+ const controllerAddress = ethers.getAddress(extractAddressFromDid(expectedController));
1356
+ if (tx.from && ethers.getAddress(tx.from) !== subjectAddress) {
1357
+ return { valid: false, proofType: proof.proofType, reason: "Transaction sender mismatch" };
1358
+ }
1359
+ if (tx.to && ethers.getAddress(tx.to) !== controllerAddress) {
1360
+ return { valid: false, proofType: proof.proofType, reason: "Transaction recipient mismatch" };
1361
+ }
1362
+ if (BigInt(tx.value) !== expectedAmount) {
1363
+ return { valid: false, proofType: proof.proofType, reason: "Transaction amount mismatch" };
1364
+ }
1365
+ return { valid: true, proofType: proof.proofType };
1366
+ }
1367
+ case "tx-interaction": {
1368
+ if (!provider) {
1369
+ return { valid: false, proofType: proof.proofType, reason: "Provider is required" };
1370
+ }
1371
+ const proofObject = proof.proofObject;
1372
+ const tx = await provider.getTransaction(
1373
+ proofObject.txHash
1374
+ );
1375
+ if (!tx) {
1376
+ return { valid: false, proofType: proof.proofType, reason: "Transaction not found" };
1377
+ }
1378
+ if (!tx.to) {
1379
+ return { valid: false, proofType: proof.proofType, reason: "Transaction target missing" };
1380
+ }
1381
+ return { valid: true, proofType: proof.proofType };
1382
+ }
1383
+ case "pop-eip712": {
1384
+ const object = proof.proofObject;
1385
+ const typedData = {
1386
+ domain: object.domain,
1387
+ types: {
1388
+ OmaTrustProof: [
1389
+ { name: "signer", type: "address" },
1390
+ { name: "authorizedEntity", type: "string" },
1391
+ { name: "signingPurpose", type: "string" },
1392
+ { name: "creationTimestamp", type: "uint256" },
1393
+ { name: "expirationTimestamp", type: "uint256" },
1394
+ { name: "randomValue", type: "bytes32" },
1395
+ { name: "statement", type: "string" }
1396
+ ]
1397
+ },
1398
+ message: object.message
1399
+ };
1400
+ const verification = verifyEip712Signature(typedData, object.signature);
1401
+ if (!verification.valid || !verification.signer) {
1402
+ return { valid: false, proofType: proof.proofType, reason: "Invalid EIP-712 signature" };
1403
+ }
1404
+ if (typeof object.message.signer === "string") {
1405
+ const expected = ethers.getAddress(object.message.signer);
1406
+ if (ethers.getAddress(verification.signer) !== expected) {
1407
+ return { valid: false, proofType: proof.proofType, reason: "Recovered signer mismatch" };
1408
+ }
1409
+ }
1410
+ return { valid: true, proofType: proof.proofType };
1411
+ }
1412
+ case "pop-jws": {
1413
+ if (typeof proof.proofObject !== "string") {
1414
+ return { valid: false, proofType: proof.proofType, reason: "Invalid JWS proof payload" };
1415
+ }
1416
+ const payload = decodeJwtPayload(proof.proofObject);
1417
+ const now = Math.floor(Date.now() / 1e3);
1418
+ const exp = payload.exp;
1419
+ if (typeof exp === "number" && exp < now) {
1420
+ return { valid: false, proofType: proof.proofType, reason: "JWS proof expired" };
1421
+ }
1422
+ return { valid: true, proofType: proof.proofType };
1423
+ }
1424
+ case "x402-receipt":
1425
+ case "x402-offer": {
1426
+ if (!proof.proofObject || typeof proof.proofObject !== "object") {
1427
+ return { valid: false, proofType: proof.proofType, reason: "Invalid x402 proof object" };
1428
+ }
1429
+ return { valid: true, proofType: proof.proofType };
1430
+ }
1431
+ case "evidence-pointer": {
1432
+ const object = proof.proofObject;
1433
+ if (!object.url) {
1434
+ return { valid: false, proofType: proof.proofType, reason: "Missing evidence URL" };
1435
+ }
1436
+ const response = await fetch(object.url);
1437
+ if (!response.ok) {
1438
+ return { valid: false, proofType: proof.proofType, reason: `Evidence fetch failed (${response.status})` };
1439
+ }
1440
+ if (object.url.endsWith("/.well-known/did.json") && expectedController) {
1441
+ const didDoc = await response.json();
1442
+ const didCheck = verifyDidDocumentControllerDid(didDoc, expectedController);
1443
+ return {
1444
+ valid: didCheck.valid,
1445
+ proofType: proof.proofType,
1446
+ reason: didCheck.reason
1447
+ };
1448
+ }
1449
+ const body = await response.text();
1450
+ if (expectedController && !body.includes(expectedController)) {
1451
+ try {
1452
+ const parsed = parseDnsTxtRecord(body);
1453
+ if (parsed.controller !== expectedController) {
1454
+ return {
1455
+ valid: false,
1456
+ proofType: proof.proofType,
1457
+ reason: "Evidence does not include expected controller DID"
1458
+ };
1459
+ }
1460
+ } catch {
1461
+ return {
1462
+ valid: false,
1463
+ proofType: proof.proofType,
1464
+ reason: "Evidence does not include expected controller DID"
1465
+ };
1466
+ }
1467
+ }
1468
+ return { valid: true, proofType: proof.proofType };
1469
+ }
1470
+ default:
1471
+ return { valid: false, proofType: proof.proofType, reason: "Unsupported proof type" };
1472
+ }
1473
+ } catch (err) {
1474
+ throw new OmaTrustError("PROOF_VERIFICATION_FAILED", "Proof verification failed", {
1475
+ proofType: proof.proofType,
1476
+ err
1477
+ });
1478
+ }
1479
+ }
1480
+ async function verifyAttestation(params) {
1481
+ const proofs = parseProofs(params.attestation);
1482
+ const checks = {};
1483
+ const reasons = [];
1484
+ const now = BigInt(Math.floor(Date.now() / 1e3));
1485
+ if (params.attestation.revocationTime > 0n) {
1486
+ checks.revocation = false;
1487
+ reasons.push("attestation revoked");
1488
+ } else {
1489
+ checks.revocation = true;
1490
+ }
1491
+ if (params.attestation.expirationTime > 0n && params.attestation.expirationTime < now) {
1492
+ checks.expiration = false;
1493
+ reasons.push("attestation expired");
1494
+ } else {
1495
+ checks.expiration = true;
1496
+ }
1497
+ if (proofs.length === 0) {
1498
+ checks.proofs = false;
1499
+ reasons.push("no proofs provided");
1500
+ }
1501
+ const selectedProofTypes = params.checks ?? proofs.map((proof) => proof.proofType);
1502
+ for (const proof of proofs) {
1503
+ if (!selectedProofTypes.includes(proof.proofType)) {
1504
+ continue;
1505
+ }
1506
+ const result = await verifyProof({
1507
+ proof,
1508
+ provider: params.provider,
1509
+ expectedSubject: params.context?.subject,
1510
+ expectedController: params.context?.controller
1511
+ });
1512
+ checks[proof.proofType] = result.valid;
1513
+ if (!result.valid) {
1514
+ reasons.push(result.reason ?? `${proof.proofType} verification failed`);
1515
+ }
1516
+ }
1517
+ return {
1518
+ valid: reasons.length === 0,
1519
+ checks,
1520
+ reasons
1521
+ };
1522
+ }
1523
+
1524
+ // src/reputation/schema.ts
1525
+ init_errors();
1526
+ async function verifySchemaExists(schemaRegistry, schemaUid) {
1527
+ const registry = schemaRegistry;
1528
+ try {
1529
+ const schema = await registry.getSchema({ uid: schemaUid });
1530
+ return Boolean(schema && schema.uid && schema.uid !== "0x".padEnd(66, "0"));
1531
+ } catch {
1532
+ return false;
1533
+ }
1534
+ }
1535
+ async function getSchemaDetails(schemaRegistry, schemaUid) {
1536
+ const registry = schemaRegistry;
1537
+ try {
1538
+ const details = await registry.getSchema({ uid: schemaUid });
1539
+ if (!details || !details.uid || details.uid === "0x".padEnd(66, "0")) {
1540
+ throw new OmaTrustError("SCHEMA_NOT_FOUND", "Schema was not found", { schemaUid });
1541
+ }
1542
+ return {
1543
+ uid: formatSchemaUid(details.uid),
1544
+ schema: details.schema,
1545
+ resolver: details.resolver,
1546
+ revocable: Boolean(details.revocable)
1547
+ };
1548
+ } catch (err) {
1549
+ if (isEasSchemaNotFoundError(err)) {
1550
+ throw new OmaTrustError("SCHEMA_NOT_FOUND", "Schema was not found", { schemaUid });
1551
+ }
1552
+ if (err instanceof OmaTrustError) {
1553
+ throw err;
1554
+ }
1555
+ throw new OmaTrustError("NETWORK_ERROR", "Failed to read schema details", { schemaUid, err });
1556
+ }
1557
+ }
1558
+ function formatSchemaUid(schemaUid) {
1559
+ if (!schemaUid) {
1560
+ throw new OmaTrustError("INVALID_INPUT", "schemaUid is required");
1561
+ }
1562
+ const value = schemaUid.startsWith("0x") ? schemaUid.toLowerCase() : `0x${schemaUid.toLowerCase()}`;
1563
+ if (!/^0x[0-9a-f]{64}$/.test(value)) {
1564
+ throw new OmaTrustError("INVALID_INPUT", "schemaUid must be a 32-byte hex string", { schemaUid });
1565
+ }
1566
+ return value;
1567
+ }
1568
+
1569
+ // src/reputation/witness.ts
1570
+ init_errors();
1571
+ async function callMethod(params, method) {
1572
+ let response;
1573
+ try {
1574
+ response = await fetch(params.gatewayUrl, {
1575
+ method: "POST",
1576
+ headers: { "Content-Type": "application/json" },
1577
+ body: JSON.stringify({
1578
+ attestationUid: params.attestationUid,
1579
+ chainId: params.chainId,
1580
+ easContract: params.easContract,
1581
+ schemaUid: params.schemaUid,
1582
+ subject: params.subject,
1583
+ controller: params.controller,
1584
+ method
1585
+ }),
1586
+ signal: AbortSignal.timeout(params.timeoutMs ?? 15e3)
1587
+ });
1588
+ } catch (err) {
1589
+ throw new OmaTrustError("NETWORK_ERROR", "Controller witness request failed", { method, err });
1590
+ }
1591
+ const details = await response.json().catch(() => void 0);
1592
+ if (!response.ok) {
1593
+ return null;
1594
+ }
1595
+ return {
1596
+ ok: true,
1597
+ method,
1598
+ details
1599
+ };
1600
+ }
1601
+ async function callControllerWitness(params) {
1602
+ const dnsResult = await callMethod(params, "dns-txt").catch(() => null);
1603
+ if (dnsResult) {
1604
+ return dnsResult;
1605
+ }
1606
+ const didJsonResult = await callMethod(params, "did-json").catch(() => null);
1607
+ if (didJsonResult) {
1608
+ return didJsonResult;
1609
+ }
1610
+ return {
1611
+ ok: false,
1612
+ method: "did-json"
1613
+ };
1614
+ }
1615
+
1616
+ // src/reputation/proof/tx-interaction.ts
1617
+ init_errors();
1618
+ function createTxInteractionProof(chainId, txHash) {
1619
+ if (!/^0x[0-9a-fA-F]{64}$/.test(txHash)) {
1620
+ throw new OmaTrustError("INVALID_INPUT", "txHash must be a 32-byte hex string", { txHash });
1621
+ }
1622
+ return {
1623
+ proofType: "tx-interaction",
1624
+ proofPurpose: "commercial-tx",
1625
+ proofObject: {
1626
+ chainId: `eip155:${chainId}`,
1627
+ txHash
1628
+ },
1629
+ version: 1,
1630
+ issuedAt: Math.floor(Date.now() / 1e3)
1631
+ };
1632
+ }
1633
+
1634
+ // src/reputation/proof/pop-eip712.ts
1635
+ init_errors();
1636
+ async function createPopEip712Proof(params, signFn) {
1637
+ if (!params.signer || !params.authorizedEntity) {
1638
+ throw new OmaTrustError("INVALID_INPUT", "signer and authorizedEntity are required", { params });
1639
+ }
1640
+ const now = Math.floor(Date.now() / 1e3);
1641
+ const creationTimestamp = params.creationTimestamp ?? now;
1642
+ const expirationTimestamp = params.expirationTimestamp ?? now + 600;
1643
+ const randomValue = params.randomValue ?? ethers.hexlify(ethers.randomBytes(32));
1644
+ const message = {
1645
+ signer: params.signer,
1646
+ authorizedEntity: params.authorizedEntity,
1647
+ signingPurpose: params.signingPurpose,
1648
+ creationTimestamp,
1649
+ expirationTimestamp,
1650
+ randomValue,
1651
+ statement: params.statement ?? "This is not a transaction or asset approval."
1652
+ };
1653
+ const { types, primaryType } = getOmaTrustProofEip712Types();
1654
+ const typedData = {
1655
+ domain: {
1656
+ name: "OMATrust Proof",
1657
+ version: "1",
1658
+ chainId: params.chainId
1659
+ },
1660
+ types,
1661
+ primaryType,
1662
+ message
1663
+ };
1664
+ const signature = await signFn(typedData);
1665
+ return {
1666
+ proofType: "pop-eip712",
1667
+ proofObject: {
1668
+ domain: typedData.domain,
1669
+ message,
1670
+ signature
1671
+ },
1672
+ version: 1,
1673
+ issuedAt: creationTimestamp,
1674
+ expiresAt: expirationTimestamp
1675
+ };
1676
+ }
1677
+
1678
+ // src/reputation/proof/pop-jws.ts
1679
+ init_errors();
1680
+ async function createPopJwsProof(params, signFn) {
1681
+ if (!params.issuer || !params.audience) {
1682
+ throw new OmaTrustError("INVALID_INPUT", "issuer and audience are required", { params });
1683
+ }
1684
+ const now = Math.floor(Date.now() / 1e3);
1685
+ const payload = {
1686
+ iss: params.issuer,
1687
+ aud: params.audience,
1688
+ purpose: params.purpose,
1689
+ iat: params.issuedAt ?? now,
1690
+ exp: params.expiresAt ?? now + 600,
1691
+ nonce: params.nonce ?? (globalThis.crypto?.randomUUID ? globalThis.crypto.randomUUID() : `${Date.now()}-${Math.random()}`)
1692
+ };
1693
+ const header = {
1694
+ typ: "JWT",
1695
+ alg: "ES256K"
1696
+ };
1697
+ const jws = await signFn(payload, header);
1698
+ return {
1699
+ proofType: "pop-jws",
1700
+ proofObject: jws,
1701
+ proofPurpose: params.purpose,
1702
+ version: 1,
1703
+ issuedAt: payload.iat,
1704
+ expiresAt: payload.exp
1705
+ };
1706
+ }
1707
+
1708
+ // src/reputation/proof/x402.ts
1709
+ function createX402ReceiptProof(receipt) {
1710
+ return {
1711
+ proofType: "x402-receipt",
1712
+ proofPurpose: "commercial-tx",
1713
+ proofObject: receipt,
1714
+ version: 1,
1715
+ issuedAt: Math.floor(Date.now() / 1e3)
1716
+ };
1717
+ }
1718
+ function createX402OfferProof(offer) {
1719
+ return {
1720
+ proofType: "x402-offer",
1721
+ proofPurpose: "commercial-tx",
1722
+ proofObject: offer,
1723
+ version: 1,
1724
+ issuedAt: Math.floor(Date.now() / 1e3)
1725
+ };
1726
+ }
1727
+
1728
+ // src/reputation/proof/evidence-pointer.ts
1729
+ init_errors();
1730
+ function createEvidencePointerProof(url) {
1731
+ if (!url || typeof url !== "string") {
1732
+ throw new OmaTrustError("INVALID_INPUT", "url must be a non-empty string", { url });
1733
+ }
1734
+ return {
1735
+ proofType: "evidence-pointer",
1736
+ proofPurpose: "shared-control",
1737
+ proofObject: { url },
1738
+ version: 1,
1739
+ issuedAt: Math.floor(Date.now() / 1e3)
1740
+ };
1741
+ }
1742
+
1743
+ // src/reputation/proof/dns-txt.browser.ts
1744
+ init_errors();
1745
+ init_dns_txt_record();
1746
+ async function verifyDnsTxtControllerDid2(domain, expectedControllerDid, options = {}) {
1747
+ if (options.resolveTxt) {
1748
+ const { verifyDnsTxtControllerDid: verifyWithResolver } = await Promise.resolve().then(() => (init_dns_txt_shared(), dns_txt_shared_exports));
1749
+ return verifyWithResolver(domain, expectedControllerDid, options);
1750
+ }
1751
+ throw new OmaTrustError(
1752
+ "NETWORK_ERROR",
1753
+ "verifyDnsTxtControllerDid is not available in browser runtimes",
1754
+ {
1755
+ domain,
1756
+ expectedControllerDid
1757
+ }
1758
+ );
1759
+ }
1760
+
1761
+ // src/reputation/proof/subject-ownership.ts
1762
+ init_did();
1763
+ init_errors();
1764
+ init_dns_txt_shared();
1765
+ var EIP1967_ADMIN_SLOT = "0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103";
1766
+ var OWNERSHIP_PATTERNS = [
1767
+ { method: "owner", signature: "function owner() view returns (address)" },
1768
+ { method: "admin", signature: "function admin() view returns (address)" },
1769
+ { method: "getOwner", signature: "function getOwner() view returns (address)" }
1770
+ ];
1771
+ function assertConnectedWalletDid(input) {
1772
+ const normalized = normalizeDid(input);
1773
+ if (extractDidMethod(normalized) !== "pkh") {
1774
+ throw new OmaTrustError("INVALID_INPUT", "connectedWalletDid must be a did:pkh DID", {
1775
+ connectedWalletDid: input
1776
+ });
1777
+ }
1778
+ return normalized;
1779
+ }
1780
+ function normalizeSubjectDid(input) {
1781
+ return normalizeDid(input);
1782
+ }
1783
+ async function readAddressFromContract(provider, contractAddress, signature, method) {
1784
+ try {
1785
+ const iface = new ethers.Interface([signature]);
1786
+ const data = iface.encodeFunctionData(method, []);
1787
+ const result = await provider.call({ to: contractAddress, data });
1788
+ const [value] = iface.decodeFunctionResult(method, result);
1789
+ if (typeof value === "string" && ethers.isAddress(value) && value !== ethers.ZeroAddress) {
1790
+ return ethers.getAddress(value);
1791
+ }
1792
+ } catch {
1793
+ }
1794
+ return null;
1795
+ }
1796
+ async function discoverControllingWallet(provider, contractAddress, chainId) {
1797
+ for (const pattern of OWNERSHIP_PATTERNS) {
1798
+ const address = await readAddressFromContract(
1799
+ provider,
1800
+ contractAddress,
1801
+ pattern.signature,
1802
+ pattern.method
1803
+ );
1804
+ if (address) {
1805
+ return buildEvmDidPkh(chainId, address);
1806
+ }
1807
+ }
1808
+ try {
1809
+ const adminValue = await provider.getStorage(contractAddress, EIP1967_ADMIN_SLOT);
1810
+ if (adminValue && adminValue !== "0x" && adminValue !== "0x0000000000000000000000000000000000000000000000000000000000000000") {
1811
+ const adminAddress = ethers.getAddress(`0x${adminValue.slice(-40)}`);
1812
+ if (adminAddress !== ethers.ZeroAddress) {
1813
+ return buildEvmDidPkh(chainId, adminAddress);
1814
+ }
1815
+ }
1816
+ } catch {
1817
+ }
1818
+ return null;
1819
+ }
1820
+ async function verifyDidWebOwnership(params) {
1821
+ const subjectDid = normalizeSubjectDid(params.subjectDid);
1822
+ const connectedWalletDid = assertConnectedWalletDid(params.connectedWalletDid);
1823
+ const domain = getDomainFromDidWeb(subjectDid);
1824
+ if (!domain) {
1825
+ throw new OmaTrustError("INVALID_INPUT", "subjectDid must be a did:web DID", {
1826
+ subjectDid: params.subjectDid
1827
+ });
1828
+ }
1829
+ let dnsReason;
1830
+ try {
1831
+ const dnsResult = await verifyDnsTxtControllerDid(domain, connectedWalletDid, {
1832
+ resolveTxt: params.resolveTxt,
1833
+ recordPrefix: params.recordPrefix
1834
+ });
1835
+ if (dnsResult.valid) {
1836
+ return {
1837
+ valid: true,
1838
+ method: "dns",
1839
+ details: `Verified via DNS TXT record at ${params.recordPrefix ?? "_controllers"}.${domain}`,
1840
+ subjectDid,
1841
+ connectedWalletDid
1842
+ };
1843
+ }
1844
+ dnsReason = dnsResult.reason;
1845
+ } catch (error) {
1846
+ dnsReason = error instanceof Error ? error.message : "DNS TXT verification failed";
1847
+ }
1848
+ let didDocReason;
1849
+ try {
1850
+ const didDocumentResult = await verifyDidJsonControllerDid(domain, connectedWalletDid, {
1851
+ fetchDidDocument: params.fetchDidDocument
1852
+ });
1853
+ if (didDocumentResult.valid) {
1854
+ return {
1855
+ valid: true,
1856
+ method: "did-document",
1857
+ details: `Verified via DID document at https://${domain}/.well-known/did.json`,
1858
+ subjectDid,
1859
+ connectedWalletDid
1860
+ };
1861
+ }
1862
+ didDocReason = didDocumentResult.reason;
1863
+ } catch (error) {
1864
+ didDocReason = error instanceof Error ? error.message : "DID document verification failed";
1865
+ }
1866
+ return {
1867
+ valid: false,
1868
+ reason: "DID ownership verification failed",
1869
+ details: `DNS check: ${dnsReason ?? "failed"}. DID document check: ${didDocReason ?? "failed"}.`,
1870
+ subjectDid,
1871
+ connectedWalletDid
1872
+ };
1873
+ }
1874
+ async function verifyDidPkhOwnership(params) {
1875
+ const subjectDid = normalizeSubjectDid(params.subjectDid);
1876
+ const connectedWalletDid = assertConnectedWalletDid(params.connectedWalletDid);
1877
+ if (!isEvmDidPkh(subjectDid)) {
1878
+ throw new OmaTrustError("INVALID_INPUT", "subjectDid must be an EVM did:pkh DID", {
1879
+ subjectDid: params.subjectDid
1880
+ });
1881
+ }
1882
+ const subjectAddress = getAddressFromDidPkh(subjectDid);
1883
+ const connectedWalletAddress = getAddressFromDidPkh(connectedWalletDid);
1884
+ const chainIdRaw = getChainIdFromDidPkh(subjectDid);
1885
+ if (!subjectAddress || !connectedWalletAddress || !chainIdRaw) {
1886
+ throw new OmaTrustError("INVALID_INPUT", "Could not parse did:pkh ownership inputs", {
1887
+ subjectDid: params.subjectDid,
1888
+ connectedWalletDid: params.connectedWalletDid
1889
+ });
1890
+ }
1891
+ const chainId = Number(chainIdRaw);
1892
+ if (!Number.isFinite(chainId)) {
1893
+ throw new OmaTrustError("INVALID_INPUT", "Invalid chain id in subjectDid", {
1894
+ subjectDid: params.subjectDid
1895
+ });
1896
+ }
1897
+ const code = await params.provider.getCode(subjectAddress);
1898
+ const isContract = code !== "0x" && code !== "0x0";
1899
+ if (!isContract) {
1900
+ if (ethers.getAddress(subjectAddress) === ethers.getAddress(connectedWalletAddress)) {
1901
+ return {
1902
+ valid: true,
1903
+ method: "wallet",
1904
+ details: "Verified direct wallet ownership from matching did:pkh subject and connected wallet",
1905
+ subjectDid,
1906
+ connectedWalletDid
1907
+ };
1908
+ }
1909
+ return {
1910
+ valid: false,
1911
+ reason: "EOA did:pkh subject does not match connected wallet",
1912
+ details: "For direct wallet did:pkh subjects, connectedWalletDid must match the subject DID.",
1913
+ subjectDid,
1914
+ connectedWalletDid
1915
+ };
1916
+ }
1917
+ const controllingWalletDid = await discoverControllingWallet(params.provider, subjectAddress, chainId);
1918
+ if (params.txHash) {
1919
+ if (!controllingWalletDid) {
1920
+ return {
1921
+ valid: false,
1922
+ reason: "Could not discover controlling wallet",
1923
+ details: "Contract does not expose owner/admin/getOwner or a readable EIP-1967 admin slot for transfer verification.",
1924
+ subjectDid,
1925
+ connectedWalletDid
1926
+ };
1927
+ }
1928
+ const tx = await params.provider.getTransaction(params.txHash);
1929
+ if (!tx) {
1930
+ return {
1931
+ valid: false,
1932
+ reason: "Transaction not found",
1933
+ details: `Transaction ${params.txHash} was not found on chain ${chainId}.`,
1934
+ subjectDid,
1935
+ connectedWalletDid,
1936
+ controllingWalletDid
1937
+ };
1938
+ }
1939
+ const receipt = await params.provider.getTransactionReceipt(params.txHash);
1940
+ if (!receipt) {
1941
+ return {
1942
+ valid: false,
1943
+ reason: "Transaction not confirmed",
1944
+ details: "Transaction exists but is not yet confirmed.",
1945
+ subjectDid,
1946
+ connectedWalletDid,
1947
+ controllingWalletDid
1948
+ };
1949
+ }
1950
+ const controllingWalletAddress = getAddressFromDidPkh(controllingWalletDid);
1951
+ if (!tx.from || !controllingWalletAddress || ethers.getAddress(tx.from) !== ethers.getAddress(controllingWalletAddress)) {
1952
+ return {
1953
+ valid: false,
1954
+ reason: "Wrong sender",
1955
+ details: `Transfer must originate from controlling wallet ${controllingWalletDid}.`,
1956
+ subjectDid,
1957
+ connectedWalletDid,
1958
+ controllingWalletDid
1959
+ };
1960
+ }
1961
+ if (!tx.to || ethers.getAddress(tx.to) !== ethers.getAddress(connectedWalletAddress)) {
1962
+ return {
1963
+ valid: false,
1964
+ reason: "Wrong recipient",
1965
+ details: `Transfer must be sent to connected wallet ${connectedWalletDid}.`,
1966
+ subjectDid,
1967
+ connectedWalletDid,
1968
+ controllingWalletDid
1969
+ };
1970
+ }
1971
+ const expectedAmount = calculateTransferAmount(
1972
+ subjectDid,
1973
+ connectedWalletDid,
1974
+ chainId,
1975
+ "shared-control"
1976
+ );
1977
+ const actualValue = BigInt(tx.value ?? 0n);
1978
+ if (actualValue !== expectedAmount) {
1979
+ return {
1980
+ valid: false,
1981
+ reason: "Wrong amount",
1982
+ details: `Transfer amount ${actualValue.toString()} does not match expected proof amount ${expectedAmount.toString()}.`,
1983
+ subjectDid,
1984
+ connectedWalletDid,
1985
+ controllingWalletDid
1986
+ };
1987
+ }
1988
+ await params.provider.getBlockNumber();
1989
+ await params.provider.getBlock(receipt.blockNumber);
1990
+ return {
1991
+ valid: true,
1992
+ method: "transfer",
1993
+ details: `Verified via transfer proof ${params.txHash}.`,
1994
+ subjectDid,
1995
+ connectedWalletDid,
1996
+ controllingWalletDid
1997
+ };
1998
+ }
1999
+ for (const pattern of OWNERSHIP_PATTERNS) {
2000
+ const ownerAddress = await readAddressFromContract(
2001
+ params.provider,
2002
+ subjectAddress,
2003
+ pattern.signature,
2004
+ pattern.method
2005
+ );
2006
+ if (ownerAddress && ethers.getAddress(ownerAddress) === ethers.getAddress(connectedWalletAddress)) {
2007
+ return {
2008
+ valid: true,
2009
+ method: "contract",
2010
+ details: `Verified via ${pattern.method}() ownership check.`,
2011
+ subjectDid,
2012
+ connectedWalletDid,
2013
+ controllingWalletDid: controllingWalletDid ?? void 0
2014
+ };
2015
+ }
2016
+ }
2017
+ try {
2018
+ const adminValue = await params.provider.getStorage(subjectAddress, EIP1967_ADMIN_SLOT);
2019
+ if (adminValue && adminValue !== "0x" && adminValue !== "0x0000000000000000000000000000000000000000000000000000000000000000") {
2020
+ const adminAddress = ethers.getAddress(`0x${adminValue.slice(-40)}`);
2021
+ if (adminAddress === ethers.getAddress(connectedWalletAddress)) {
2022
+ return {
2023
+ valid: true,
2024
+ method: "contract",
2025
+ details: "Verified via EIP-1967 admin slot.",
2026
+ subjectDid,
2027
+ connectedWalletDid,
2028
+ controllingWalletDid: controllingWalletDid ?? buildEvmDidPkh(chainId, adminAddress)
2029
+ };
2030
+ }
2031
+ }
2032
+ } catch {
2033
+ }
2034
+ if (ethers.getAddress(subjectAddress) === ethers.getAddress(connectedWalletAddress) && controllingWalletDid) {
2035
+ return {
2036
+ valid: true,
2037
+ method: "minting-wallet",
2038
+ details: `Verified because connected wallet matches the contract DID address. Controlling wallet is ${controllingWalletDid}.`,
2039
+ subjectDid,
2040
+ connectedWalletDid,
2041
+ controllingWalletDid
2042
+ };
2043
+ }
2044
+ return {
2045
+ valid: false,
2046
+ reason: "Contract ownership verification failed",
2047
+ details: controllingWalletDid ? `Connected wallet ${connectedWalletDid} does not match the controlling wallet ${controllingWalletDid} or the subject contract address ${subjectDid}.` : `Could not match connected wallet ${connectedWalletDid} to contract ownership for ${subjectDid}.`,
2048
+ subjectDid,
2049
+ connectedWalletDid,
2050
+ controllingWalletDid: controllingWalletDid ?? void 0
2051
+ };
2052
+ }
2053
+ async function verifySubjectOwnership(params) {
2054
+ const subjectDid = normalizeSubjectDid(params.subjectDid);
2055
+ const method = extractDidMethod(subjectDid);
2056
+ if (method === "web") {
2057
+ return verifyDidWebOwnership(params);
2058
+ }
2059
+ if (method === "pkh") {
2060
+ const didPkhParams = params;
2061
+ if (!didPkhParams.provider) {
2062
+ throw new OmaTrustError(
2063
+ "INVALID_INPUT",
2064
+ "provider is required for did:pkh ownership verification",
2065
+ { subjectDid }
2066
+ );
2067
+ }
2068
+ return verifyDidPkhOwnership(didPkhParams);
2069
+ }
2070
+ throw new OmaTrustError("INVALID_INPUT", "Unsupported DID type for ownership verification", {
2071
+ subjectDid
2072
+ });
2073
+ }
2074
+
2075
+ exports.buildDelegatedAttestationTypedData = buildDelegatedAttestationTypedData;
2076
+ exports.buildDelegatedTypedDataFromEncoded = buildDelegatedTypedDataFromEncoded;
2077
+ exports.buildDnsTxtRecord = buildDnsTxtRecord;
2078
+ exports.buildEip712Domain = buildEip712Domain;
2079
+ exports.calculateAverageUserReviewRating = calculateAverageUserReviewRating;
2080
+ exports.calculateTransferAmount = calculateTransferAmount;
2081
+ exports.calculateTransferAmountFromAddresses = calculateTransferAmountFromAddresses;
2082
+ exports.callControllerWitness = callControllerWitness;
2083
+ exports.constructSeed = constructSeed;
2084
+ exports.createEvidencePointerProof = createEvidencePointerProof;
2085
+ exports.createPopEip712Proof = createPopEip712Proof;
2086
+ exports.createPopJwsProof = createPopJwsProof;
2087
+ exports.createTxEncodedValueProof = createTxEncodedValueProof;
2088
+ exports.createTxInteractionProof = createTxInteractionProof;
2089
+ exports.createX402OfferProof = createX402OfferProof;
2090
+ exports.createX402ReceiptProof = createX402ReceiptProof;
2091
+ exports.decodeAttestationData = decodeAttestationData;
2092
+ exports.deduplicateReviews = deduplicateReviews;
2093
+ exports.encodeAttestationData = encodeAttestationData;
2094
+ exports.extractAddressesFromDidDocument = extractAddressesFromDidDocument;
2095
+ exports.extractExpirationTime = extractExpirationTime;
2096
+ exports.fetchDidDocument = fetchDidDocument;
2097
+ exports.formatSchemaUid = formatSchemaUid;
2098
+ exports.formatTransferAmount = formatTransferAmount;
2099
+ exports.getAttestation = getAttestation;
2100
+ exports.getAttestationsByAttester = getAttestationsByAttester;
2101
+ exports.getAttestationsForDid = getAttestationsForDid;
2102
+ exports.getChainConstants = getChainConstants;
2103
+ exports.getExplorerAddressUrl = getExplorerAddressUrl;
2104
+ exports.getExplorerTxUrl = getExplorerTxUrl;
2105
+ exports.getLatestAttestations = getLatestAttestations;
2106
+ exports.getMajorVersion = getMajorVersion;
2107
+ exports.getOmaTrustProofEip712Types = getOmaTrustProofEip712Types;
2108
+ exports.getSchemaDetails = getSchemaDetails;
2109
+ exports.getSupportedChainIds = getSupportedChainIds;
2110
+ exports.hashSeed = hashSeed;
2111
+ exports.isChainSupported = isChainSupported;
2112
+ exports.listAttestations = listAttestations;
2113
+ exports.normalizeSchema = normalizeSchema;
2114
+ exports.parseDnsTxtRecord = parseDnsTxtRecord;
2115
+ exports.prepareDelegatedAttestation = prepareDelegatedAttestation;
2116
+ exports.revokeAttestation = revokeAttestation;
2117
+ exports.schemaToString = schemaToString;
2118
+ exports.splitSignature = splitSignature;
2119
+ exports.submitAttestation = submitAttestation;
2120
+ exports.submitDelegatedAttestation = submitDelegatedAttestation;
2121
+ exports.validateAttestationData = validateAttestationData;
2122
+ exports.verifyAttestation = verifyAttestation;
2123
+ exports.verifyDidDocumentControllerDid = verifyDidDocumentControllerDid;
2124
+ exports.verifyDidJsonControllerDid = verifyDidJsonControllerDid;
2125
+ exports.verifyDidPkhOwnership = verifyDidPkhOwnership;
2126
+ exports.verifyDidWebOwnership = verifyDidWebOwnership;
2127
+ exports.verifyDnsTxtControllerDid = verifyDnsTxtControllerDid2;
2128
+ exports.verifyEip712Signature = verifyEip712Signature;
2129
+ exports.verifyProof = verifyProof;
2130
+ exports.verifySchemaExists = verifySchemaExists;
2131
+ exports.verifySubjectOwnership = verifySubjectOwnership;
2132
+ //# sourceMappingURL=index.browser.cjs.map
2133
+ //# sourceMappingURL=index.browser.cjs.map