@chaoschain/sdk 0.2.2 → 0.2.4

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.
@@ -1,13 +1,41 @@
1
- import { ethers } from 'ethers';
2
- import * as fs3 from 'fs';
3
- import fs3__default from 'fs';
4
- import * as path3 from 'path';
5
- import path3__default from 'path';
6
- import * as crypto2 from 'crypto';
7
- import { createHash } from 'crypto';
8
- import axios2 from 'axios';
9
- import * as http from 'http';
10
- import * as jose from 'jose';
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var ethers = require('ethers');
6
+ var fs3 = require('fs');
7
+ var path3 = require('path');
8
+ var crypto2 = require('crypto');
9
+ var axios2 = require('axios');
10
+ var http = require('http');
11
+ var jose = require('jose');
12
+
13
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
14
+
15
+ function _interopNamespace(e) {
16
+ if (e && e.__esModule) return e;
17
+ var n = Object.create(null);
18
+ if (e) {
19
+ Object.keys(e).forEach(function (k) {
20
+ if (k !== 'default') {
21
+ var d = Object.getOwnPropertyDescriptor(e, k);
22
+ Object.defineProperty(n, k, d.get ? d : {
23
+ enumerable: true,
24
+ get: function () { return e[k]; }
25
+ });
26
+ }
27
+ });
28
+ }
29
+ n.default = e;
30
+ return Object.freeze(n);
31
+ }
32
+
33
+ var fs3__namespace = /*#__PURE__*/_interopNamespace(fs3);
34
+ var path3__namespace = /*#__PURE__*/_interopNamespace(path3);
35
+ var crypto2__namespace = /*#__PURE__*/_interopNamespace(crypto2);
36
+ var axios2__default = /*#__PURE__*/_interopDefault(axios2);
37
+ var http__namespace = /*#__PURE__*/_interopNamespace(http);
38
+ var jose__namespace = /*#__PURE__*/_interopNamespace(jose);
11
39
 
12
40
  var __create = Object.create;
13
41
  var __defProp = Object.defineProperty;
@@ -37,7 +65,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
37
65
  // file that has been converted to a CommonJS file using a Babel-
38
66
  // compatible transform (i.e. "__esModule" has not been set), then set
39
67
  // "default" to the CommonJS "module.exports" for node compatibility.
40
- !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
68
+ __defProp(target, "default", { value: mod, enumerable: true }) ,
41
69
  mod
42
70
  ));
43
71
 
@@ -10285,27 +10313,27 @@ var WalletManager = class _WalletManager {
10285
10313
  */
10286
10314
  initializeWallet(config) {
10287
10315
  if (config.privateKey) {
10288
- return new ethers.Wallet(config.privateKey);
10316
+ return new ethers.ethers.Wallet(config.privateKey);
10289
10317
  }
10290
10318
  if (config.mnemonic) {
10291
- return ethers.Wallet.fromPhrase(config.mnemonic);
10319
+ return ethers.ethers.Wallet.fromPhrase(config.mnemonic);
10292
10320
  }
10293
10321
  if (config.walletFile) {
10294
10322
  return this.loadFromFile(config.walletFile);
10295
10323
  }
10296
- return ethers.Wallet.createRandom();
10324
+ return ethers.ethers.Wallet.createRandom();
10297
10325
  }
10298
10326
  /**
10299
10327
  * Load wallet from encrypted file
10300
10328
  */
10301
10329
  loadFromFile(filePath) {
10302
10330
  try {
10303
- const walletData = fs3.readFileSync(filePath, "utf8");
10331
+ const walletData = fs3__namespace.readFileSync(filePath, "utf8");
10304
10332
  const data = JSON.parse(walletData);
10305
10333
  if (data.encrypted) {
10306
10334
  throw new Error("Encrypted wallets require password (not yet implemented)");
10307
10335
  }
10308
- return new ethers.Wallet(data.privateKey);
10336
+ return new ethers.ethers.Wallet(data.privateKey);
10309
10337
  } catch (error) {
10310
10338
  throw new Error(`Failed to load wallet from file: ${error.message}`);
10311
10339
  }
@@ -10314,13 +10342,13 @@ var WalletManager = class _WalletManager {
10314
10342
  * Save wallet to encrypted file
10315
10343
  */
10316
10344
  async saveToFile(filePath, password) {
10317
- const directory = path3.dirname(filePath);
10318
- if (!fs3.existsSync(directory)) {
10319
- fs3.mkdirSync(directory, { recursive: true });
10345
+ const directory = path3__namespace.dirname(filePath);
10346
+ if (!fs3__namespace.existsSync(directory)) {
10347
+ fs3__namespace.mkdirSync(directory, { recursive: true });
10320
10348
  }
10321
10349
  if (password) {
10322
10350
  const encrypted = await this.wallet.encrypt(password);
10323
- fs3.writeFileSync(filePath, encrypted, "utf8");
10351
+ fs3__namespace.writeFileSync(filePath, encrypted, "utf8");
10324
10352
  } else {
10325
10353
  const data = {
10326
10354
  address: this.wallet.address,
@@ -10328,7 +10356,7 @@ var WalletManager = class _WalletManager {
10328
10356
  mnemonic: "mnemonic" in this.wallet ? this.wallet.mnemonic?.phrase : void 0,
10329
10357
  encrypted: false
10330
10358
  };
10331
- fs3.writeFileSync(filePath, JSON.stringify(data, null, 2), "utf8");
10359
+ fs3__namespace.writeFileSync(filePath, JSON.stringify(data, null, 2), "utf8");
10332
10360
  }
10333
10361
  }
10334
10362
  /**
@@ -10396,7 +10424,7 @@ var WalletManager = class _WalletManager {
10396
10424
  * Generate a new random wallet
10397
10425
  */
10398
10426
  static createRandom() {
10399
- const wallet = ethers.Wallet.createRandom();
10427
+ const wallet = ethers.ethers.Wallet.createRandom();
10400
10428
  return new _WalletManager({ privateKey: wallet.privateKey });
10401
10429
  }
10402
10430
  /**
@@ -10415,14 +10443,14 @@ var WalletManager = class _WalletManager {
10415
10443
  * Generate new mnemonic
10416
10444
  */
10417
10445
  static generateMnemonic() {
10418
- return ethers.Wallet.createRandom().mnemonic?.phrase || "";
10446
+ return ethers.ethers.Wallet.createRandom().mnemonic?.phrase || "";
10419
10447
  }
10420
10448
  /**
10421
10449
  * Validate mnemonic
10422
10450
  */
10423
10451
  static isValidMnemonic(mnemonic) {
10424
10452
  try {
10425
- ethers.Wallet.fromPhrase(mnemonic);
10453
+ ethers.ethers.Wallet.fromPhrase(mnemonic);
10426
10454
  return true;
10427
10455
  } catch {
10428
10456
  return false;
@@ -10433,7 +10461,7 @@ var WalletManager = class _WalletManager {
10433
10461
  */
10434
10462
  static isValidPrivateKey(privateKey) {
10435
10463
  try {
10436
- new ethers.Wallet(privateKey);
10464
+ new ethers.ethers.Wallet(privateKey);
10437
10465
  return true;
10438
10466
  } catch {
10439
10467
  return false;
@@ -10443,7 +10471,7 @@ var WalletManager = class _WalletManager {
10443
10471
  * Derive child wallet from HD path
10444
10472
  */
10445
10473
  static deriveChild(mnemonic, path4) {
10446
- const hdNode = ethers.HDNodeWallet.fromPhrase(mnemonic, void 0, path4);
10474
+ const hdNode = ethers.ethers.HDNodeWallet.fromPhrase(mnemonic, void 0, path4);
10447
10475
  return new _WalletManager({ privateKey: hdNode.privateKey });
10448
10476
  }
10449
10477
  };
@@ -11313,13 +11341,13 @@ var ChaosAgent = class {
11313
11341
  _agentId = null;
11314
11342
  constructor(addresses, signer, _provider) {
11315
11343
  this.signer = signer;
11316
- this.identityContract = new ethers.Contract(addresses.identity, IDENTITY_REGISTRY_ABI, signer);
11317
- this.reputationContract = new ethers.Contract(
11344
+ this.identityContract = new ethers.ethers.Contract(addresses.identity, IDENTITY_REGISTRY_ABI, signer);
11345
+ this.reputationContract = new ethers.ethers.Contract(
11318
11346
  addresses.reputation,
11319
11347
  REPUTATION_REGISTRY_ABI,
11320
11348
  signer
11321
11349
  );
11322
- this.validationContract = new ethers.Contract(
11350
+ this.validationContract = new ethers.ethers.Contract(
11323
11351
  addresses.validation,
11324
11352
  VALIDATION_REGISTRY_ABI,
11325
11353
  signer
@@ -11521,23 +11549,23 @@ var ChaosAgent = class {
11521
11549
  const chainId = network.chainId;
11522
11550
  const identityAddress = await this.identityContract.getAddress();
11523
11551
  const signerAddress = await this.signer.getAddress();
11524
- const feedbackAuthData = ethers.solidityPackedKeccak256(
11552
+ const feedbackAuthData = ethers.ethers.solidityPackedKeccak256(
11525
11553
  ["uint256", "address", "uint64", "uint256", "uint256", "address", "address"],
11526
11554
  [agentId, clientAddress, indexLimit, expiry, chainId, identityAddress, signerAddress]
11527
11555
  );
11528
- const signature = await this.signer.signMessage(ethers.getBytes(feedbackAuthData));
11529
- const signatureBytes = ethers.getBytes(signature);
11530
- const structBytes = ethers.concat([
11531
- ethers.toBeHex(agentId, 32),
11532
- ethers.zeroPadValue(clientAddress, 32),
11533
- ethers.concat([ethers.toBeHex(indexLimit, 8), ethers.zeroPadValue("0x", 24)]),
11556
+ const signature = await this.signer.signMessage(ethers.ethers.getBytes(feedbackAuthData));
11557
+ const signatureBytes = ethers.ethers.getBytes(signature);
11558
+ const structBytes = ethers.ethers.concat([
11559
+ ethers.ethers.toBeHex(agentId, 32),
11560
+ ethers.ethers.zeroPadValue(clientAddress, 32),
11561
+ ethers.ethers.concat([ethers.ethers.toBeHex(indexLimit, 8), ethers.ethers.zeroPadValue("0x", 24)]),
11534
11562
  // uint64 padded
11535
- ethers.toBeHex(expiry, 32),
11536
- ethers.toBeHex(chainId, 32),
11537
- ethers.zeroPadValue(identityAddress, 32),
11538
- ethers.zeroPadValue(signerAddress, 32)
11563
+ ethers.ethers.toBeHex(expiry, 32),
11564
+ ethers.ethers.toBeHex(chainId, 32),
11565
+ ethers.ethers.zeroPadValue(identityAddress, 32),
11566
+ ethers.ethers.zeroPadValue(signerAddress, 32)
11539
11567
  ]);
11540
- const feedbackAuth = ethers.hexlify(ethers.concat([structBytes, signatureBytes]));
11568
+ const feedbackAuth = ethers.ethers.hexlify(ethers.ethers.concat([structBytes, signatureBytes]));
11541
11569
  console.log(`\u2705 Generated feedback authorization for agent #${agentId}`);
11542
11570
  return feedbackAuth;
11543
11571
  } catch (e) {
@@ -11562,7 +11590,7 @@ var ChaosAgent = class {
11562
11590
  const rawValue = typeof feedbackData?.value === "bigint" || typeof feedbackData?.value === "number" ? feedbackData.value : rating;
11563
11591
  const value = typeof rawValue === "bigint" ? rawValue : BigInt(Math.round(rawValue * Math.pow(10, valueDecimals)));
11564
11592
  const feedbackContent = typeof feedbackData?.content === "string" ? feedbackData.content : feedbackUri;
11565
- const feedbackHash = typeof feedbackData?.feedbackHash === "string" ? feedbackData.feedbackHash.startsWith("0x") ? feedbackData.feedbackHash : ethers.id(feedbackData.feedbackHash) : ethers.keccak256(ethers.toUtf8Bytes(feedbackContent));
11593
+ const feedbackHash = typeof feedbackData?.feedbackHash === "string" ? feedbackData.feedbackHash.startsWith("0x") ? feedbackData.feedbackHash : ethers.ethers.id(feedbackData.feedbackHash) : ethers.ethers.keccak256(ethers.ethers.toUtf8Bytes(feedbackContent));
11566
11594
  const tx = await this.reputationContract.giveFeedback(
11567
11595
  agentId,
11568
11596
  value,
@@ -11704,7 +11732,7 @@ var ChaosAgent = class {
11704
11732
  * @param requestHash Hash of the request content (bytes32)
11705
11733
  */
11706
11734
  async requestValidation(validatorAddress, agentId, requestUri, requestHash) {
11707
- const hashBytes = requestHash.startsWith("0x") ? requestHash : ethers.id(requestHash);
11735
+ const hashBytes = requestHash.startsWith("0x") ? requestHash : ethers.ethers.id(requestHash);
11708
11736
  const tx = await this.validationContract.validationRequest(
11709
11737
  validatorAddress,
11710
11738
  agentId,
@@ -11722,13 +11750,13 @@ var ChaosAgent = class {
11722
11750
  * @param responseHash Hash of the response content (bytes32)
11723
11751
  * @param tag Optional tag for categorization (bytes32)
11724
11752
  */
11725
- async respondToValidation(requestHash, response, responseUri, responseHash, tag = ethers.ZeroHash) {
11753
+ async respondToValidation(requestHash, response, responseUri, responseHash, tag = ethers.ethers.ZeroHash) {
11726
11754
  if (response < 0 || response > 100) {
11727
11755
  throw new Error("Response must be between 0 and 100");
11728
11756
  }
11729
- const reqHashBytes = requestHash.startsWith("0x") ? requestHash : ethers.id(requestHash);
11730
- const resHashBytes = responseHash.startsWith("0x") ? responseHash : ethers.id(responseHash);
11731
- const tagBytes = tag.startsWith("0x") ? tag : ethers.ZeroHash;
11757
+ const reqHashBytes = requestHash.startsWith("0x") ? requestHash : ethers.ethers.id(requestHash);
11758
+ const resHashBytes = responseHash.startsWith("0x") ? responseHash : ethers.ethers.id(responseHash);
11759
+ const tagBytes = tag.startsWith("0x") ? tag : ethers.ethers.ZeroHash;
11732
11760
  const tx = await this.validationContract.validationResponse(
11733
11761
  reqHashBytes,
11734
11762
  response,
@@ -11744,7 +11772,7 @@ var ChaosAgent = class {
11744
11772
  * @param requestHash Hash of the validation request (bytes32)
11745
11773
  */
11746
11774
  async getValidationStatus(requestHash) {
11747
- const hashBytes = requestHash.startsWith("0x") ? requestHash : ethers.id(requestHash);
11775
+ const hashBytes = requestHash.startsWith("0x") ? requestHash : ethers.ethers.id(requestHash);
11748
11776
  const result = await this.validationContract.getValidationStatus(hashBytes);
11749
11777
  return {
11750
11778
  validatorAddress: result.validatorAddress,
@@ -11761,8 +11789,8 @@ var ChaosAgent = class {
11761
11789
  * @param validatorAddresses Array of validator addresses (empty for all)
11762
11790
  * @param tag Tag filter (ZeroHash for no filter)
11763
11791
  */
11764
- async getValidationSummary(agentId, validatorAddresses = [], tag = ethers.ZeroHash) {
11765
- const tagBytes = tag.startsWith("0x") ? tag : ethers.ZeroHash;
11792
+ async getValidationSummary(agentId, validatorAddresses = [], tag = ethers.ethers.ZeroHash) {
11793
+ const tagBytes = tag.startsWith("0x") ? tag : ethers.ethers.ZeroHash;
11766
11794
  const result = await this.validationContract.getSummary(agentId, validatorAddresses, tagBytes);
11767
11795
  return {
11768
11796
  count: result.count,
@@ -11793,25 +11821,25 @@ var ChaosAgent = class {
11793
11821
  // Cache Implementation
11794
11822
  // ============================================================================
11795
11823
  getCachedFilePath() {
11796
- return path3__default.join(process.cwd(), "chaoschain_agent_ids.json");
11824
+ return path3__namespace.default.join(process.cwd(), "chaoschain_agent_ids.json");
11797
11825
  }
11798
11826
  loadAgentIdFromCache(chainId, wallet) {
11799
11827
  const cacheFile = this.getCachedFilePath();
11800
- if (!fs3__default.existsSync(cacheFile)) return null;
11801
- const cacheData = fs3__default.readFileSync(cacheFile, "utf-8");
11828
+ if (!fs3__namespace.default.existsSync(cacheFile)) return null;
11829
+ const cacheData = fs3__namespace.default.readFileSync(cacheFile, "utf-8");
11802
11830
  const cache = JSON.parse(cacheData);
11803
11831
  return cache[chainId]?.[wallet]?.agentId || null;
11804
11832
  }
11805
11833
  saveAgentIdTocache(chainId, wallet, agentId, domain) {
11806
11834
  const cacheFile = this.getCachedFilePath();
11807
- const cache = fs3__default.existsSync(cacheFile) ? JSON.parse(fs3__default.readFileSync(cacheFile, "utf-8")) : {};
11835
+ const cache = fs3__namespace.default.existsSync(cacheFile) ? JSON.parse(fs3__namespace.default.readFileSync(cacheFile, "utf-8")) : {};
11808
11836
  cache[String(chainId)] = cache[String(chainId)] ?? {};
11809
11837
  cache[String(chainId)][wallet.toLowerCase()] = {
11810
11838
  agentId,
11811
11839
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
11812
11840
  domain
11813
11841
  };
11814
- fs3__default.writeFileSync(cacheFile, JSON.stringify(cache, null, 2));
11842
+ fs3__namespace.default.writeFileSync(cacheFile, JSON.stringify(cache, null, 2));
11815
11843
  }
11816
11844
  // ============================================================================
11817
11845
  // Event Listening
@@ -12009,10 +12037,10 @@ var X402PaymentManager = class {
12009
12037
  */
12010
12038
  getTreasuryAddress(network) {
12011
12039
  const treasuries = {
12012
- "base-sepolia": "0x8004AA63c570c570eBF15376c0dB199918BFe9Fb",
12013
- "ethereum-sepolia": "0x8004a6090Cd10A7288092483047B097295Fb8847",
12014
- "optimism-sepolia": "0x8004a6090Cd10A7288092483047B097295Fb8847",
12015
- "linea-sepolia": "0x8004aa7C931bCE1233973a0C6A667f73F66282e7"
12040
+ "base-sepolia": "0x20E7B2A2c8969725b88Dd3EF3a11Bc3353C83F70",
12041
+ "ethereum-sepolia": "0x20E7B2A2c8969725b88Dd3EF3a11Bc3353C83F70",
12042
+ "optimism-sepolia": "0x20E7B2A2c8969725b88Dd3EF3a11Bc3353C83F70",
12043
+ "linea-sepolia": "0x20E7B2A2c8969725b88Dd3EF3a11Bc3353C83F70"
12016
12044
  };
12017
12045
  return treasuries[network] || treasuries["base-sepolia"];
12018
12046
  }
@@ -12040,7 +12068,7 @@ var X402PaymentManager = class {
12040
12068
  * Returns 32-byte hex string (0x-prefixed)
12041
12069
  */
12042
12070
  generateNonce() {
12043
- return ethers.hexlify(ethers.randomBytes(32));
12071
+ return ethers.ethers.hexlify(ethers.ethers.randomBytes(32));
12044
12072
  }
12045
12073
  /**
12046
12074
  * Sign EIP-3009 Transfer Authorization
@@ -12253,8 +12281,8 @@ var X402PaymentManager = class {
12253
12281
  * Execute native token (ETH) payment
12254
12282
  */
12255
12283
  async executeNativePayment(recipientAddress, amount, protocolFee) {
12256
- const amountWei = ethers.parseEther(amount.toString());
12257
- const feeWei = ethers.parseEther(protocolFee.toString());
12284
+ const amountWei = ethers.ethers.parseEther(amount.toString());
12285
+ const feeWei = ethers.ethers.parseEther(protocolFee.toString());
12258
12286
  const mainTx = await this.wallet.sendTransaction({
12259
12287
  to: recipientAddress,
12260
12288
  value: amountWei
@@ -12293,8 +12321,8 @@ var X402PaymentManager = class {
12293
12321
  if (!usdcAddress) {
12294
12322
  throw new PaymentError(`USDC not supported on ${this.network}`);
12295
12323
  }
12296
- const totalAmountWei = ethers.parseUnits(amount.toString(), 6);
12297
- const feeWei = ethers.parseUnits(protocolFee.toString(), 6);
12324
+ const totalAmountWei = ethers.ethers.parseUnits(amount.toString(), 6);
12325
+ const feeWei = ethers.ethers.parseUnits(protocolFee.toString(), 6);
12298
12326
  console.log(`\u{1F4B3} Preparing EIP-3009 payment authorization...`);
12299
12327
  console.log(` Total: ${amount} USDC`);
12300
12328
  console.log(` Fee: ${protocolFee} USDC`);
@@ -12389,7 +12417,7 @@ var X402PaymentManager = class {
12389
12417
  scheme: "exact",
12390
12418
  // x402 scheme for exact payment amount
12391
12419
  network: this.network,
12392
- maxAmountRequired: ethers.parseUnits(amount.toString(), currency === "USDC" ? 6 : 18).toString(),
12420
+ maxAmountRequired: ethers.ethers.parseUnits(amount.toString(), currency === "USDC" ? 6 : 18).toString(),
12393
12421
  resource,
12394
12422
  description: serviceDescription,
12395
12423
  mimeType: "application/json",
@@ -12437,7 +12465,7 @@ var X402PaymentManager = class {
12437
12465
  status: paymentProof.status
12438
12466
  };
12439
12467
  const receiptJson = JSON.stringify(receiptData);
12440
- const receiptHash = crypto2.createHash("sha256").update(receiptJson).digest("hex");
12468
+ const receiptHash = crypto2__namespace.createHash("sha256").update(receiptJson).digest("hex");
12441
12469
  return {
12442
12470
  receipt_type: "x402_payment",
12443
12471
  receipt_hash: receiptHash,
@@ -12481,7 +12509,7 @@ var PaymentManager = class {
12481
12509
  this.wallet = wallet;
12482
12510
  this.credentials = credentials;
12483
12511
  if (credentials.stripe_secret_key) {
12484
- this.stripeAxiosInstance = axios2.create({
12512
+ this.stripeAxiosInstance = axios2__default.default.create({
12485
12513
  baseURL: "https://api.stripe.com/v1",
12486
12514
  headers: {
12487
12515
  Authorization: `Bearer ${credentials.stripe_secret_key}`,
@@ -12503,7 +12531,7 @@ var PaymentManager = class {
12503
12531
  const auth = Buffer.from(
12504
12532
  `${this.credentials.paypal_client_id}:${this.credentials.paypal_client_secret}`
12505
12533
  ).toString("base64");
12506
- const response = await axios2.post(
12534
+ const response = await axios2__default.default.post(
12507
12535
  "https://api-m.sandbox.paypal.com/v1/oauth2/token",
12508
12536
  "grant_type=client_credentials",
12509
12537
  {
@@ -12770,7 +12798,7 @@ var X402Server = class {
12770
12798
  console.warn("\u26A0\uFE0F Server already running");
12771
12799
  return;
12772
12800
  }
12773
- this.server = http.createServer((req, res) => {
12801
+ this.server = http__namespace.createServer((req, res) => {
12774
12802
  this.handleRequest(req, res).catch((error) => {
12775
12803
  console.error("\u274C Request handler error:", error);
12776
12804
  res.writeHead(500, { "Content-Type": "application/json" });
@@ -12973,17 +13001,17 @@ var GoogleAP2Integration = class {
12973
13001
  * Generate or load RSA keypair for production JWT signing
12974
13002
  */
12975
13003
  getOrGenerateRsaKeypair() {
12976
- const keyDir = path3.join(process.cwd(), "keys");
12977
- const privateKeyPath = path3.join(keyDir, `${this.agentName}_ap2_private.pem`);
12978
- const publicKeyPath = path3.join(keyDir, `${this.agentName}_ap2_public.pem`);
12979
- if (!fs3.existsSync(keyDir)) {
12980
- fs3.mkdirSync(keyDir, { recursive: true });
13004
+ const keyDir = path3__namespace.join(process.cwd(), "keys");
13005
+ const privateKeyPath = path3__namespace.join(keyDir, `${this.agentName}_ap2_private.pem`);
13006
+ const publicKeyPath = path3__namespace.join(keyDir, `${this.agentName}_ap2_public.pem`);
13007
+ if (!fs3__namespace.existsSync(keyDir)) {
13008
+ fs3__namespace.mkdirSync(keyDir, { recursive: true });
12981
13009
  }
12982
- if (fs3.existsSync(privateKeyPath) && fs3.existsSync(publicKeyPath)) {
13010
+ if (fs3__namespace.existsSync(privateKeyPath) && fs3__namespace.existsSync(publicKeyPath)) {
12983
13011
  try {
12984
- const privateKeyPem = fs3.readFileSync(privateKeyPath, "utf-8");
12985
- const publicKeyPem = fs3.readFileSync(publicKeyPath, "utf-8");
12986
- const privateKey2 = crypto2.createPrivateKey(privateKeyPem);
13012
+ const privateKeyPem = fs3__namespace.readFileSync(privateKeyPath, "utf-8");
13013
+ const publicKeyPem = fs3__namespace.readFileSync(publicKeyPath, "utf-8");
13014
+ const privateKey2 = crypto2__namespace.createPrivateKey(privateKeyPem);
12987
13015
  console.log(`\u{1F511} Loaded existing RSA keypair for ${this.agentName}`);
12988
13016
  return { privateKey: privateKey2, publicKey: publicKeyPem };
12989
13017
  } catch (e) {
@@ -12991,7 +13019,7 @@ var GoogleAP2Integration = class {
12991
13019
  }
12992
13020
  }
12993
13021
  console.log(`\u{1F511} Generating new RSA keypair for ${this.agentName}`);
12994
- const { privateKey, publicKey } = crypto2.generateKeyPairSync("rsa", {
13022
+ const { privateKey, publicKey } = crypto2__namespace.generateKeyPairSync("rsa", {
12995
13023
  modulusLength: 2048,
12996
13024
  publicKeyEncoding: {
12997
13025
  type: "spki",
@@ -13003,14 +13031,14 @@ var GoogleAP2Integration = class {
13003
13031
  }
13004
13032
  });
13005
13033
  try {
13006
- fs3.writeFileSync(privateKeyPath, privateKey);
13007
- fs3.writeFileSync(publicKeyPath, publicKey);
13034
+ fs3__namespace.writeFileSync(privateKeyPath, privateKey);
13035
+ fs3__namespace.writeFileSync(publicKeyPath, publicKey);
13008
13036
  console.log(`\u{1F4BE} RSA keypair saved to ${keyDir}`);
13009
13037
  } catch (e) {
13010
13038
  console.warn(`\u26A0\uFE0F Failed to save keys: ${e}`);
13011
13039
  }
13012
13040
  return {
13013
- privateKey: crypto2.createPrivateKey(privateKey),
13041
+ privateKey: crypto2__namespace.createPrivateKey(privateKey),
13014
13042
  publicKey
13015
13043
  };
13016
13044
  }
@@ -13119,7 +13147,7 @@ var GoogleAP2Integration = class {
13119
13147
  */
13120
13148
  async createMerchantJwt(cartContents) {
13121
13149
  const cartJson = JSON.stringify(cartContents);
13122
- const cartHash = crypto2.createHash("sha256").update(cartJson).digest("hex");
13150
+ const cartHash = crypto2__namespace.createHash("sha256").update(cartJson).digest("hex");
13123
13151
  const now = Math.floor(Date.now() / 1e3);
13124
13152
  const payload = {
13125
13153
  iss: `did:chaoschain:${this.agentName}`,
@@ -13138,7 +13166,7 @@ var GoogleAP2Integration = class {
13138
13166
  // Cart integrity hash
13139
13167
  merchant_name: cartContents.merchant_name
13140
13168
  };
13141
- const jwt = await new jose.SignJWT(payload).setProtectedHeader({
13169
+ const jwt = await new jose__namespace.SignJWT(payload).setProtectedHeader({
13142
13170
  alg: "RS256",
13143
13171
  kid: `did:chaoschain:${this.agentName}#key-1`
13144
13172
  }).sign(this.privateKey);
@@ -13149,8 +13177,8 @@ var GoogleAP2Integration = class {
13149
13177
  */
13150
13178
  async verifyJwtToken(token) {
13151
13179
  try {
13152
- const publicKey = crypto2.createPublicKey(this.publicKey);
13153
- const { payload } = await jose.jwtVerify(token, publicKey, {
13180
+ const publicKey = crypto2__namespace.createPublicKey(this.publicKey);
13181
+ const { payload } = await jose__namespace.jwtVerify(token, publicKey, {
13154
13182
  algorithms: ["RS256"],
13155
13183
  audience: "chaoschain:payment_processor"
13156
13184
  });
@@ -13404,7 +13432,7 @@ var A2AX402Extension = class {
13404
13432
  agent_payee: this.agentName
13405
13433
  };
13406
13434
  const proofJson = JSON.stringify(proofData);
13407
- const proofHash = crypto2.createHash("sha256").update(proofJson).digest("hex");
13435
+ const proofHash = crypto2__namespace.createHash("sha256").update(proofJson).digest("hex");
13408
13436
  return {
13409
13437
  proof_type: "a2a_x402_payment",
13410
13438
  proof_hash: proofHash,
@@ -13542,10 +13570,10 @@ var ProcessIntegrity = class {
13542
13570
  generateCodeHash(func) {
13543
13571
  try {
13544
13572
  const sourceCode = func.toString();
13545
- return createHash("sha256").update(sourceCode).digest("hex");
13573
+ return crypto2.createHash("sha256").update(sourceCode).digest("hex");
13546
13574
  } catch {
13547
13575
  const funcInfo = `${func.name}`;
13548
- return createHash("sha256").update(funcInfo).digest("hex");
13576
+ return crypto2.createHash("sha256").update(funcInfo).digest("hex");
13549
13577
  }
13550
13578
  }
13551
13579
  /**
@@ -13621,7 +13649,7 @@ var ProcessIntegrity = class {
13621
13649
  execution_time: executionTime.toISOString(),
13622
13650
  agent_name: this.agentName
13623
13651
  };
13624
- const executionHash = createHash("sha256").update(JSON.stringify(executionData)).digest("hex");
13652
+ const executionHash = crypto2.createHash("sha256").update(JSON.stringify(executionData)).digest("hex");
13625
13653
  const proof = {
13626
13654
  proofId,
13627
13655
  functionName,
@@ -13745,7 +13773,7 @@ var LocalIPFSStorage = class {
13745
13773
  const buffer = typeof data === "string" ? Buffer.from(data) : data;
13746
13774
  const form = new import_form_data.default();
13747
13775
  form.append("file", buffer, { contentType: mime });
13748
- const response = await axios2.post(`${this.apiUrl}/api/v0/add`, form, {
13776
+ const response = await axios2__default.default.post(`${this.apiUrl}/api/v0/add`, form, {
13749
13777
  headers: form.getHeaders(),
13750
13778
  maxBodyLength: Infinity
13751
13779
  });
@@ -13768,7 +13796,7 @@ var LocalIPFSStorage = class {
13768
13796
  }
13769
13797
  async get(cid) {
13770
13798
  try {
13771
- const response = await axios2.post(`${this.apiUrl}/api/v0/cat`, null, {
13799
+ const response = await axios2__default.default.post(`${this.apiUrl}/api/v0/cat`, null, {
13772
13800
  params: { arg: cid },
13773
13801
  responseType: "arraybuffer"
13774
13802
  });
@@ -13779,7 +13807,7 @@ var LocalIPFSStorage = class {
13779
13807
  }
13780
13808
  async pin(cid) {
13781
13809
  try {
13782
- await axios2.post(`${this.apiUrl}/api/v0/pin/add`, null, {
13810
+ await axios2__default.default.post(`${this.apiUrl}/api/v0/pin/add`, null, {
13783
13811
  params: { arg: cid }
13784
13812
  });
13785
13813
  console.log(`\u{1F4CC} Pinned to local IPFS: ${cid}`);
@@ -13789,7 +13817,7 @@ var LocalIPFSStorage = class {
13789
13817
  }
13790
13818
  async unpin(cid) {
13791
13819
  try {
13792
- await axios2.post(`${this.apiUrl}/api/v0/pin/rm`, null, {
13820
+ await axios2__default.default.post(`${this.apiUrl}/api/v0/pin/rm`, null, {
13793
13821
  params: { arg: cid }
13794
13822
  });
13795
13823
  console.log(`\u{1F4CC} Unpinned from local IPFS: ${cid}`);
@@ -13814,7 +13842,7 @@ var PinataStorage = class {
13814
13842
  contentType: mime,
13815
13843
  filename: `file_${Date.now()}`
13816
13844
  });
13817
- const response = await axios2.post("https://api.pinata.cloud/pinning/pinFileToIPFS", form, {
13845
+ const response = await axios2__default.default.post("https://api.pinata.cloud/pinning/pinFileToIPFS", form, {
13818
13846
  headers: {
13819
13847
  ...form.getHeaders(),
13820
13848
  Authorization: `Bearer ${this.jwtToken}`
@@ -13835,7 +13863,7 @@ var PinataStorage = class {
13835
13863
  }
13836
13864
  async get(cid) {
13837
13865
  try {
13838
- const response = await axios2.get(`${this.gatewayUrl}/ipfs/${cid}`, {
13866
+ const response = await axios2__default.default.get(`${this.gatewayUrl}/ipfs/${cid}`, {
13839
13867
  responseType: "arraybuffer"
13840
13868
  });
13841
13869
  return Buffer.from(response.data);
@@ -13845,7 +13873,7 @@ var PinataStorage = class {
13845
13873
  }
13846
13874
  async pin(cid) {
13847
13875
  try {
13848
- await axios2.post(
13876
+ await axios2__default.default.post(
13849
13877
  "https://api.pinata.cloud/pinning/pinByHash",
13850
13878
  { hashToPin: cid },
13851
13879
  {
@@ -13862,7 +13890,7 @@ var PinataStorage = class {
13862
13890
  }
13863
13891
  async unpin(cid) {
13864
13892
  try {
13865
- await axios2.delete(`https://api.pinata.cloud/pinning/unpin/${cid}`, {
13893
+ await axios2__default.default.delete(`https://api.pinata.cloud/pinning/unpin/${cid}`, {
13866
13894
  headers: {
13867
13895
  Authorization: `Bearer ${this.jwtToken}`
13868
13896
  }
@@ -13898,7 +13926,7 @@ var IrysStorage = class {
13898
13926
  }
13899
13927
  async get(cid) {
13900
13928
  try {
13901
- const response = await axios2.get(`https://arweave.net/${cid}`, {
13929
+ const response = await axios2__default.default.get(`https://arweave.net/${cid}`, {
13902
13930
  responseType: "arraybuffer"
13903
13931
  });
13904
13932
  return Buffer.from(response.data);
@@ -14555,7 +14583,21 @@ var GatewayClient = class {
14555
14583
  auth;
14556
14584
  retryConfig;
14557
14585
  constructor(config) {
14558
- this.gatewayUrl = config.gatewayUrl.replace(/\/$/, "");
14586
+ const rawBaseUrl = config.baseUrl ?? config.gatewayUrl ?? "https://gateway.chaoscha.in";
14587
+ let parsed;
14588
+ try {
14589
+ parsed = new URL(rawBaseUrl);
14590
+ } catch {
14591
+ throw new Error(
14592
+ `Invalid gateway baseUrl "${rawBaseUrl}". Provide a valid absolute URL, e.g. https://gateway.chaoscha.in`
14593
+ );
14594
+ }
14595
+ if (!["http:", "https:"].includes(parsed.protocol)) {
14596
+ throw new Error(
14597
+ `Invalid gateway baseUrl protocol "${parsed.protocol}". Only http/https are supported.`
14598
+ );
14599
+ }
14600
+ this.gatewayUrl = parsed.toString().replace(/\/$/, "");
14559
14601
  this.timeout = this._resolveTimeout(
14560
14602
  config.timeoutMs,
14561
14603
  config.timeoutSeconds,
@@ -14696,7 +14738,7 @@ var GatewayClient = class {
14696
14738
  let attempt = 0;
14697
14739
  while (true) {
14698
14740
  try {
14699
- const response = await axios2({
14741
+ const response = await axios2__default.default({
14700
14742
  method,
14701
14743
  url,
14702
14744
  data,
@@ -14980,6 +15022,68 @@ var GatewayClient = class {
14980
15022
  const workflow = await this.closeEpoch(studioAddress, epoch, signerAddress);
14981
15023
  return this.waitForCompletion(workflow.workflowId, options);
14982
15024
  }
15025
+ // ===========================================================================
15026
+ // Read API — Studio Work Discovery
15027
+ // ===========================================================================
15028
+ /**
15029
+ * Fetch pending (unfinalized) work for a studio from the gateway.
15030
+ *
15031
+ * @param studioAddress - 0x-prefixed studio contract address
15032
+ * @param options - Optional limit/offset for pagination
15033
+ * @returns Typed pending work response
15034
+ */
15035
+ async getPendingWork(studioAddress, options) {
15036
+ const limit = options?.limit ?? 20;
15037
+ const offset = options?.offset ?? 0;
15038
+ const url = `${this.gatewayUrl}/v1/studio/${studioAddress}/work?status=pending&limit=${limit}&offset=${offset}`;
15039
+ try {
15040
+ const response = await axios2__default.default.get(url, {
15041
+ timeout: this.timeout,
15042
+ headers: this._buildHeaders()
15043
+ });
15044
+ return response.data;
15045
+ } catch (error) {
15046
+ const axiosErr = error;
15047
+ if (axiosErr.code === "ECONNREFUSED" || axiosErr.code === "ENOTFOUND" || !axiosErr.response) {
15048
+ throw new GatewayConnectionError(
15049
+ `ChaosChain gateway unreachable at ${this.gatewayUrl}. Check GATEWAY_URL.`
15050
+ );
15051
+ }
15052
+ if (axiosErr.response) {
15053
+ throw new GatewayError(
15054
+ `Gateway returned ${axiosErr.response.status}: ${JSON.stringify(axiosErr.response.data)}`
15055
+ );
15056
+ }
15057
+ throw error;
15058
+ }
15059
+ }
15060
+ /**
15061
+ * Fetch full evidence graph for a work submission.
15062
+ * Endpoint: GET /v1/work/{hash}/evidence
15063
+ */
15064
+ async getWorkEvidence(workHash) {
15065
+ const url = `${this.gatewayUrl}/v1/work/${workHash}/evidence`;
15066
+ try {
15067
+ const response = await axios2__default.default.get(url, {
15068
+ timeout: this.timeout,
15069
+ headers: this._buildHeaders()
15070
+ });
15071
+ return response.data;
15072
+ } catch (error) {
15073
+ const axiosErr = error;
15074
+ if (axiosErr.code === "ECONNREFUSED" || axiosErr.code === "ENOTFOUND" || !axiosErr.response) {
15075
+ throw new GatewayConnectionError(
15076
+ `ChaosChain gateway unreachable at ${this.gatewayUrl}. Check GATEWAY_URL.`
15077
+ );
15078
+ }
15079
+ if (axiosErr.response) {
15080
+ throw new GatewayError(
15081
+ `Gateway returned ${axiosErr.response.status}: ${JSON.stringify(axiosErr.response.data)}`
15082
+ );
15083
+ }
15084
+ throw error;
15085
+ }
15086
+ }
14983
15087
  };
14984
15088
  var StudioClient = class {
14985
15089
  provider;
@@ -15006,7 +15110,7 @@ var StudioClient = class {
15006
15110
  if (!chaosCoreAddress) {
15007
15111
  throw new ContractError(`ChaosCore contract address not found for network: ${this.network}.`);
15008
15112
  }
15009
- const chaosCore = new ethers.Contract(chaosCoreAddress, CHAOS_CORE_ABI, this.signer);
15113
+ const chaosCore = new ethers.ethers.Contract(chaosCoreAddress, CHAOS_CORE_ABI, this.signer);
15010
15114
  const tx = await chaosCore.createStudio(name, logicModuleAddress);
15011
15115
  const receipt = await tx.wait();
15012
15116
  const event = receipt.logs.find((log) => {
@@ -15040,11 +15144,11 @@ var StudioClient = class {
15040
15144
  * @param stakeAmount - Amount to stake in wei (default: 0.0001 ETH)
15041
15145
  */
15042
15146
  async registerWithStudio(studioAddress, agentId, role, stakeAmount) {
15043
- const stake = stakeAmount ?? ethers.parseEther("0.0001");
15147
+ const stake = stakeAmount ?? ethers.ethers.parseEther("0.0001");
15044
15148
  if (stake === 0n) {
15045
15149
  throw new ContractError("Stake amount must be > 0 (contract requirement)");
15046
15150
  }
15047
- const studio = new ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.signer);
15151
+ const studio = new ethers.ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.signer);
15048
15152
  const tx = await studio.registerAgent(agentId, role, {
15049
15153
  value: stake
15050
15154
  });
@@ -15067,7 +15171,7 @@ var StudioClient = class {
15067
15171
  */
15068
15172
  async submitWork(studioAddress, dataHash, threadRoot, evidenceRoot, feedbackAuth = "0x") {
15069
15173
  console.warn("submitWork() is deprecated. Use Gateway for production.");
15070
- const studio = new ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.signer);
15174
+ const studio = new ethers.ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.signer);
15071
15175
  const tx = await studio.submitWork(dataHash, threadRoot, evidenceRoot, feedbackAuth);
15072
15176
  const receipt = await tx.wait();
15073
15177
  return receipt.hash;
@@ -15096,7 +15200,7 @@ var StudioClient = class {
15096
15200
  `Participants (${participants.length}) and weights (${contributionWeights.length}) must have same length`
15097
15201
  );
15098
15202
  }
15099
- const studio = new ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.signer);
15203
+ const studio = new ethers.ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.signer);
15100
15204
  const tx = await studio.submitWorkMultiAgent(
15101
15205
  dataHash,
15102
15206
  threadRoot,
@@ -15123,7 +15227,7 @@ var StudioClient = class {
15123
15227
  * @returns Transaction hash
15124
15228
  */
15125
15229
  async commitScore(studioAddress, dataHash, commitment) {
15126
- const studio = new ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.signer);
15230
+ const studio = new ethers.ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.signer);
15127
15231
  const tx = await studio.commitScore(dataHash, commitment);
15128
15232
  const receipt = await tx.wait();
15129
15233
  return receipt.hash;
@@ -15141,7 +15245,7 @@ var StudioClient = class {
15141
15245
  * @returns Transaction hash
15142
15246
  */
15143
15247
  async revealScore(studioAddress, dataHash, scoreVector, salt) {
15144
- const studio = new ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.signer);
15248
+ const studio = new ethers.ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.signer);
15145
15249
  const tx = await studio.revealScore(dataHash, scoreVector, salt);
15146
15250
  const receipt = await tx.wait();
15147
15251
  return receipt.hash;
@@ -15163,7 +15267,7 @@ var StudioClient = class {
15163
15267
  * @returns Transaction hash
15164
15268
  */
15165
15269
  async submitScoreVector(studioAddress, dataHash, scores) {
15166
- const studio = new ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.signer);
15270
+ const studio = new ethers.ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.signer);
15167
15271
  const scoreVector = this.encodeScoreVector(scores);
15168
15272
  const tx = await studio.submitScoreVector(dataHash, scoreVector);
15169
15273
  const receipt = await tx.wait();
@@ -15192,7 +15296,7 @@ var StudioClient = class {
15192
15296
  * @returns Transaction hash
15193
15297
  */
15194
15298
  async submitScoreVectorForWorker(studioAddress, dataHash, workerAddress, scores) {
15195
- const studio = new ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.signer);
15299
+ const studio = new ethers.ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.signer);
15196
15300
  const scoreVector = this.encodeScoreVector(scores);
15197
15301
  const tx = await studio.submitScoreVectorForWorker(dataHash, workerAddress, scoreVector);
15198
15302
  const receipt = await tx.wait();
@@ -15219,7 +15323,7 @@ var StudioClient = class {
15219
15323
  `RewardsDistributor contract address not found for network: ${this.network}.`
15220
15324
  );
15221
15325
  }
15222
- const distributor = new ethers.Contract(
15326
+ const distributor = new ethers.ethers.Contract(
15223
15327
  rewardsDistributorAddress,
15224
15328
  REWARDS_DISTRIBUTOR_ABI,
15225
15329
  this.signer
@@ -15239,7 +15343,7 @@ var StudioClient = class {
15239
15343
  * @returns Pending reward amount in wei
15240
15344
  */
15241
15345
  async getPendingRewards(studioAddress, account) {
15242
- const studio = new ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.provider);
15346
+ const studio = new ethers.ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.provider);
15243
15347
  return studio.getWithdrawableBalance(account);
15244
15348
  }
15245
15349
  /**
@@ -15249,7 +15353,7 @@ var StudioClient = class {
15249
15353
  * @returns Transaction hash
15250
15354
  */
15251
15355
  async withdrawRewards(studioAddress) {
15252
- const studio = new ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.signer);
15356
+ const studio = new ethers.ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.signer);
15253
15357
  const tx = await studio.withdrawRewards();
15254
15358
  const receipt = await tx.wait();
15255
15359
  return receipt.hash;
@@ -15266,9 +15370,9 @@ var StudioClient = class {
15266
15370
  * @returns bytes32 commitment hash
15267
15371
  */
15268
15372
  computeScoreCommitment(scores, salt, dataHash) {
15269
- const abiCoder = new ethers.AbiCoder();
15373
+ const abiCoder = new ethers.ethers.AbiCoder();
15270
15374
  const encoded = abiCoder.encode(["uint8[]", "bytes32", "bytes32"], [scores, salt, dataHash]);
15271
- return ethers.keccak256(encoded);
15375
+ return ethers.ethers.keccak256(encoded);
15272
15376
  }
15273
15377
  /**
15274
15378
  * Encode score vector for revealScore.
@@ -15277,7 +15381,7 @@ var StudioClient = class {
15277
15381
  * @returns ABI-encoded bytes
15278
15382
  */
15279
15383
  encodeScoreVector(scores) {
15280
- const abiCoder = new ethers.AbiCoder();
15384
+ const abiCoder = new ethers.ethers.AbiCoder();
15281
15385
  return abiCoder.encode(["uint8[]"], [scores]);
15282
15386
  }
15283
15387
  /**
@@ -15286,13 +15390,12 @@ var StudioClient = class {
15286
15390
  * @returns bytes32 random salt
15287
15391
  */
15288
15392
  generateSalt() {
15289
- return ethers.hexlify(ethers.randomBytes(32));
15393
+ return ethers.ethers.hexlify(ethers.ethers.randomBytes(32));
15290
15394
  }
15291
15395
  };
15292
15396
 
15293
15397
  // src/ChaosChainSDK.ts
15294
15398
  var ChaosChainSDK = class _ChaosChainSDK {
15295
- static warnedGatewayMissing = false;
15296
15399
  static warnedStudioClientProduction = false;
15297
15400
  // Core components
15298
15401
  walletManager;
@@ -15371,7 +15474,7 @@ var ChaosChainSDK = class _ChaosChainSDK {
15371
15474
  );
15372
15475
  }
15373
15476
  try {
15374
- this.provider = new ethers.JsonRpcProvider(rpcUrl);
15477
+ this.provider = new ethers.ethers.JsonRpcProvider(rpcUrl);
15375
15478
  } catch (error) {
15376
15479
  throw new ConfigurationError(
15377
15480
  `Failed to initialize provider for network "${String(config.network)}".`,
@@ -15470,23 +15573,16 @@ var ChaosChainSDK = class _ChaosChainSDK {
15470
15573
  this.computeProvider
15471
15574
  );
15472
15575
  }
15473
- if (config.gatewayConfig || config.gatewayUrl) {
15474
- const gatewayConfig = config.gatewayConfig || { gatewayUrl: config.gatewayUrl };
15475
- this.gateway = new GatewayClient(gatewayConfig);
15476
- console.log(`\u{1F310} Gateway client initialized: ${gatewayConfig.gatewayUrl}`);
15477
- }
15576
+ const gatewayConfig = config.gatewayConfig ?? (config.gatewayUrl ? { gatewayUrl: config.gatewayUrl } : {});
15577
+ this.gateway = new GatewayClient(gatewayConfig);
15578
+ const gatewayBaseUrl = gatewayConfig.baseUrl ?? gatewayConfig.gatewayUrl ?? "https://gateway.chaoscha.in";
15579
+ console.log(`\u{1F310} Gateway client initialized: ${gatewayBaseUrl}`);
15478
15580
  this.studio = new StudioClient({
15479
15581
  provider: this.provider,
15480
15582
  signer: this.walletManager.getWallet(),
15481
15583
  network: typeof config.network === "string" ? config.network : config.network
15482
15584
  });
15483
15585
  const isLocalNetwork = String(config.network) === "local" /* LOCAL */ || String(config.network) === "local";
15484
- if (!this.gateway && !isLocalNetwork && !_ChaosChainSDK.warnedGatewayMissing) {
15485
- console.warn(
15486
- "\u26A0\uFE0F Gateway is not configured. For production workflows, use gatewayConfig to enable Gateway orchestration."
15487
- );
15488
- _ChaosChainSDK.warnedGatewayMissing = true;
15489
- }
15490
15586
  if (process.env.NODE_ENV === "production" && !isLocalNetwork && !_ChaosChainSDK.warnedStudioClientProduction) {
15491
15587
  console.warn(
15492
15588
  "\u26A0\uFE0F StudioClient is intended for low-level or testing use. In production, prefer Gateway workflows."
@@ -15589,19 +15685,19 @@ var ChaosChainSDK = class _ChaosChainSDK {
15589
15685
  * Get agent reputation score (ERC-8004 v1.0)
15590
15686
  */
15591
15687
  async getReputationScore(agentId) {
15592
- const summary = await this.chaosAgent.getSummary(agentId, [], ethers.ZeroHash, ethers.ZeroHash);
15688
+ const summary = await this.chaosAgent.getSummary(agentId, [], ethers.ethers.ZeroHash, ethers.ethers.ZeroHash);
15593
15689
  return summary.averageScore;
15594
15690
  }
15595
15691
  /**
15596
15692
  * Read all feedback for an agent
15597
15693
  */
15598
- async readAllFeedback(agentId, clientAddresses = [], tag1 = ethers.ZeroHash, tag2 = ethers.ZeroHash, includeRevoked = false) {
15694
+ async readAllFeedback(agentId, clientAddresses = [], tag1 = ethers.ethers.ZeroHash, tag2 = ethers.ethers.ZeroHash, includeRevoked = false) {
15599
15695
  return this.chaosAgent.readAllFeedback(agentId, clientAddresses, tag1, tag2, includeRevoked);
15600
15696
  }
15601
15697
  /**
15602
15698
  * Get feedback summary statistics
15603
15699
  */
15604
- async getFeedbackSummary(agentId, clientAddresses = [], tag1 = ethers.ZeroHash, tag2 = ethers.ZeroHash) {
15700
+ async getFeedbackSummary(agentId, clientAddresses = [], tag1 = ethers.ethers.ZeroHash, tag2 = ethers.ethers.ZeroHash) {
15605
15701
  return this.chaosAgent.getSummary(agentId, clientAddresses, tag1, tag2);
15606
15702
  }
15607
15703
  /**
@@ -15640,7 +15736,7 @@ var ChaosChainSDK = class _ChaosChainSDK {
15640
15736
  /**
15641
15737
  * Get validation summary for an agent
15642
15738
  */
15643
- async getValidationSummary(agentId, validatorAddresses = [], tag = ethers.ZeroHash) {
15739
+ async getValidationSummary(agentId, validatorAddresses = [], tag = ethers.ethers.ZeroHash) {
15644
15740
  return this.chaosAgent.getValidationSummary(agentId, validatorAddresses, tag);
15645
15741
  }
15646
15742
  /**
@@ -15727,7 +15823,7 @@ var ChaosChainSDK = class _ChaosChainSDK {
15727
15823
  */
15728
15824
  async getETHBalance() {
15729
15825
  const balance = await this.provider.getBalance(this.getAddress());
15730
- return ethers.formatEther(balance);
15826
+ return ethers.ethers.formatEther(balance);
15731
15827
  }
15732
15828
  /**
15733
15829
  * Get USDC balance (if USDC contract exists on network)
@@ -15911,7 +16007,7 @@ var ChaosChainSDK = class _ChaosChainSDK {
15911
16007
  * Get SDK version
15912
16008
  */
15913
16009
  getVersion() {
15914
- return "0.1.3";
16010
+ return "0.2.4";
15915
16011
  }
15916
16012
  /**
15917
16013
  * Get SDK capabilities summary
@@ -16090,7 +16186,7 @@ var IPFSLocalStorage = class {
16090
16186
  const formData = new FormData();
16091
16187
  const blob = new Blob([buffer], { type: options?.mime || "application/octet-stream" });
16092
16188
  formData.append("file", blob);
16093
- const response = await axios2.post(`${this.apiUrl}/api/v0/add`, formData, {
16189
+ const response = await axios2__default.default.post(`${this.apiUrl}/api/v0/add`, formData, {
16094
16190
  headers: {
16095
16191
  "Content-Type": "multipart/form-data"
16096
16192
  },
@@ -16115,7 +16211,7 @@ var IPFSLocalStorage = class {
16115
16211
  */
16116
16212
  async download(cid) {
16117
16213
  try {
16118
- const response = await axios2.get(`${this.gatewayUrl}/ipfs/${cid}`, {
16214
+ const response = await axios2__default.default.get(`${this.gatewayUrl}/ipfs/${cid}`, {
16119
16215
  responseType: "arraybuffer"
16120
16216
  });
16121
16217
  return Buffer.from(response.data);
@@ -16128,7 +16224,7 @@ var IPFSLocalStorage = class {
16128
16224
  */
16129
16225
  async pin(cid) {
16130
16226
  try {
16131
- await axios2.post(`${this.apiUrl}/api/v0/pin/add`, null, {
16227
+ await axios2__default.default.post(`${this.apiUrl}/api/v0/pin/add`, null, {
16132
16228
  params: { arg: cid }
16133
16229
  });
16134
16230
  } catch (error) {
@@ -16140,7 +16236,7 @@ var IPFSLocalStorage = class {
16140
16236
  */
16141
16237
  async unpin(cid) {
16142
16238
  try {
16143
- await axios2.post(`${this.apiUrl}/api/v0/pin/rm`, null, {
16239
+ await axios2__default.default.post(`${this.apiUrl}/api/v0/pin/rm`, null, {
16144
16240
  params: { arg: cid }
16145
16241
  });
16146
16242
  } catch (error) {
@@ -16152,7 +16248,7 @@ var IPFSLocalStorage = class {
16152
16248
  */
16153
16249
  async isAvailable() {
16154
16250
  try {
16155
- await axios2.post(`${this.apiUrl}/api/v0/version`);
16251
+ await axios2__default.default.post(`${this.apiUrl}/api/v0/version`);
16156
16252
  return true;
16157
16253
  } catch {
16158
16254
  return false;
@@ -16163,7 +16259,7 @@ var IPFSLocalStorage = class {
16163
16259
  */
16164
16260
  async getVersion() {
16165
16261
  try {
16166
- const response = await axios2.post(`${this.apiUrl}/api/v0/version`);
16262
+ const response = await axios2__default.default.post(`${this.apiUrl}/api/v0/version`);
16167
16263
  return response.data.Version;
16168
16264
  } catch (error) {
16169
16265
  throw new Error(`Failed to get IPFS version: ${error.message}`);
@@ -16342,8 +16438,372 @@ var StudioManager = class {
16342
16438
  }
16343
16439
  };
16344
16440
 
16441
+ // src/evidence.ts
16442
+ function rangeFit(value, min, target, max) {
16443
+ if (value <= min || value >= max) return 0;
16444
+ if (value === target) return 1;
16445
+ if (value < target) {
16446
+ return Math.max(0, Math.min(1, (value - min) / (target - min)));
16447
+ }
16448
+ return Math.max(0, Math.min(1, (max - value) / (max - target)));
16449
+ }
16450
+ function resolveScoring(policy, mandate) {
16451
+ if (!policy) return void 0;
16452
+ if (!mandate?.overrides) return policy.scoring;
16453
+ const base = policy.scoring;
16454
+ const ov = mandate.overrides;
16455
+ return {
16456
+ initiative: ov.initiative ?? base.initiative,
16457
+ collaboration: ov.collaboration ?? base.collaboration,
16458
+ reasoning: ov.reasoning ?? base.reasoning,
16459
+ compliance: ov.compliance ?? base.compliance,
16460
+ efficiency: ov.efficiency ?? base.efficiency
16461
+ };
16462
+ }
16463
+ function computeObserved(evidence) {
16464
+ const totalNodes = evidence.length;
16465
+ const byId = /* @__PURE__ */ new Map();
16466
+ const childrenOf = /* @__PURE__ */ new Map();
16467
+ for (const e of evidence) {
16468
+ byId.set(e.arweave_tx_id, e);
16469
+ childrenOf.set(e.arweave_tx_id, []);
16470
+ }
16471
+ let edgeCount = 0;
16472
+ let rootCount = 0;
16473
+ let artifactCount = 0;
16474
+ for (const e of evidence) {
16475
+ edgeCount += e.parent_ids.length;
16476
+ if (e.parent_ids.length === 0) rootCount++;
16477
+ if (e.artifact_ids.length > 0) artifactCount++;
16478
+ for (const pid of e.parent_ids) {
16479
+ const c = childrenOf.get(pid);
16480
+ if (c) c.push(e.arweave_tx_id);
16481
+ }
16482
+ }
16483
+ const rootOrigins = /* @__PURE__ */ new Map();
16484
+ function getRootOrigins(id) {
16485
+ if (rootOrigins.has(id)) return rootOrigins.get(id);
16486
+ const node = byId.get(id);
16487
+ if (!node || node.parent_ids.length === 0) {
16488
+ const s = /* @__PURE__ */ new Set([id]);
16489
+ rootOrigins.set(id, s);
16490
+ return s;
16491
+ }
16492
+ const origins = /* @__PURE__ */ new Set();
16493
+ for (const pid of node.parent_ids) {
16494
+ for (const r of getRootOrigins(pid)) origins.add(r);
16495
+ }
16496
+ rootOrigins.set(id, origins);
16497
+ return origins;
16498
+ }
16499
+ for (const e of evidence) getRootOrigins(e.arweave_tx_id);
16500
+ let integrationNodeCount = 0;
16501
+ for (const e of evidence) {
16502
+ if (e.parent_ids.length < 2) continue;
16503
+ const parentRootSets = e.parent_ids.filter((pid) => byId.has(pid)).map((pid) => rootOrigins.get(pid));
16504
+ const uniqueRoots = /* @__PURE__ */ new Set();
16505
+ for (const s of parentRootSets) {
16506
+ for (const r of s) uniqueRoots.add(r);
16507
+ }
16508
+ if (uniqueRoots.size >= 2) integrationNodeCount++;
16509
+ }
16510
+ let terminalCount = 0;
16511
+ for (const [, children] of childrenOf) {
16512
+ if (children.length === 0) terminalCount++;
16513
+ }
16514
+ const uniqueAuthors = new Set(evidence.map((e) => e.author)).size;
16515
+ const timestamps = evidence.map((e) => e.timestamp).filter((t) => t > 0);
16516
+ const durationMs = timestamps.length >= 2 ? Math.max(...timestamps) - Math.min(...timestamps) : void 0;
16517
+ const maxDepth = computeDepth(evidence);
16518
+ return {
16519
+ totalNodes,
16520
+ rootCount,
16521
+ edgeCount,
16522
+ maxDepth,
16523
+ artifactCount,
16524
+ terminalCount,
16525
+ integrationNodeCount,
16526
+ uniqueAuthors,
16527
+ durationMs
16528
+ };
16529
+ }
16530
+ function computeComplianceSignal(evidence, _observed, scoring, mandate) {
16531
+ const compliance = scoring.compliance;
16532
+ const allArtifacts = /* @__PURE__ */ new Set();
16533
+ for (const e of evidence) {
16534
+ for (const a of e.artifact_ids) allArtifacts.add(a);
16535
+ }
16536
+ const testPatterns = ["test", "spec", ".test.", ".spec.", "__test__", "__spec__"];
16537
+ const testsPresent = [...allArtifacts].some((a) => {
16538
+ const lower = a.toLowerCase();
16539
+ return testPatterns.some((p) => lower.includes(p));
16540
+ });
16541
+ const requiredArtifacts = [
16542
+ ...compliance.requiredArtifacts ?? [],
16543
+ ...mandate?.constraints?.requiredArtifacts ?? []
16544
+ ];
16545
+ const present = [];
16546
+ const missing = [];
16547
+ for (const req of requiredArtifacts) {
16548
+ const found = [...allArtifacts].some((a) => a.toLowerCase().includes(req.toLowerCase()));
16549
+ if (found) present.push(req);
16550
+ else missing.push(req);
16551
+ }
16552
+ const forbiddenPatterns = [
16553
+ ...compliance.forbiddenPatterns ?? [],
16554
+ ...mandate?.constraints?.forbiddenPatterns ?? []
16555
+ ];
16556
+ const violations = [];
16557
+ for (const pattern of forbiddenPatterns) {
16558
+ const lower = pattern.toLowerCase();
16559
+ if ([...allArtifacts].some((a) => a.toLowerCase().includes(lower))) {
16560
+ violations.push(`forbidden pattern found: ${pattern}`);
16561
+ }
16562
+ }
16563
+ if (mandate?.constraints?.mustPassTests && !testsPresent) {
16564
+ violations.push("mandate requires tests but none detected");
16565
+ }
16566
+ const w = compliance.weights;
16567
+ const totalWeight = (w.testsPresent ?? 0) + (w.requiredArtifactsPresent ?? 0) + (w.noPolicyViolations ?? 0);
16568
+ if (totalWeight === 0) {
16569
+ return { signal: testsPresent ? 1 : 0, testsPresent, violations, present, missing };
16570
+ }
16571
+ const testsScore = testsPresent ? 1 : 0;
16572
+ const artifactScore = requiredArtifacts.length > 0 ? present.length / requiredArtifacts.length : 1;
16573
+ const violationScore = violations.length === 0 ? 1 : 0;
16574
+ const signal = Math.max(0, Math.min(
16575
+ 1,
16576
+ (w.testsPresent * testsScore + w.requiredArtifactsPresent * artifactScore + w.noPolicyViolations * violationScore) / totalWeight
16577
+ ));
16578
+ return { signal, testsPresent, violations, present, missing };
16579
+ }
16580
+ function computeEfficiencySignal(observed, scoring, mandate) {
16581
+ const eff = scoring.efficiency;
16582
+ const w = eff.weights;
16583
+ let totalWeight = 0;
16584
+ let weightedSum = 0;
16585
+ if (eff.durationRatio && w.durationRatio && observed.durationMs !== void 0) {
16586
+ const latencyBudget = mandate?.constraints?.latencyBudgetMs;
16587
+ if (latencyBudget && latencyBudget > 0) {
16588
+ const ratio = observed.durationMs / latencyBudget;
16589
+ weightedSum += w.durationRatio * rangeFit(ratio, eff.durationRatio.min, eff.durationRatio.target, eff.durationRatio.max);
16590
+ totalWeight += w.durationRatio;
16591
+ }
16592
+ }
16593
+ if (eff.artifactCountRatio && w.artifactCountRatio && observed.totalNodes > 0) {
16594
+ const ratio = observed.artifactCount / observed.totalNodes;
16595
+ weightedSum += w.artifactCountRatio * rangeFit(ratio, eff.artifactCountRatio.min, eff.artifactCountRatio.target, eff.artifactCountRatio.max);
16596
+ totalWeight += w.artifactCountRatio;
16597
+ }
16598
+ if (totalWeight === 0) return void 0;
16599
+ return Math.max(0, Math.min(1, weightedSum / totalWeight));
16600
+ }
16601
+ function extractAgencySignals(evidence, context) {
16602
+ const totalNodes = evidence.length;
16603
+ if (totalNodes === 0) {
16604
+ return {
16605
+ initiativeSignal: 0,
16606
+ collaborationSignal: 0,
16607
+ reasoningSignal: 0,
16608
+ observed: {
16609
+ totalNodes: 0,
16610
+ rootCount: 0,
16611
+ edgeCount: 0,
16612
+ maxDepth: 0,
16613
+ artifactCount: 0,
16614
+ terminalCount: 0,
16615
+ integrationNodeCount: 0
16616
+ }
16617
+ };
16618
+ }
16619
+ const observed = computeObserved(evidence);
16620
+ const rootRatio = observed.rootCount / totalNodes;
16621
+ const edgeDensity = observed.edgeCount / Math.max(totalNodes - 1, 1);
16622
+ const integrationRatio = observed.integrationNodeCount / totalNodes;
16623
+ const depthRatio = observed.maxDepth / totalNodes;
16624
+ const scoring = resolveScoring(context?.studioPolicy, context?.workMandate);
16625
+ let initiativeSignal;
16626
+ let collaborationSignal;
16627
+ let reasoningSignal;
16628
+ let complianceSignal;
16629
+ let efficiencySignal;
16630
+ const observedBlock = {
16631
+ totalNodes,
16632
+ rootCount: observed.rootCount,
16633
+ edgeCount: observed.edgeCount,
16634
+ maxDepth: observed.maxDepth,
16635
+ artifactCount: observed.artifactCount,
16636
+ terminalCount: observed.terminalCount,
16637
+ integrationNodeCount: observed.integrationNodeCount,
16638
+ uniqueAuthors: observed.uniqueAuthors,
16639
+ durationMs: observed.durationMs
16640
+ };
16641
+ if (!scoring) {
16642
+ const SOFT_CAP = 0.9;
16643
+ initiativeSignal = Math.max(0, Math.min(SOFT_CAP, rootRatio));
16644
+ collaborationSignal = Math.max(0, Math.min(SOFT_CAP, edgeDensity));
16645
+ reasoningSignal = Math.max(0, Math.min(SOFT_CAP, depthRatio));
16646
+ } else {
16647
+ const ir = scoring.initiative.rootRatio;
16648
+ const initiativeBase = rangeFit(rootRatio, ir.min, ir.target, ir.max);
16649
+ const cw = scoring.collaboration.weights;
16650
+ const ed = scoring.collaboration.edgeDensity;
16651
+ const intR = scoring.collaboration.integrationRatio;
16652
+ const collabWeightSum = (cw.edgeDensity || 0) + (cw.integrationRatio || 0);
16653
+ if (collabWeightSum > 0) {
16654
+ collaborationSignal = (cw.edgeDensity * rangeFit(edgeDensity, ed.min, ed.target, ed.max) + cw.integrationRatio * rangeFit(integrationRatio, intR.min, intR.target, intR.max)) / collabWeightSum;
16655
+ } else {
16656
+ collaborationSignal = 0;
16657
+ }
16658
+ collaborationSignal = Math.max(0, Math.min(1, collaborationSignal));
16659
+ const dr = scoring.reasoning.depthRatio;
16660
+ const reasoningBase = rangeFit(depthRatio, dr.min, dr.target, dr.max);
16661
+ const fragmentationPenalty = rootRatio > ir.max ? (rootRatio - ir.max) * 0.5 : 0;
16662
+ const overcomplexityPenalty = depthRatio > dr.max ? (depthRatio - dr.max) * 0.5 : 0;
16663
+ initiativeSignal = Math.max(0, Math.min(1, initiativeBase - fragmentationPenalty));
16664
+ reasoningSignal = Math.max(0, Math.min(1, reasoningBase - overcomplexityPenalty));
16665
+ observedBlock.fragmentationPenalty = fragmentationPenalty;
16666
+ observedBlock.overcomplexityPenalty = overcomplexityPenalty;
16667
+ const compResult = computeComplianceSignal(evidence, observed, scoring, context?.workMandate);
16668
+ complianceSignal = compResult.signal;
16669
+ observedBlock.testsPresent = compResult.testsPresent;
16670
+ observedBlock.policyViolations = compResult.violations;
16671
+ observedBlock.requiredArtifactsPresent = compResult.present;
16672
+ observedBlock.missingArtifacts = compResult.missing;
16673
+ efficiencySignal = computeEfficiencySignal(observed, scoring, context?.workMandate);
16674
+ }
16675
+ return {
16676
+ initiativeSignal,
16677
+ collaborationSignal,
16678
+ reasoningSignal,
16679
+ complianceSignal,
16680
+ efficiencySignal,
16681
+ observed: observedBlock
16682
+ };
16683
+ }
16684
+ function computeDepth(evidence) {
16685
+ if (evidence.length === 0) return 0;
16686
+ const byId = /* @__PURE__ */ new Map();
16687
+ for (const e of evidence) byId.set(e.arweave_tx_id, e);
16688
+ const memo = /* @__PURE__ */ new Map();
16689
+ function dfs(id) {
16690
+ if (memo.has(id)) return memo.get(id);
16691
+ const node = byId.get(id);
16692
+ if (!node || node.parent_ids.length === 0) {
16693
+ memo.set(id, 1);
16694
+ return 1;
16695
+ }
16696
+ let maxParent = 0;
16697
+ for (const pid of node.parent_ids) {
16698
+ maxParent = Math.max(maxParent, dfs(pid));
16699
+ }
16700
+ const depth = maxParent + 1;
16701
+ memo.set(id, depth);
16702
+ return depth;
16703
+ }
16704
+ let maxDepth = 0;
16705
+ for (const e of evidence) {
16706
+ maxDepth = Math.max(maxDepth, dfs(e.arweave_tx_id));
16707
+ }
16708
+ return maxDepth;
16709
+ }
16710
+ function normalizeInput(value) {
16711
+ const v = value > 1 ? value / 100 : value;
16712
+ return Math.max(0, Math.min(1, v));
16713
+ }
16714
+ var CLAMP_100 = (v) => Math.max(0, Math.min(100, Math.round(v)));
16715
+ function resolveDimension(override, signal) {
16716
+ if (override !== void 0) return normalizeInput(override);
16717
+ return signal ?? 0;
16718
+ }
16719
+ function composeScoreVector(signals, assessment) {
16720
+ if (assessment.complianceScore === void 0 || assessment.complianceScore === null) {
16721
+ throw new Error("complianceScore is required for production scoring");
16722
+ }
16723
+ if (assessment.efficiencyScore === void 0 || assessment.efficiencyScore === null) {
16724
+ throw new Error("efficiencyScore is required for production scoring");
16725
+ }
16726
+ return [
16727
+ CLAMP_100(resolveDimension(assessment.initiativeScore, signals.initiativeSignal) * 100),
16728
+ CLAMP_100(resolveDimension(assessment.collaborationScore, signals.collaborationSignal) * 100),
16729
+ CLAMP_100(resolveDimension(assessment.reasoningScore, signals.reasoningSignal) * 100),
16730
+ CLAMP_100(normalizeInput(assessment.complianceScore) * 100),
16731
+ CLAMP_100(normalizeInput(assessment.efficiencyScore) * 100)
16732
+ ];
16733
+ }
16734
+ function composeScoreVectorWithDefaults(signals, assessment) {
16735
+ return [
16736
+ CLAMP_100(resolveDimension(assessment?.initiativeScore, signals.initiativeSignal) * 100),
16737
+ CLAMP_100(resolveDimension(assessment?.collaborationScore, signals.collaborationSignal) * 100),
16738
+ CLAMP_100(resolveDimension(assessment?.reasoningScore, signals.reasoningSignal) * 100),
16739
+ CLAMP_100(resolveDimension(assessment?.complianceScore, signals.complianceSignal) * 100),
16740
+ CLAMP_100(resolveDimension(assessment?.efficiencyScore, signals.efficiencySignal) * 100)
16741
+ ];
16742
+ }
16743
+ function derivePoAScores(evidence, options) {
16744
+ if (evidence.length === 0) {
16745
+ return [
16746
+ 0,
16747
+ 0,
16748
+ 0,
16749
+ CLAMP_100(options?.compliance !== void 0 ? normalizeInput(options.compliance) * 100 : 0),
16750
+ CLAMP_100(options?.efficiency !== void 0 ? normalizeInput(options.efficiency) * 100 : 0)
16751
+ ];
16752
+ }
16753
+ const signals = extractAgencySignals(evidence);
16754
+ return composeScoreVectorWithDefaults(signals, {
16755
+ complianceScore: options?.compliance,
16756
+ efficiencyScore: options?.efficiency
16757
+ });
16758
+ }
16759
+ function validateEvidenceGraph(evidence) {
16760
+ const ids = new Set(evidence.map((e) => e.arweave_tx_id));
16761
+ for (const e of evidence) {
16762
+ for (const pid of e.parent_ids) {
16763
+ if (!ids.has(pid)) return false;
16764
+ }
16765
+ }
16766
+ const inDegree = /* @__PURE__ */ new Map();
16767
+ const children = /* @__PURE__ */ new Map();
16768
+ for (const e of evidence) {
16769
+ if (!inDegree.has(e.arweave_tx_id)) inDegree.set(e.arweave_tx_id, 0);
16770
+ if (!children.has(e.arweave_tx_id)) children.set(e.arweave_tx_id, []);
16771
+ }
16772
+ for (const e of evidence) {
16773
+ for (const pid of e.parent_ids) {
16774
+ inDegree.set(e.arweave_tx_id, (inDegree.get(e.arweave_tx_id) ?? 0) + 1);
16775
+ const c = children.get(pid) ?? [];
16776
+ c.push(e.arweave_tx_id);
16777
+ children.set(pid, c);
16778
+ }
16779
+ }
16780
+ const queue = [];
16781
+ for (const [id, deg] of inDegree) {
16782
+ if (deg === 0) queue.push(id);
16783
+ }
16784
+ let visited = 0;
16785
+ while (queue.length > 0) {
16786
+ const node = queue.shift();
16787
+ visited++;
16788
+ for (const child of children.get(node) ?? []) {
16789
+ const newDeg = (inDegree.get(child) ?? 1) - 1;
16790
+ inDegree.set(child, newDeg);
16791
+ if (newDeg === 0) queue.push(child);
16792
+ }
16793
+ }
16794
+ return visited === evidence.length;
16795
+ }
16796
+ function verifyWorkEvidence(evidence, context) {
16797
+ const valid = validateEvidenceGraph(evidence);
16798
+ if (!valid) {
16799
+ return { valid: false };
16800
+ }
16801
+ const signals = extractAgencySignals(evidence, context);
16802
+ return { valid: true, signals };
16803
+ }
16804
+
16345
16805
  // src/index.ts
16346
- var SDK_VERSION = "0.2.0";
16806
+ var SDK_VERSION = "0.2.4";
16347
16807
  var ERC8004_VERSION = "1.0";
16348
16808
  var X402_VERSION = "1.0";
16349
16809
  var src_default = ChaosChainSDK;
@@ -16369,6 +16829,65 @@ mime-types/index.js:
16369
16829
  *)
16370
16830
  */
16371
16831
 
16372
- export { A2AX402Extension, AgentRegistrationError, AgentRole, AutoStorageManager, CHAOS_CORE_ABI, ChaosAgent, ChaosChainSDK, ChaosChainSDKError, ConfigurationError, ContractError, ERC8004_VERSION, GatewayClient, GatewayConnectionError, GatewayError, GatewayTimeoutError, GoogleAP2Integration, IDENTITY_REGISTRY_ABI, IPFSLocalStorage, PinataStorage as IPFSPinataStorage, IntegrityVerificationError, IrysStorage, IrysStorage as IrysStorageProvider, LocalIPFSStorage, MandateManager, NetworkConfig, PaymentError, PaymentManager, PaymentMethod, PinataStorage, REPUTATION_REGISTRY_ABI, REWARDS_DISTRIBUTOR_ABI, ValidationError as SDKValidationError, SDK_VERSION, STUDIO_FACTORY_ABI, STUDIO_PROXY_ABI, StorageError, StudioClient, StudioManager, VALIDATION_REGISTRY_ABI, ValidationStatus, WalletManager, WorkflowFailedError, WorkflowState, WorkflowType, X402PaymentManager, X402Server, X402_VERSION, ZeroGStorage, src_default as default, getContractAddresses2 as getContractAddresses, getNetworkInfo, initChaosChainSDK };
16373
- //# sourceMappingURL=index.mjs.map
16374
- //# sourceMappingURL=index.mjs.map
16832
+ exports.A2AX402Extension = A2AX402Extension;
16833
+ exports.AgentRegistrationError = AgentRegistrationError;
16834
+ exports.AgentRole = AgentRole;
16835
+ exports.AutoStorageManager = AutoStorageManager;
16836
+ exports.CHAOS_CORE_ABI = CHAOS_CORE_ABI;
16837
+ exports.ChaosAgent = ChaosAgent;
16838
+ exports.ChaosChainSDK = ChaosChainSDK;
16839
+ exports.ChaosChainSDKError = ChaosChainSDKError;
16840
+ exports.ConfigurationError = ConfigurationError;
16841
+ exports.ContractError = ContractError;
16842
+ exports.ERC8004_VERSION = ERC8004_VERSION;
16843
+ exports.GatewayClient = GatewayClient;
16844
+ exports.GatewayConnectionError = GatewayConnectionError;
16845
+ exports.GatewayError = GatewayError;
16846
+ exports.GatewayTimeoutError = GatewayTimeoutError;
16847
+ exports.GoogleAP2Integration = GoogleAP2Integration;
16848
+ exports.IDENTITY_REGISTRY_ABI = IDENTITY_REGISTRY_ABI;
16849
+ exports.IPFSLocalStorage = IPFSLocalStorage;
16850
+ exports.IPFSPinataStorage = PinataStorage;
16851
+ exports.IntegrityVerificationError = IntegrityVerificationError;
16852
+ exports.IrysStorage = IrysStorage;
16853
+ exports.IrysStorageProvider = IrysStorage;
16854
+ exports.LocalIPFSStorage = LocalIPFSStorage;
16855
+ exports.MandateManager = MandateManager;
16856
+ exports.NetworkConfig = NetworkConfig;
16857
+ exports.PaymentError = PaymentError;
16858
+ exports.PaymentManager = PaymentManager;
16859
+ exports.PaymentMethod = PaymentMethod;
16860
+ exports.PinataStorage = PinataStorage;
16861
+ exports.REPUTATION_REGISTRY_ABI = REPUTATION_REGISTRY_ABI;
16862
+ exports.REWARDS_DISTRIBUTOR_ABI = REWARDS_DISTRIBUTOR_ABI;
16863
+ exports.SDKValidationError = ValidationError;
16864
+ exports.SDK_VERSION = SDK_VERSION;
16865
+ exports.STUDIO_FACTORY_ABI = STUDIO_FACTORY_ABI;
16866
+ exports.STUDIO_PROXY_ABI = STUDIO_PROXY_ABI;
16867
+ exports.StorageError = StorageError;
16868
+ exports.StudioClient = StudioClient;
16869
+ exports.StudioManager = StudioManager;
16870
+ exports.VALIDATION_REGISTRY_ABI = VALIDATION_REGISTRY_ABI;
16871
+ exports.ValidationStatus = ValidationStatus;
16872
+ exports.WalletManager = WalletManager;
16873
+ exports.WorkflowFailedError = WorkflowFailedError;
16874
+ exports.WorkflowState = WorkflowState;
16875
+ exports.WorkflowType = WorkflowType;
16876
+ exports.X402PaymentManager = X402PaymentManager;
16877
+ exports.X402Server = X402Server;
16878
+ exports.X402_VERSION = X402_VERSION;
16879
+ exports.ZeroGStorage = ZeroGStorage;
16880
+ exports.composeScoreVector = composeScoreVector;
16881
+ exports.composeScoreVectorWithDefaults = composeScoreVectorWithDefaults;
16882
+ exports.computeDepth = computeDepth;
16883
+ exports.default = src_default;
16884
+ exports.derivePoAScores = derivePoAScores;
16885
+ exports.extractAgencySignals = extractAgencySignals;
16886
+ exports.getContractAddresses = getContractAddresses2;
16887
+ exports.getNetworkInfo = getNetworkInfo;
16888
+ exports.initChaosChainSDK = initChaosChainSDK;
16889
+ exports.rangeFit = rangeFit;
16890
+ exports.validateEvidenceGraph = validateEvidenceGraph;
16891
+ exports.verifyWorkEvidence = verifyWorkEvidence;
16892
+ //# sourceMappingURL=index.cjs.map
16893
+ //# sourceMappingURL=index.cjs.map