@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.
- package/README.md +109 -8
- package/dist/IPFSLocal-BqyHRp_l.d.ts +38 -0
- package/dist/IPFSLocal-azjjaiGR.d.cts +38 -0
- package/dist/{index.mjs → index.cjs} +665 -146
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +2575 -0
- package/dist/index.d.ts +2575 -0
- package/dist/index.js +576 -223
- package/dist/index.js.map +1 -1
- package/dist/providers/compute/{index.mjs → index.cjs} +5 -3
- package/dist/providers/compute/index.cjs.map +1 -0
- package/dist/providers/compute/index.d.cts +17 -0
- package/dist/providers/compute/index.d.ts +17 -0
- package/dist/providers/compute/index.js +1 -3
- package/dist/providers/compute/index.js.map +1 -1
- package/dist/providers/storage/{index.mjs → index.cjs} +23 -15
- package/dist/providers/storage/index.cjs.map +1 -0
- package/dist/providers/storage/index.d.cts +82 -0
- package/dist/providers/storage/index.d.ts +82 -0
- package/dist/providers/storage/index.js +13 -21
- package/dist/providers/storage/index.js.map +1 -1
- package/dist/types-DZze-Z8B.d.cts +780 -0
- package/dist/types-DZze-Z8B.d.ts +780 -0
- package/package.json +10 -9
- package/dist/index.mjs.map +0 -1
- package/dist/providers/compute/index.mjs.map +0 -1
- package/dist/providers/storage/index.mjs.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,41 +1,13 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
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);
|
|
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';
|
|
39
11
|
|
|
40
12
|
var __create = Object.create;
|
|
41
13
|
var __defProp = Object.defineProperty;
|
|
@@ -65,7 +37,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
65
37
|
// file that has been converted to a CommonJS file using a Babel-
|
|
66
38
|
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
67
39
|
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
68
|
-
|
|
40
|
+
__defProp(target, "default", { value: mod, enumerable: true }) ,
|
|
69
41
|
mod
|
|
70
42
|
));
|
|
71
43
|
|
|
@@ -10313,27 +10285,27 @@ var WalletManager = class _WalletManager {
|
|
|
10313
10285
|
*/
|
|
10314
10286
|
initializeWallet(config) {
|
|
10315
10287
|
if (config.privateKey) {
|
|
10316
|
-
return new ethers.
|
|
10288
|
+
return new ethers.Wallet(config.privateKey);
|
|
10317
10289
|
}
|
|
10318
10290
|
if (config.mnemonic) {
|
|
10319
|
-
return ethers.
|
|
10291
|
+
return ethers.Wallet.fromPhrase(config.mnemonic);
|
|
10320
10292
|
}
|
|
10321
10293
|
if (config.walletFile) {
|
|
10322
10294
|
return this.loadFromFile(config.walletFile);
|
|
10323
10295
|
}
|
|
10324
|
-
return ethers.
|
|
10296
|
+
return ethers.Wallet.createRandom();
|
|
10325
10297
|
}
|
|
10326
10298
|
/**
|
|
10327
10299
|
* Load wallet from encrypted file
|
|
10328
10300
|
*/
|
|
10329
10301
|
loadFromFile(filePath) {
|
|
10330
10302
|
try {
|
|
10331
|
-
const walletData =
|
|
10303
|
+
const walletData = fs3.readFileSync(filePath, "utf8");
|
|
10332
10304
|
const data = JSON.parse(walletData);
|
|
10333
10305
|
if (data.encrypted) {
|
|
10334
10306
|
throw new Error("Encrypted wallets require password (not yet implemented)");
|
|
10335
10307
|
}
|
|
10336
|
-
return new ethers.
|
|
10308
|
+
return new ethers.Wallet(data.privateKey);
|
|
10337
10309
|
} catch (error) {
|
|
10338
10310
|
throw new Error(`Failed to load wallet from file: ${error.message}`);
|
|
10339
10311
|
}
|
|
@@ -10342,13 +10314,13 @@ var WalletManager = class _WalletManager {
|
|
|
10342
10314
|
* Save wallet to encrypted file
|
|
10343
10315
|
*/
|
|
10344
10316
|
async saveToFile(filePath, password) {
|
|
10345
|
-
const directory =
|
|
10346
|
-
if (!
|
|
10347
|
-
|
|
10317
|
+
const directory = path3.dirname(filePath);
|
|
10318
|
+
if (!fs3.existsSync(directory)) {
|
|
10319
|
+
fs3.mkdirSync(directory, { recursive: true });
|
|
10348
10320
|
}
|
|
10349
10321
|
if (password) {
|
|
10350
10322
|
const encrypted = await this.wallet.encrypt(password);
|
|
10351
|
-
|
|
10323
|
+
fs3.writeFileSync(filePath, encrypted, "utf8");
|
|
10352
10324
|
} else {
|
|
10353
10325
|
const data = {
|
|
10354
10326
|
address: this.wallet.address,
|
|
@@ -10356,7 +10328,7 @@ var WalletManager = class _WalletManager {
|
|
|
10356
10328
|
mnemonic: "mnemonic" in this.wallet ? this.wallet.mnemonic?.phrase : void 0,
|
|
10357
10329
|
encrypted: false
|
|
10358
10330
|
};
|
|
10359
|
-
|
|
10331
|
+
fs3.writeFileSync(filePath, JSON.stringify(data, null, 2), "utf8");
|
|
10360
10332
|
}
|
|
10361
10333
|
}
|
|
10362
10334
|
/**
|
|
@@ -10424,7 +10396,7 @@ var WalletManager = class _WalletManager {
|
|
|
10424
10396
|
* Generate a new random wallet
|
|
10425
10397
|
*/
|
|
10426
10398
|
static createRandom() {
|
|
10427
|
-
const wallet = ethers.
|
|
10399
|
+
const wallet = ethers.Wallet.createRandom();
|
|
10428
10400
|
return new _WalletManager({ privateKey: wallet.privateKey });
|
|
10429
10401
|
}
|
|
10430
10402
|
/**
|
|
@@ -10443,14 +10415,14 @@ var WalletManager = class _WalletManager {
|
|
|
10443
10415
|
* Generate new mnemonic
|
|
10444
10416
|
*/
|
|
10445
10417
|
static generateMnemonic() {
|
|
10446
|
-
return ethers.
|
|
10418
|
+
return ethers.Wallet.createRandom().mnemonic?.phrase || "";
|
|
10447
10419
|
}
|
|
10448
10420
|
/**
|
|
10449
10421
|
* Validate mnemonic
|
|
10450
10422
|
*/
|
|
10451
10423
|
static isValidMnemonic(mnemonic) {
|
|
10452
10424
|
try {
|
|
10453
|
-
ethers.
|
|
10425
|
+
ethers.Wallet.fromPhrase(mnemonic);
|
|
10454
10426
|
return true;
|
|
10455
10427
|
} catch {
|
|
10456
10428
|
return false;
|
|
@@ -10461,7 +10433,7 @@ var WalletManager = class _WalletManager {
|
|
|
10461
10433
|
*/
|
|
10462
10434
|
static isValidPrivateKey(privateKey) {
|
|
10463
10435
|
try {
|
|
10464
|
-
new ethers.
|
|
10436
|
+
new ethers.Wallet(privateKey);
|
|
10465
10437
|
return true;
|
|
10466
10438
|
} catch {
|
|
10467
10439
|
return false;
|
|
@@ -10471,7 +10443,7 @@ var WalletManager = class _WalletManager {
|
|
|
10471
10443
|
* Derive child wallet from HD path
|
|
10472
10444
|
*/
|
|
10473
10445
|
static deriveChild(mnemonic, path4) {
|
|
10474
|
-
const hdNode = ethers.
|
|
10446
|
+
const hdNode = ethers.HDNodeWallet.fromPhrase(mnemonic, void 0, path4);
|
|
10475
10447
|
return new _WalletManager({ privateKey: hdNode.privateKey });
|
|
10476
10448
|
}
|
|
10477
10449
|
};
|
|
@@ -11341,13 +11313,13 @@ var ChaosAgent = class {
|
|
|
11341
11313
|
_agentId = null;
|
|
11342
11314
|
constructor(addresses, signer, _provider) {
|
|
11343
11315
|
this.signer = signer;
|
|
11344
|
-
this.identityContract = new ethers.
|
|
11345
|
-
this.reputationContract = new ethers.
|
|
11316
|
+
this.identityContract = new ethers.Contract(addresses.identity, IDENTITY_REGISTRY_ABI, signer);
|
|
11317
|
+
this.reputationContract = new ethers.Contract(
|
|
11346
11318
|
addresses.reputation,
|
|
11347
11319
|
REPUTATION_REGISTRY_ABI,
|
|
11348
11320
|
signer
|
|
11349
11321
|
);
|
|
11350
|
-
this.validationContract = new ethers.
|
|
11322
|
+
this.validationContract = new ethers.Contract(
|
|
11351
11323
|
addresses.validation,
|
|
11352
11324
|
VALIDATION_REGISTRY_ABI,
|
|
11353
11325
|
signer
|
|
@@ -11549,23 +11521,23 @@ var ChaosAgent = class {
|
|
|
11549
11521
|
const chainId = network.chainId;
|
|
11550
11522
|
const identityAddress = await this.identityContract.getAddress();
|
|
11551
11523
|
const signerAddress = await this.signer.getAddress();
|
|
11552
|
-
const feedbackAuthData = ethers.
|
|
11524
|
+
const feedbackAuthData = ethers.solidityPackedKeccak256(
|
|
11553
11525
|
["uint256", "address", "uint64", "uint256", "uint256", "address", "address"],
|
|
11554
11526
|
[agentId, clientAddress, indexLimit, expiry, chainId, identityAddress, signerAddress]
|
|
11555
11527
|
);
|
|
11556
|
-
const signature = await this.signer.signMessage(ethers.
|
|
11557
|
-
const signatureBytes = ethers.
|
|
11558
|
-
const structBytes = ethers.
|
|
11559
|
-
ethers.
|
|
11560
|
-
ethers.
|
|
11561
|
-
ethers.
|
|
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)]),
|
|
11562
11534
|
// uint64 padded
|
|
11563
|
-
ethers.
|
|
11564
|
-
ethers.
|
|
11565
|
-
ethers.
|
|
11566
|
-
ethers.
|
|
11535
|
+
ethers.toBeHex(expiry, 32),
|
|
11536
|
+
ethers.toBeHex(chainId, 32),
|
|
11537
|
+
ethers.zeroPadValue(identityAddress, 32),
|
|
11538
|
+
ethers.zeroPadValue(signerAddress, 32)
|
|
11567
11539
|
]);
|
|
11568
|
-
const feedbackAuth = ethers.
|
|
11540
|
+
const feedbackAuth = ethers.hexlify(ethers.concat([structBytes, signatureBytes]));
|
|
11569
11541
|
console.log(`\u2705 Generated feedback authorization for agent #${agentId}`);
|
|
11570
11542
|
return feedbackAuth;
|
|
11571
11543
|
} catch (e) {
|
|
@@ -11590,7 +11562,7 @@ var ChaosAgent = class {
|
|
|
11590
11562
|
const rawValue = typeof feedbackData?.value === "bigint" || typeof feedbackData?.value === "number" ? feedbackData.value : rating;
|
|
11591
11563
|
const value = typeof rawValue === "bigint" ? rawValue : BigInt(Math.round(rawValue * Math.pow(10, valueDecimals)));
|
|
11592
11564
|
const feedbackContent = typeof feedbackData?.content === "string" ? feedbackData.content : feedbackUri;
|
|
11593
|
-
const feedbackHash = typeof feedbackData?.feedbackHash === "string" ? feedbackData.feedbackHash.startsWith("0x") ? feedbackData.feedbackHash : ethers.
|
|
11565
|
+
const feedbackHash = typeof feedbackData?.feedbackHash === "string" ? feedbackData.feedbackHash.startsWith("0x") ? feedbackData.feedbackHash : ethers.id(feedbackData.feedbackHash) : ethers.keccak256(ethers.toUtf8Bytes(feedbackContent));
|
|
11594
11566
|
const tx = await this.reputationContract.giveFeedback(
|
|
11595
11567
|
agentId,
|
|
11596
11568
|
value,
|
|
@@ -11732,7 +11704,7 @@ var ChaosAgent = class {
|
|
|
11732
11704
|
* @param requestHash Hash of the request content (bytes32)
|
|
11733
11705
|
*/
|
|
11734
11706
|
async requestValidation(validatorAddress, agentId, requestUri, requestHash) {
|
|
11735
|
-
const hashBytes = requestHash.startsWith("0x") ? requestHash : ethers.
|
|
11707
|
+
const hashBytes = requestHash.startsWith("0x") ? requestHash : ethers.id(requestHash);
|
|
11736
11708
|
const tx = await this.validationContract.validationRequest(
|
|
11737
11709
|
validatorAddress,
|
|
11738
11710
|
agentId,
|
|
@@ -11750,13 +11722,13 @@ var ChaosAgent = class {
|
|
|
11750
11722
|
* @param responseHash Hash of the response content (bytes32)
|
|
11751
11723
|
* @param tag Optional tag for categorization (bytes32)
|
|
11752
11724
|
*/
|
|
11753
|
-
async respondToValidation(requestHash, response, responseUri, responseHash, tag = ethers.
|
|
11725
|
+
async respondToValidation(requestHash, response, responseUri, responseHash, tag = ethers.ZeroHash) {
|
|
11754
11726
|
if (response < 0 || response > 100) {
|
|
11755
11727
|
throw new Error("Response must be between 0 and 100");
|
|
11756
11728
|
}
|
|
11757
|
-
const reqHashBytes = requestHash.startsWith("0x") ? requestHash : ethers.
|
|
11758
|
-
const resHashBytes = responseHash.startsWith("0x") ? responseHash : ethers.
|
|
11759
|
-
const tagBytes = tag.startsWith("0x") ? tag : ethers.
|
|
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;
|
|
11760
11732
|
const tx = await this.validationContract.validationResponse(
|
|
11761
11733
|
reqHashBytes,
|
|
11762
11734
|
response,
|
|
@@ -11772,7 +11744,7 @@ var ChaosAgent = class {
|
|
|
11772
11744
|
* @param requestHash Hash of the validation request (bytes32)
|
|
11773
11745
|
*/
|
|
11774
11746
|
async getValidationStatus(requestHash) {
|
|
11775
|
-
const hashBytes = requestHash.startsWith("0x") ? requestHash : ethers.
|
|
11747
|
+
const hashBytes = requestHash.startsWith("0x") ? requestHash : ethers.id(requestHash);
|
|
11776
11748
|
const result = await this.validationContract.getValidationStatus(hashBytes);
|
|
11777
11749
|
return {
|
|
11778
11750
|
validatorAddress: result.validatorAddress,
|
|
@@ -11789,8 +11761,8 @@ var ChaosAgent = class {
|
|
|
11789
11761
|
* @param validatorAddresses Array of validator addresses (empty for all)
|
|
11790
11762
|
* @param tag Tag filter (ZeroHash for no filter)
|
|
11791
11763
|
*/
|
|
11792
|
-
async getValidationSummary(agentId, validatorAddresses = [], tag = ethers.
|
|
11793
|
-
const tagBytes = tag.startsWith("0x") ? tag : ethers.
|
|
11764
|
+
async getValidationSummary(agentId, validatorAddresses = [], tag = ethers.ZeroHash) {
|
|
11765
|
+
const tagBytes = tag.startsWith("0x") ? tag : ethers.ZeroHash;
|
|
11794
11766
|
const result = await this.validationContract.getSummary(agentId, validatorAddresses, tagBytes);
|
|
11795
11767
|
return {
|
|
11796
11768
|
count: result.count,
|
|
@@ -11821,25 +11793,25 @@ var ChaosAgent = class {
|
|
|
11821
11793
|
// Cache Implementation
|
|
11822
11794
|
// ============================================================================
|
|
11823
11795
|
getCachedFilePath() {
|
|
11824
|
-
return
|
|
11796
|
+
return path3__default.join(process.cwd(), "chaoschain_agent_ids.json");
|
|
11825
11797
|
}
|
|
11826
11798
|
loadAgentIdFromCache(chainId, wallet) {
|
|
11827
11799
|
const cacheFile = this.getCachedFilePath();
|
|
11828
|
-
if (!
|
|
11829
|
-
const cacheData =
|
|
11800
|
+
if (!fs3__default.existsSync(cacheFile)) return null;
|
|
11801
|
+
const cacheData = fs3__default.readFileSync(cacheFile, "utf-8");
|
|
11830
11802
|
const cache = JSON.parse(cacheData);
|
|
11831
11803
|
return cache[chainId]?.[wallet]?.agentId || null;
|
|
11832
11804
|
}
|
|
11833
11805
|
saveAgentIdTocache(chainId, wallet, agentId, domain) {
|
|
11834
11806
|
const cacheFile = this.getCachedFilePath();
|
|
11835
|
-
const cache =
|
|
11807
|
+
const cache = fs3__default.existsSync(cacheFile) ? JSON.parse(fs3__default.readFileSync(cacheFile, "utf-8")) : {};
|
|
11836
11808
|
cache[String(chainId)] = cache[String(chainId)] ?? {};
|
|
11837
11809
|
cache[String(chainId)][wallet.toLowerCase()] = {
|
|
11838
11810
|
agentId,
|
|
11839
11811
|
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
11840
11812
|
domain
|
|
11841
11813
|
};
|
|
11842
|
-
|
|
11814
|
+
fs3__default.writeFileSync(cacheFile, JSON.stringify(cache, null, 2));
|
|
11843
11815
|
}
|
|
11844
11816
|
// ============================================================================
|
|
11845
11817
|
// Event Listening
|
|
@@ -12037,10 +12009,10 @@ var X402PaymentManager = class {
|
|
|
12037
12009
|
*/
|
|
12038
12010
|
getTreasuryAddress(network) {
|
|
12039
12011
|
const treasuries = {
|
|
12040
|
-
"base-sepolia": "
|
|
12041
|
-
"ethereum-sepolia": "
|
|
12042
|
-
"optimism-sepolia": "
|
|
12043
|
-
"linea-sepolia": "
|
|
12012
|
+
"base-sepolia": "0x20E7B2A2c8969725b88Dd3EF3a11Bc3353C83F70",
|
|
12013
|
+
"ethereum-sepolia": "0x20E7B2A2c8969725b88Dd3EF3a11Bc3353C83F70",
|
|
12014
|
+
"optimism-sepolia": "0x20E7B2A2c8969725b88Dd3EF3a11Bc3353C83F70",
|
|
12015
|
+
"linea-sepolia": "0x20E7B2A2c8969725b88Dd3EF3a11Bc3353C83F70"
|
|
12044
12016
|
};
|
|
12045
12017
|
return treasuries[network] || treasuries["base-sepolia"];
|
|
12046
12018
|
}
|
|
@@ -12068,7 +12040,7 @@ var X402PaymentManager = class {
|
|
|
12068
12040
|
* Returns 32-byte hex string (0x-prefixed)
|
|
12069
12041
|
*/
|
|
12070
12042
|
generateNonce() {
|
|
12071
|
-
return ethers.
|
|
12043
|
+
return ethers.hexlify(ethers.randomBytes(32));
|
|
12072
12044
|
}
|
|
12073
12045
|
/**
|
|
12074
12046
|
* Sign EIP-3009 Transfer Authorization
|
|
@@ -12281,8 +12253,8 @@ var X402PaymentManager = class {
|
|
|
12281
12253
|
* Execute native token (ETH) payment
|
|
12282
12254
|
*/
|
|
12283
12255
|
async executeNativePayment(recipientAddress, amount, protocolFee) {
|
|
12284
|
-
const amountWei = ethers.
|
|
12285
|
-
const feeWei = ethers.
|
|
12256
|
+
const amountWei = ethers.parseEther(amount.toString());
|
|
12257
|
+
const feeWei = ethers.parseEther(protocolFee.toString());
|
|
12286
12258
|
const mainTx = await this.wallet.sendTransaction({
|
|
12287
12259
|
to: recipientAddress,
|
|
12288
12260
|
value: amountWei
|
|
@@ -12321,8 +12293,8 @@ var X402PaymentManager = class {
|
|
|
12321
12293
|
if (!usdcAddress) {
|
|
12322
12294
|
throw new PaymentError(`USDC not supported on ${this.network}`);
|
|
12323
12295
|
}
|
|
12324
|
-
const totalAmountWei = ethers.
|
|
12325
|
-
const feeWei = ethers.
|
|
12296
|
+
const totalAmountWei = ethers.parseUnits(amount.toString(), 6);
|
|
12297
|
+
const feeWei = ethers.parseUnits(protocolFee.toString(), 6);
|
|
12326
12298
|
console.log(`\u{1F4B3} Preparing EIP-3009 payment authorization...`);
|
|
12327
12299
|
console.log(` Total: ${amount} USDC`);
|
|
12328
12300
|
console.log(` Fee: ${protocolFee} USDC`);
|
|
@@ -12417,7 +12389,7 @@ var X402PaymentManager = class {
|
|
|
12417
12389
|
scheme: "exact",
|
|
12418
12390
|
// x402 scheme for exact payment amount
|
|
12419
12391
|
network: this.network,
|
|
12420
|
-
maxAmountRequired: ethers.
|
|
12392
|
+
maxAmountRequired: ethers.parseUnits(amount.toString(), currency === "USDC" ? 6 : 18).toString(),
|
|
12421
12393
|
resource,
|
|
12422
12394
|
description: serviceDescription,
|
|
12423
12395
|
mimeType: "application/json",
|
|
@@ -12465,7 +12437,7 @@ var X402PaymentManager = class {
|
|
|
12465
12437
|
status: paymentProof.status
|
|
12466
12438
|
};
|
|
12467
12439
|
const receiptJson = JSON.stringify(receiptData);
|
|
12468
|
-
const receiptHash =
|
|
12440
|
+
const receiptHash = crypto2.createHash("sha256").update(receiptJson).digest("hex");
|
|
12469
12441
|
return {
|
|
12470
12442
|
receipt_type: "x402_payment",
|
|
12471
12443
|
receipt_hash: receiptHash,
|
|
@@ -12509,7 +12481,7 @@ var PaymentManager = class {
|
|
|
12509
12481
|
this.wallet = wallet;
|
|
12510
12482
|
this.credentials = credentials;
|
|
12511
12483
|
if (credentials.stripe_secret_key) {
|
|
12512
|
-
this.stripeAxiosInstance =
|
|
12484
|
+
this.stripeAxiosInstance = axios2.create({
|
|
12513
12485
|
baseURL: "https://api.stripe.com/v1",
|
|
12514
12486
|
headers: {
|
|
12515
12487
|
Authorization: `Bearer ${credentials.stripe_secret_key}`,
|
|
@@ -12531,7 +12503,7 @@ var PaymentManager = class {
|
|
|
12531
12503
|
const auth = Buffer.from(
|
|
12532
12504
|
`${this.credentials.paypal_client_id}:${this.credentials.paypal_client_secret}`
|
|
12533
12505
|
).toString("base64");
|
|
12534
|
-
const response = await
|
|
12506
|
+
const response = await axios2.post(
|
|
12535
12507
|
"https://api-m.sandbox.paypal.com/v1/oauth2/token",
|
|
12536
12508
|
"grant_type=client_credentials",
|
|
12537
12509
|
{
|
|
@@ -12798,7 +12770,7 @@ var X402Server = class {
|
|
|
12798
12770
|
console.warn("\u26A0\uFE0F Server already running");
|
|
12799
12771
|
return;
|
|
12800
12772
|
}
|
|
12801
|
-
this.server =
|
|
12773
|
+
this.server = http.createServer((req, res) => {
|
|
12802
12774
|
this.handleRequest(req, res).catch((error) => {
|
|
12803
12775
|
console.error("\u274C Request handler error:", error);
|
|
12804
12776
|
res.writeHead(500, { "Content-Type": "application/json" });
|
|
@@ -13001,17 +12973,17 @@ var GoogleAP2Integration = class {
|
|
|
13001
12973
|
* Generate or load RSA keypair for production JWT signing
|
|
13002
12974
|
*/
|
|
13003
12975
|
getOrGenerateRsaKeypair() {
|
|
13004
|
-
const keyDir =
|
|
13005
|
-
const privateKeyPath =
|
|
13006
|
-
const publicKeyPath =
|
|
13007
|
-
if (!
|
|
13008
|
-
|
|
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 });
|
|
13009
12981
|
}
|
|
13010
|
-
if (
|
|
12982
|
+
if (fs3.existsSync(privateKeyPath) && fs3.existsSync(publicKeyPath)) {
|
|
13011
12983
|
try {
|
|
13012
|
-
const privateKeyPem =
|
|
13013
|
-
const publicKeyPem =
|
|
13014
|
-
const privateKey2 =
|
|
12984
|
+
const privateKeyPem = fs3.readFileSync(privateKeyPath, "utf-8");
|
|
12985
|
+
const publicKeyPem = fs3.readFileSync(publicKeyPath, "utf-8");
|
|
12986
|
+
const privateKey2 = crypto2.createPrivateKey(privateKeyPem);
|
|
13015
12987
|
console.log(`\u{1F511} Loaded existing RSA keypair for ${this.agentName}`);
|
|
13016
12988
|
return { privateKey: privateKey2, publicKey: publicKeyPem };
|
|
13017
12989
|
} catch (e) {
|
|
@@ -13019,7 +12991,7 @@ var GoogleAP2Integration = class {
|
|
|
13019
12991
|
}
|
|
13020
12992
|
}
|
|
13021
12993
|
console.log(`\u{1F511} Generating new RSA keypair for ${this.agentName}`);
|
|
13022
|
-
const { privateKey, publicKey } =
|
|
12994
|
+
const { privateKey, publicKey } = crypto2.generateKeyPairSync("rsa", {
|
|
13023
12995
|
modulusLength: 2048,
|
|
13024
12996
|
publicKeyEncoding: {
|
|
13025
12997
|
type: "spki",
|
|
@@ -13031,14 +13003,14 @@ var GoogleAP2Integration = class {
|
|
|
13031
13003
|
}
|
|
13032
13004
|
});
|
|
13033
13005
|
try {
|
|
13034
|
-
|
|
13035
|
-
|
|
13006
|
+
fs3.writeFileSync(privateKeyPath, privateKey);
|
|
13007
|
+
fs3.writeFileSync(publicKeyPath, publicKey);
|
|
13036
13008
|
console.log(`\u{1F4BE} RSA keypair saved to ${keyDir}`);
|
|
13037
13009
|
} catch (e) {
|
|
13038
13010
|
console.warn(`\u26A0\uFE0F Failed to save keys: ${e}`);
|
|
13039
13011
|
}
|
|
13040
13012
|
return {
|
|
13041
|
-
privateKey:
|
|
13013
|
+
privateKey: crypto2.createPrivateKey(privateKey),
|
|
13042
13014
|
publicKey
|
|
13043
13015
|
};
|
|
13044
13016
|
}
|
|
@@ -13147,7 +13119,7 @@ var GoogleAP2Integration = class {
|
|
|
13147
13119
|
*/
|
|
13148
13120
|
async createMerchantJwt(cartContents) {
|
|
13149
13121
|
const cartJson = JSON.stringify(cartContents);
|
|
13150
|
-
const cartHash =
|
|
13122
|
+
const cartHash = crypto2.createHash("sha256").update(cartJson).digest("hex");
|
|
13151
13123
|
const now = Math.floor(Date.now() / 1e3);
|
|
13152
13124
|
const payload = {
|
|
13153
13125
|
iss: `did:chaoschain:${this.agentName}`,
|
|
@@ -13166,7 +13138,7 @@ var GoogleAP2Integration = class {
|
|
|
13166
13138
|
// Cart integrity hash
|
|
13167
13139
|
merchant_name: cartContents.merchant_name
|
|
13168
13140
|
};
|
|
13169
|
-
const jwt = await new
|
|
13141
|
+
const jwt = await new jose.SignJWT(payload).setProtectedHeader({
|
|
13170
13142
|
alg: "RS256",
|
|
13171
13143
|
kid: `did:chaoschain:${this.agentName}#key-1`
|
|
13172
13144
|
}).sign(this.privateKey);
|
|
@@ -13177,8 +13149,8 @@ var GoogleAP2Integration = class {
|
|
|
13177
13149
|
*/
|
|
13178
13150
|
async verifyJwtToken(token) {
|
|
13179
13151
|
try {
|
|
13180
|
-
const publicKey =
|
|
13181
|
-
const { payload } = await
|
|
13152
|
+
const publicKey = crypto2.createPublicKey(this.publicKey);
|
|
13153
|
+
const { payload } = await jose.jwtVerify(token, publicKey, {
|
|
13182
13154
|
algorithms: ["RS256"],
|
|
13183
13155
|
audience: "chaoschain:payment_processor"
|
|
13184
13156
|
});
|
|
@@ -13432,7 +13404,7 @@ var A2AX402Extension = class {
|
|
|
13432
13404
|
agent_payee: this.agentName
|
|
13433
13405
|
};
|
|
13434
13406
|
const proofJson = JSON.stringify(proofData);
|
|
13435
|
-
const proofHash =
|
|
13407
|
+
const proofHash = crypto2.createHash("sha256").update(proofJson).digest("hex");
|
|
13436
13408
|
return {
|
|
13437
13409
|
proof_type: "a2a_x402_payment",
|
|
13438
13410
|
proof_hash: proofHash,
|
|
@@ -13570,10 +13542,10 @@ var ProcessIntegrity = class {
|
|
|
13570
13542
|
generateCodeHash(func) {
|
|
13571
13543
|
try {
|
|
13572
13544
|
const sourceCode = func.toString();
|
|
13573
|
-
return
|
|
13545
|
+
return createHash("sha256").update(sourceCode).digest("hex");
|
|
13574
13546
|
} catch {
|
|
13575
13547
|
const funcInfo = `${func.name}`;
|
|
13576
|
-
return
|
|
13548
|
+
return createHash("sha256").update(funcInfo).digest("hex");
|
|
13577
13549
|
}
|
|
13578
13550
|
}
|
|
13579
13551
|
/**
|
|
@@ -13649,7 +13621,7 @@ var ProcessIntegrity = class {
|
|
|
13649
13621
|
execution_time: executionTime.toISOString(),
|
|
13650
13622
|
agent_name: this.agentName
|
|
13651
13623
|
};
|
|
13652
|
-
const executionHash =
|
|
13624
|
+
const executionHash = createHash("sha256").update(JSON.stringify(executionData)).digest("hex");
|
|
13653
13625
|
const proof = {
|
|
13654
13626
|
proofId,
|
|
13655
13627
|
functionName,
|
|
@@ -13773,7 +13745,7 @@ var LocalIPFSStorage = class {
|
|
|
13773
13745
|
const buffer = typeof data === "string" ? Buffer.from(data) : data;
|
|
13774
13746
|
const form = new import_form_data.default();
|
|
13775
13747
|
form.append("file", buffer, { contentType: mime });
|
|
13776
|
-
const response = await
|
|
13748
|
+
const response = await axios2.post(`${this.apiUrl}/api/v0/add`, form, {
|
|
13777
13749
|
headers: form.getHeaders(),
|
|
13778
13750
|
maxBodyLength: Infinity
|
|
13779
13751
|
});
|
|
@@ -13796,7 +13768,7 @@ var LocalIPFSStorage = class {
|
|
|
13796
13768
|
}
|
|
13797
13769
|
async get(cid) {
|
|
13798
13770
|
try {
|
|
13799
|
-
const response = await
|
|
13771
|
+
const response = await axios2.post(`${this.apiUrl}/api/v0/cat`, null, {
|
|
13800
13772
|
params: { arg: cid },
|
|
13801
13773
|
responseType: "arraybuffer"
|
|
13802
13774
|
});
|
|
@@ -13807,7 +13779,7 @@ var LocalIPFSStorage = class {
|
|
|
13807
13779
|
}
|
|
13808
13780
|
async pin(cid) {
|
|
13809
13781
|
try {
|
|
13810
|
-
await
|
|
13782
|
+
await axios2.post(`${this.apiUrl}/api/v0/pin/add`, null, {
|
|
13811
13783
|
params: { arg: cid }
|
|
13812
13784
|
});
|
|
13813
13785
|
console.log(`\u{1F4CC} Pinned to local IPFS: ${cid}`);
|
|
@@ -13817,7 +13789,7 @@ var LocalIPFSStorage = class {
|
|
|
13817
13789
|
}
|
|
13818
13790
|
async unpin(cid) {
|
|
13819
13791
|
try {
|
|
13820
|
-
await
|
|
13792
|
+
await axios2.post(`${this.apiUrl}/api/v0/pin/rm`, null, {
|
|
13821
13793
|
params: { arg: cid }
|
|
13822
13794
|
});
|
|
13823
13795
|
console.log(`\u{1F4CC} Unpinned from local IPFS: ${cid}`);
|
|
@@ -13842,7 +13814,7 @@ var PinataStorage = class {
|
|
|
13842
13814
|
contentType: mime,
|
|
13843
13815
|
filename: `file_${Date.now()}`
|
|
13844
13816
|
});
|
|
13845
|
-
const response = await
|
|
13817
|
+
const response = await axios2.post("https://api.pinata.cloud/pinning/pinFileToIPFS", form, {
|
|
13846
13818
|
headers: {
|
|
13847
13819
|
...form.getHeaders(),
|
|
13848
13820
|
Authorization: `Bearer ${this.jwtToken}`
|
|
@@ -13863,7 +13835,7 @@ var PinataStorage = class {
|
|
|
13863
13835
|
}
|
|
13864
13836
|
async get(cid) {
|
|
13865
13837
|
try {
|
|
13866
|
-
const response = await
|
|
13838
|
+
const response = await axios2.get(`${this.gatewayUrl}/ipfs/${cid}`, {
|
|
13867
13839
|
responseType: "arraybuffer"
|
|
13868
13840
|
});
|
|
13869
13841
|
return Buffer.from(response.data);
|
|
@@ -13873,7 +13845,7 @@ var PinataStorage = class {
|
|
|
13873
13845
|
}
|
|
13874
13846
|
async pin(cid) {
|
|
13875
13847
|
try {
|
|
13876
|
-
await
|
|
13848
|
+
await axios2.post(
|
|
13877
13849
|
"https://api.pinata.cloud/pinning/pinByHash",
|
|
13878
13850
|
{ hashToPin: cid },
|
|
13879
13851
|
{
|
|
@@ -13890,7 +13862,7 @@ var PinataStorage = class {
|
|
|
13890
13862
|
}
|
|
13891
13863
|
async unpin(cid) {
|
|
13892
13864
|
try {
|
|
13893
|
-
await
|
|
13865
|
+
await axios2.delete(`https://api.pinata.cloud/pinning/unpin/${cid}`, {
|
|
13894
13866
|
headers: {
|
|
13895
13867
|
Authorization: `Bearer ${this.jwtToken}`
|
|
13896
13868
|
}
|
|
@@ -13926,7 +13898,7 @@ var IrysStorage = class {
|
|
|
13926
13898
|
}
|
|
13927
13899
|
async get(cid) {
|
|
13928
13900
|
try {
|
|
13929
|
-
const response = await
|
|
13901
|
+
const response = await axios2.get(`https://arweave.net/${cid}`, {
|
|
13930
13902
|
responseType: "arraybuffer"
|
|
13931
13903
|
});
|
|
13932
13904
|
return Buffer.from(response.data);
|
|
@@ -14583,7 +14555,21 @@ var GatewayClient = class {
|
|
|
14583
14555
|
auth;
|
|
14584
14556
|
retryConfig;
|
|
14585
14557
|
constructor(config) {
|
|
14586
|
-
|
|
14558
|
+
const rawBaseUrl = config.baseUrl ?? config.gatewayUrl ?? "https://gateway.chaoscha.in";
|
|
14559
|
+
let parsed;
|
|
14560
|
+
try {
|
|
14561
|
+
parsed = new URL(rawBaseUrl);
|
|
14562
|
+
} catch {
|
|
14563
|
+
throw new Error(
|
|
14564
|
+
`Invalid gateway baseUrl "${rawBaseUrl}". Provide a valid absolute URL, e.g. https://gateway.chaoscha.in`
|
|
14565
|
+
);
|
|
14566
|
+
}
|
|
14567
|
+
if (!["http:", "https:"].includes(parsed.protocol)) {
|
|
14568
|
+
throw new Error(
|
|
14569
|
+
`Invalid gateway baseUrl protocol "${parsed.protocol}". Only http/https are supported.`
|
|
14570
|
+
);
|
|
14571
|
+
}
|
|
14572
|
+
this.gatewayUrl = parsed.toString().replace(/\/$/, "");
|
|
14587
14573
|
this.timeout = this._resolveTimeout(
|
|
14588
14574
|
config.timeoutMs,
|
|
14589
14575
|
config.timeoutSeconds,
|
|
@@ -14724,7 +14710,7 @@ var GatewayClient = class {
|
|
|
14724
14710
|
let attempt = 0;
|
|
14725
14711
|
while (true) {
|
|
14726
14712
|
try {
|
|
14727
|
-
const response = await
|
|
14713
|
+
const response = await axios2({
|
|
14728
14714
|
method,
|
|
14729
14715
|
url,
|
|
14730
14716
|
data,
|
|
@@ -15008,6 +14994,68 @@ var GatewayClient = class {
|
|
|
15008
14994
|
const workflow = await this.closeEpoch(studioAddress, epoch, signerAddress);
|
|
15009
14995
|
return this.waitForCompletion(workflow.workflowId, options);
|
|
15010
14996
|
}
|
|
14997
|
+
// ===========================================================================
|
|
14998
|
+
// Read API — Studio Work Discovery
|
|
14999
|
+
// ===========================================================================
|
|
15000
|
+
/**
|
|
15001
|
+
* Fetch pending (unfinalized) work for a studio from the gateway.
|
|
15002
|
+
*
|
|
15003
|
+
* @param studioAddress - 0x-prefixed studio contract address
|
|
15004
|
+
* @param options - Optional limit/offset for pagination
|
|
15005
|
+
* @returns Typed pending work response
|
|
15006
|
+
*/
|
|
15007
|
+
async getPendingWork(studioAddress, options) {
|
|
15008
|
+
const limit = options?.limit ?? 20;
|
|
15009
|
+
const offset = options?.offset ?? 0;
|
|
15010
|
+
const url = `${this.gatewayUrl}/v1/studio/${studioAddress}/work?status=pending&limit=${limit}&offset=${offset}`;
|
|
15011
|
+
try {
|
|
15012
|
+
const response = await axios2.get(url, {
|
|
15013
|
+
timeout: this.timeout,
|
|
15014
|
+
headers: this._buildHeaders()
|
|
15015
|
+
});
|
|
15016
|
+
return response.data;
|
|
15017
|
+
} catch (error) {
|
|
15018
|
+
const axiosErr = error;
|
|
15019
|
+
if (axiosErr.code === "ECONNREFUSED" || axiosErr.code === "ENOTFOUND" || !axiosErr.response) {
|
|
15020
|
+
throw new GatewayConnectionError(
|
|
15021
|
+
`ChaosChain gateway unreachable at ${this.gatewayUrl}. Check GATEWAY_URL.`
|
|
15022
|
+
);
|
|
15023
|
+
}
|
|
15024
|
+
if (axiosErr.response) {
|
|
15025
|
+
throw new GatewayError(
|
|
15026
|
+
`Gateway returned ${axiosErr.response.status}: ${JSON.stringify(axiosErr.response.data)}`
|
|
15027
|
+
);
|
|
15028
|
+
}
|
|
15029
|
+
throw error;
|
|
15030
|
+
}
|
|
15031
|
+
}
|
|
15032
|
+
/**
|
|
15033
|
+
* Fetch full evidence graph for a work submission.
|
|
15034
|
+
* Endpoint: GET /v1/work/{hash}/evidence
|
|
15035
|
+
*/
|
|
15036
|
+
async getWorkEvidence(workHash) {
|
|
15037
|
+
const url = `${this.gatewayUrl}/v1/work/${workHash}/evidence`;
|
|
15038
|
+
try {
|
|
15039
|
+
const response = await axios2.get(url, {
|
|
15040
|
+
timeout: this.timeout,
|
|
15041
|
+
headers: this._buildHeaders()
|
|
15042
|
+
});
|
|
15043
|
+
return response.data;
|
|
15044
|
+
} catch (error) {
|
|
15045
|
+
const axiosErr = error;
|
|
15046
|
+
if (axiosErr.code === "ECONNREFUSED" || axiosErr.code === "ENOTFOUND" || !axiosErr.response) {
|
|
15047
|
+
throw new GatewayConnectionError(
|
|
15048
|
+
`ChaosChain gateway unreachable at ${this.gatewayUrl}. Check GATEWAY_URL.`
|
|
15049
|
+
);
|
|
15050
|
+
}
|
|
15051
|
+
if (axiosErr.response) {
|
|
15052
|
+
throw new GatewayError(
|
|
15053
|
+
`Gateway returned ${axiosErr.response.status}: ${JSON.stringify(axiosErr.response.data)}`
|
|
15054
|
+
);
|
|
15055
|
+
}
|
|
15056
|
+
throw error;
|
|
15057
|
+
}
|
|
15058
|
+
}
|
|
15011
15059
|
};
|
|
15012
15060
|
var StudioClient = class {
|
|
15013
15061
|
provider;
|
|
@@ -15034,7 +15082,7 @@ var StudioClient = class {
|
|
|
15034
15082
|
if (!chaosCoreAddress) {
|
|
15035
15083
|
throw new ContractError(`ChaosCore contract address not found for network: ${this.network}.`);
|
|
15036
15084
|
}
|
|
15037
|
-
const chaosCore = new ethers.
|
|
15085
|
+
const chaosCore = new ethers.Contract(chaosCoreAddress, CHAOS_CORE_ABI, this.signer);
|
|
15038
15086
|
const tx = await chaosCore.createStudio(name, logicModuleAddress);
|
|
15039
15087
|
const receipt = await tx.wait();
|
|
15040
15088
|
const event = receipt.logs.find((log) => {
|
|
@@ -15068,11 +15116,11 @@ var StudioClient = class {
|
|
|
15068
15116
|
* @param stakeAmount - Amount to stake in wei (default: 0.0001 ETH)
|
|
15069
15117
|
*/
|
|
15070
15118
|
async registerWithStudio(studioAddress, agentId, role, stakeAmount) {
|
|
15071
|
-
const stake = stakeAmount ?? ethers.
|
|
15119
|
+
const stake = stakeAmount ?? ethers.parseEther("0.0001");
|
|
15072
15120
|
if (stake === 0n) {
|
|
15073
15121
|
throw new ContractError("Stake amount must be > 0 (contract requirement)");
|
|
15074
15122
|
}
|
|
15075
|
-
const studio = new ethers.
|
|
15123
|
+
const studio = new ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.signer);
|
|
15076
15124
|
const tx = await studio.registerAgent(agentId, role, {
|
|
15077
15125
|
value: stake
|
|
15078
15126
|
});
|
|
@@ -15095,7 +15143,7 @@ var StudioClient = class {
|
|
|
15095
15143
|
*/
|
|
15096
15144
|
async submitWork(studioAddress, dataHash, threadRoot, evidenceRoot, feedbackAuth = "0x") {
|
|
15097
15145
|
console.warn("submitWork() is deprecated. Use Gateway for production.");
|
|
15098
|
-
const studio = new ethers.
|
|
15146
|
+
const studio = new ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.signer);
|
|
15099
15147
|
const tx = await studio.submitWork(dataHash, threadRoot, evidenceRoot, feedbackAuth);
|
|
15100
15148
|
const receipt = await tx.wait();
|
|
15101
15149
|
return receipt.hash;
|
|
@@ -15124,7 +15172,7 @@ var StudioClient = class {
|
|
|
15124
15172
|
`Participants (${participants.length}) and weights (${contributionWeights.length}) must have same length`
|
|
15125
15173
|
);
|
|
15126
15174
|
}
|
|
15127
|
-
const studio = new ethers.
|
|
15175
|
+
const studio = new ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.signer);
|
|
15128
15176
|
const tx = await studio.submitWorkMultiAgent(
|
|
15129
15177
|
dataHash,
|
|
15130
15178
|
threadRoot,
|
|
@@ -15151,7 +15199,7 @@ var StudioClient = class {
|
|
|
15151
15199
|
* @returns Transaction hash
|
|
15152
15200
|
*/
|
|
15153
15201
|
async commitScore(studioAddress, dataHash, commitment) {
|
|
15154
|
-
const studio = new ethers.
|
|
15202
|
+
const studio = new ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.signer);
|
|
15155
15203
|
const tx = await studio.commitScore(dataHash, commitment);
|
|
15156
15204
|
const receipt = await tx.wait();
|
|
15157
15205
|
return receipt.hash;
|
|
@@ -15169,7 +15217,7 @@ var StudioClient = class {
|
|
|
15169
15217
|
* @returns Transaction hash
|
|
15170
15218
|
*/
|
|
15171
15219
|
async revealScore(studioAddress, dataHash, scoreVector, salt) {
|
|
15172
|
-
const studio = new ethers.
|
|
15220
|
+
const studio = new ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.signer);
|
|
15173
15221
|
const tx = await studio.revealScore(dataHash, scoreVector, salt);
|
|
15174
15222
|
const receipt = await tx.wait();
|
|
15175
15223
|
return receipt.hash;
|
|
@@ -15191,7 +15239,7 @@ var StudioClient = class {
|
|
|
15191
15239
|
* @returns Transaction hash
|
|
15192
15240
|
*/
|
|
15193
15241
|
async submitScoreVector(studioAddress, dataHash, scores) {
|
|
15194
|
-
const studio = new ethers.
|
|
15242
|
+
const studio = new ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.signer);
|
|
15195
15243
|
const scoreVector = this.encodeScoreVector(scores);
|
|
15196
15244
|
const tx = await studio.submitScoreVector(dataHash, scoreVector);
|
|
15197
15245
|
const receipt = await tx.wait();
|
|
@@ -15220,7 +15268,7 @@ var StudioClient = class {
|
|
|
15220
15268
|
* @returns Transaction hash
|
|
15221
15269
|
*/
|
|
15222
15270
|
async submitScoreVectorForWorker(studioAddress, dataHash, workerAddress, scores) {
|
|
15223
|
-
const studio = new ethers.
|
|
15271
|
+
const studio = new ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.signer);
|
|
15224
15272
|
const scoreVector = this.encodeScoreVector(scores);
|
|
15225
15273
|
const tx = await studio.submitScoreVectorForWorker(dataHash, workerAddress, scoreVector);
|
|
15226
15274
|
const receipt = await tx.wait();
|
|
@@ -15247,7 +15295,7 @@ var StudioClient = class {
|
|
|
15247
15295
|
`RewardsDistributor contract address not found for network: ${this.network}.`
|
|
15248
15296
|
);
|
|
15249
15297
|
}
|
|
15250
|
-
const distributor = new ethers.
|
|
15298
|
+
const distributor = new ethers.Contract(
|
|
15251
15299
|
rewardsDistributorAddress,
|
|
15252
15300
|
REWARDS_DISTRIBUTOR_ABI,
|
|
15253
15301
|
this.signer
|
|
@@ -15267,7 +15315,7 @@ var StudioClient = class {
|
|
|
15267
15315
|
* @returns Pending reward amount in wei
|
|
15268
15316
|
*/
|
|
15269
15317
|
async getPendingRewards(studioAddress, account) {
|
|
15270
|
-
const studio = new ethers.
|
|
15318
|
+
const studio = new ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.provider);
|
|
15271
15319
|
return studio.getWithdrawableBalance(account);
|
|
15272
15320
|
}
|
|
15273
15321
|
/**
|
|
@@ -15277,7 +15325,7 @@ var StudioClient = class {
|
|
|
15277
15325
|
* @returns Transaction hash
|
|
15278
15326
|
*/
|
|
15279
15327
|
async withdrawRewards(studioAddress) {
|
|
15280
|
-
const studio = new ethers.
|
|
15328
|
+
const studio = new ethers.Contract(studioAddress, STUDIO_PROXY_ABI, this.signer);
|
|
15281
15329
|
const tx = await studio.withdrawRewards();
|
|
15282
15330
|
const receipt = await tx.wait();
|
|
15283
15331
|
return receipt.hash;
|
|
@@ -15294,9 +15342,9 @@ var StudioClient = class {
|
|
|
15294
15342
|
* @returns bytes32 commitment hash
|
|
15295
15343
|
*/
|
|
15296
15344
|
computeScoreCommitment(scores, salt, dataHash) {
|
|
15297
|
-
const abiCoder = new ethers.
|
|
15345
|
+
const abiCoder = new ethers.AbiCoder();
|
|
15298
15346
|
const encoded = abiCoder.encode(["uint8[]", "bytes32", "bytes32"], [scores, salt, dataHash]);
|
|
15299
|
-
return ethers.
|
|
15347
|
+
return ethers.keccak256(encoded);
|
|
15300
15348
|
}
|
|
15301
15349
|
/**
|
|
15302
15350
|
* Encode score vector for revealScore.
|
|
@@ -15305,7 +15353,7 @@ var StudioClient = class {
|
|
|
15305
15353
|
* @returns ABI-encoded bytes
|
|
15306
15354
|
*/
|
|
15307
15355
|
encodeScoreVector(scores) {
|
|
15308
|
-
const abiCoder = new ethers.
|
|
15356
|
+
const abiCoder = new ethers.AbiCoder();
|
|
15309
15357
|
return abiCoder.encode(["uint8[]"], [scores]);
|
|
15310
15358
|
}
|
|
15311
15359
|
/**
|
|
@@ -15314,13 +15362,12 @@ var StudioClient = class {
|
|
|
15314
15362
|
* @returns bytes32 random salt
|
|
15315
15363
|
*/
|
|
15316
15364
|
generateSalt() {
|
|
15317
|
-
return ethers.
|
|
15365
|
+
return ethers.hexlify(ethers.randomBytes(32));
|
|
15318
15366
|
}
|
|
15319
15367
|
};
|
|
15320
15368
|
|
|
15321
15369
|
// src/ChaosChainSDK.ts
|
|
15322
15370
|
var ChaosChainSDK = class _ChaosChainSDK {
|
|
15323
|
-
static warnedGatewayMissing = false;
|
|
15324
15371
|
static warnedStudioClientProduction = false;
|
|
15325
15372
|
// Core components
|
|
15326
15373
|
walletManager;
|
|
@@ -15399,7 +15446,7 @@ var ChaosChainSDK = class _ChaosChainSDK {
|
|
|
15399
15446
|
);
|
|
15400
15447
|
}
|
|
15401
15448
|
try {
|
|
15402
|
-
this.provider = new ethers.
|
|
15449
|
+
this.provider = new ethers.JsonRpcProvider(rpcUrl);
|
|
15403
15450
|
} catch (error) {
|
|
15404
15451
|
throw new ConfigurationError(
|
|
15405
15452
|
`Failed to initialize provider for network "${String(config.network)}".`,
|
|
@@ -15498,23 +15545,16 @@ var ChaosChainSDK = class _ChaosChainSDK {
|
|
|
15498
15545
|
this.computeProvider
|
|
15499
15546
|
);
|
|
15500
15547
|
}
|
|
15501
|
-
|
|
15502
|
-
|
|
15503
|
-
|
|
15504
|
-
|
|
15505
|
-
}
|
|
15548
|
+
const gatewayConfig = config.gatewayConfig ?? (config.gatewayUrl ? { gatewayUrl: config.gatewayUrl } : {});
|
|
15549
|
+
this.gateway = new GatewayClient(gatewayConfig);
|
|
15550
|
+
const gatewayBaseUrl = gatewayConfig.baseUrl ?? gatewayConfig.gatewayUrl ?? "https://gateway.chaoscha.in";
|
|
15551
|
+
console.log(`\u{1F310} Gateway client initialized: ${gatewayBaseUrl}`);
|
|
15506
15552
|
this.studio = new StudioClient({
|
|
15507
15553
|
provider: this.provider,
|
|
15508
15554
|
signer: this.walletManager.getWallet(),
|
|
15509
15555
|
network: typeof config.network === "string" ? config.network : config.network
|
|
15510
15556
|
});
|
|
15511
15557
|
const isLocalNetwork = String(config.network) === "local" /* LOCAL */ || String(config.network) === "local";
|
|
15512
|
-
if (!this.gateway && !isLocalNetwork && !_ChaosChainSDK.warnedGatewayMissing) {
|
|
15513
|
-
console.warn(
|
|
15514
|
-
"\u26A0\uFE0F Gateway is not configured. For production workflows, use gatewayConfig to enable Gateway orchestration."
|
|
15515
|
-
);
|
|
15516
|
-
_ChaosChainSDK.warnedGatewayMissing = true;
|
|
15517
|
-
}
|
|
15518
15558
|
if (process.env.NODE_ENV === "production" && !isLocalNetwork && !_ChaosChainSDK.warnedStudioClientProduction) {
|
|
15519
15559
|
console.warn(
|
|
15520
15560
|
"\u26A0\uFE0F StudioClient is intended for low-level or testing use. In production, prefer Gateway workflows."
|
|
@@ -15617,19 +15657,19 @@ var ChaosChainSDK = class _ChaosChainSDK {
|
|
|
15617
15657
|
* Get agent reputation score (ERC-8004 v1.0)
|
|
15618
15658
|
*/
|
|
15619
15659
|
async getReputationScore(agentId) {
|
|
15620
|
-
const summary = await this.chaosAgent.getSummary(agentId, [], ethers.
|
|
15660
|
+
const summary = await this.chaosAgent.getSummary(agentId, [], ethers.ZeroHash, ethers.ZeroHash);
|
|
15621
15661
|
return summary.averageScore;
|
|
15622
15662
|
}
|
|
15623
15663
|
/**
|
|
15624
15664
|
* Read all feedback for an agent
|
|
15625
15665
|
*/
|
|
15626
|
-
async readAllFeedback(agentId, clientAddresses = [], tag1 = ethers.
|
|
15666
|
+
async readAllFeedback(agentId, clientAddresses = [], tag1 = ethers.ZeroHash, tag2 = ethers.ZeroHash, includeRevoked = false) {
|
|
15627
15667
|
return this.chaosAgent.readAllFeedback(agentId, clientAddresses, tag1, tag2, includeRevoked);
|
|
15628
15668
|
}
|
|
15629
15669
|
/**
|
|
15630
15670
|
* Get feedback summary statistics
|
|
15631
15671
|
*/
|
|
15632
|
-
async getFeedbackSummary(agentId, clientAddresses = [], tag1 = ethers.
|
|
15672
|
+
async getFeedbackSummary(agentId, clientAddresses = [], tag1 = ethers.ZeroHash, tag2 = ethers.ZeroHash) {
|
|
15633
15673
|
return this.chaosAgent.getSummary(agentId, clientAddresses, tag1, tag2);
|
|
15634
15674
|
}
|
|
15635
15675
|
/**
|
|
@@ -15668,7 +15708,7 @@ var ChaosChainSDK = class _ChaosChainSDK {
|
|
|
15668
15708
|
/**
|
|
15669
15709
|
* Get validation summary for an agent
|
|
15670
15710
|
*/
|
|
15671
|
-
async getValidationSummary(agentId, validatorAddresses = [], tag = ethers.
|
|
15711
|
+
async getValidationSummary(agentId, validatorAddresses = [], tag = ethers.ZeroHash) {
|
|
15672
15712
|
return this.chaosAgent.getValidationSummary(agentId, validatorAddresses, tag);
|
|
15673
15713
|
}
|
|
15674
15714
|
/**
|
|
@@ -15755,7 +15795,7 @@ var ChaosChainSDK = class _ChaosChainSDK {
|
|
|
15755
15795
|
*/
|
|
15756
15796
|
async getETHBalance() {
|
|
15757
15797
|
const balance = await this.provider.getBalance(this.getAddress());
|
|
15758
|
-
return ethers.
|
|
15798
|
+
return ethers.formatEther(balance);
|
|
15759
15799
|
}
|
|
15760
15800
|
/**
|
|
15761
15801
|
* Get USDC balance (if USDC contract exists on network)
|
|
@@ -15939,7 +15979,7 @@ var ChaosChainSDK = class _ChaosChainSDK {
|
|
|
15939
15979
|
* Get SDK version
|
|
15940
15980
|
*/
|
|
15941
15981
|
getVersion() {
|
|
15942
|
-
return "0.
|
|
15982
|
+
return "0.2.4";
|
|
15943
15983
|
}
|
|
15944
15984
|
/**
|
|
15945
15985
|
* Get SDK capabilities summary
|
|
@@ -16118,7 +16158,7 @@ var IPFSLocalStorage = class {
|
|
|
16118
16158
|
const formData = new FormData();
|
|
16119
16159
|
const blob = new Blob([buffer], { type: options?.mime || "application/octet-stream" });
|
|
16120
16160
|
formData.append("file", blob);
|
|
16121
|
-
const response = await
|
|
16161
|
+
const response = await axios2.post(`${this.apiUrl}/api/v0/add`, formData, {
|
|
16122
16162
|
headers: {
|
|
16123
16163
|
"Content-Type": "multipart/form-data"
|
|
16124
16164
|
},
|
|
@@ -16143,7 +16183,7 @@ var IPFSLocalStorage = class {
|
|
|
16143
16183
|
*/
|
|
16144
16184
|
async download(cid) {
|
|
16145
16185
|
try {
|
|
16146
|
-
const response = await
|
|
16186
|
+
const response = await axios2.get(`${this.gatewayUrl}/ipfs/${cid}`, {
|
|
16147
16187
|
responseType: "arraybuffer"
|
|
16148
16188
|
});
|
|
16149
16189
|
return Buffer.from(response.data);
|
|
@@ -16156,7 +16196,7 @@ var IPFSLocalStorage = class {
|
|
|
16156
16196
|
*/
|
|
16157
16197
|
async pin(cid) {
|
|
16158
16198
|
try {
|
|
16159
|
-
await
|
|
16199
|
+
await axios2.post(`${this.apiUrl}/api/v0/pin/add`, null, {
|
|
16160
16200
|
params: { arg: cid }
|
|
16161
16201
|
});
|
|
16162
16202
|
} catch (error) {
|
|
@@ -16168,7 +16208,7 @@ var IPFSLocalStorage = class {
|
|
|
16168
16208
|
*/
|
|
16169
16209
|
async unpin(cid) {
|
|
16170
16210
|
try {
|
|
16171
|
-
await
|
|
16211
|
+
await axios2.post(`${this.apiUrl}/api/v0/pin/rm`, null, {
|
|
16172
16212
|
params: { arg: cid }
|
|
16173
16213
|
});
|
|
16174
16214
|
} catch (error) {
|
|
@@ -16180,7 +16220,7 @@ var IPFSLocalStorage = class {
|
|
|
16180
16220
|
*/
|
|
16181
16221
|
async isAvailable() {
|
|
16182
16222
|
try {
|
|
16183
|
-
await
|
|
16223
|
+
await axios2.post(`${this.apiUrl}/api/v0/version`);
|
|
16184
16224
|
return true;
|
|
16185
16225
|
} catch {
|
|
16186
16226
|
return false;
|
|
@@ -16191,7 +16231,7 @@ var IPFSLocalStorage = class {
|
|
|
16191
16231
|
*/
|
|
16192
16232
|
async getVersion() {
|
|
16193
16233
|
try {
|
|
16194
|
-
const response = await
|
|
16234
|
+
const response = await axios2.post(`${this.apiUrl}/api/v0/version`);
|
|
16195
16235
|
return response.data.Version;
|
|
16196
16236
|
} catch (error) {
|
|
16197
16237
|
throw new Error(`Failed to get IPFS version: ${error.message}`);
|
|
@@ -16370,8 +16410,372 @@ var StudioManager = class {
|
|
|
16370
16410
|
}
|
|
16371
16411
|
};
|
|
16372
16412
|
|
|
16413
|
+
// src/evidence.ts
|
|
16414
|
+
function rangeFit(value, min, target, max) {
|
|
16415
|
+
if (value <= min || value >= max) return 0;
|
|
16416
|
+
if (value === target) return 1;
|
|
16417
|
+
if (value < target) {
|
|
16418
|
+
return Math.max(0, Math.min(1, (value - min) / (target - min)));
|
|
16419
|
+
}
|
|
16420
|
+
return Math.max(0, Math.min(1, (max - value) / (max - target)));
|
|
16421
|
+
}
|
|
16422
|
+
function resolveScoring(policy, mandate) {
|
|
16423
|
+
if (!policy) return void 0;
|
|
16424
|
+
if (!mandate?.overrides) return policy.scoring;
|
|
16425
|
+
const base = policy.scoring;
|
|
16426
|
+
const ov = mandate.overrides;
|
|
16427
|
+
return {
|
|
16428
|
+
initiative: ov.initiative ?? base.initiative,
|
|
16429
|
+
collaboration: ov.collaboration ?? base.collaboration,
|
|
16430
|
+
reasoning: ov.reasoning ?? base.reasoning,
|
|
16431
|
+
compliance: ov.compliance ?? base.compliance,
|
|
16432
|
+
efficiency: ov.efficiency ?? base.efficiency
|
|
16433
|
+
};
|
|
16434
|
+
}
|
|
16435
|
+
function computeObserved(evidence) {
|
|
16436
|
+
const totalNodes = evidence.length;
|
|
16437
|
+
const byId = /* @__PURE__ */ new Map();
|
|
16438
|
+
const childrenOf = /* @__PURE__ */ new Map();
|
|
16439
|
+
for (const e of evidence) {
|
|
16440
|
+
byId.set(e.arweave_tx_id, e);
|
|
16441
|
+
childrenOf.set(e.arweave_tx_id, []);
|
|
16442
|
+
}
|
|
16443
|
+
let edgeCount = 0;
|
|
16444
|
+
let rootCount = 0;
|
|
16445
|
+
let artifactCount = 0;
|
|
16446
|
+
for (const e of evidence) {
|
|
16447
|
+
edgeCount += e.parent_ids.length;
|
|
16448
|
+
if (e.parent_ids.length === 0) rootCount++;
|
|
16449
|
+
if (e.artifact_ids.length > 0) artifactCount++;
|
|
16450
|
+
for (const pid of e.parent_ids) {
|
|
16451
|
+
const c = childrenOf.get(pid);
|
|
16452
|
+
if (c) c.push(e.arweave_tx_id);
|
|
16453
|
+
}
|
|
16454
|
+
}
|
|
16455
|
+
const rootOrigins = /* @__PURE__ */ new Map();
|
|
16456
|
+
function getRootOrigins(id) {
|
|
16457
|
+
if (rootOrigins.has(id)) return rootOrigins.get(id);
|
|
16458
|
+
const node = byId.get(id);
|
|
16459
|
+
if (!node || node.parent_ids.length === 0) {
|
|
16460
|
+
const s = /* @__PURE__ */ new Set([id]);
|
|
16461
|
+
rootOrigins.set(id, s);
|
|
16462
|
+
return s;
|
|
16463
|
+
}
|
|
16464
|
+
const origins = /* @__PURE__ */ new Set();
|
|
16465
|
+
for (const pid of node.parent_ids) {
|
|
16466
|
+
for (const r of getRootOrigins(pid)) origins.add(r);
|
|
16467
|
+
}
|
|
16468
|
+
rootOrigins.set(id, origins);
|
|
16469
|
+
return origins;
|
|
16470
|
+
}
|
|
16471
|
+
for (const e of evidence) getRootOrigins(e.arweave_tx_id);
|
|
16472
|
+
let integrationNodeCount = 0;
|
|
16473
|
+
for (const e of evidence) {
|
|
16474
|
+
if (e.parent_ids.length < 2) continue;
|
|
16475
|
+
const parentRootSets = e.parent_ids.filter((pid) => byId.has(pid)).map((pid) => rootOrigins.get(pid));
|
|
16476
|
+
const uniqueRoots = /* @__PURE__ */ new Set();
|
|
16477
|
+
for (const s of parentRootSets) {
|
|
16478
|
+
for (const r of s) uniqueRoots.add(r);
|
|
16479
|
+
}
|
|
16480
|
+
if (uniqueRoots.size >= 2) integrationNodeCount++;
|
|
16481
|
+
}
|
|
16482
|
+
let terminalCount = 0;
|
|
16483
|
+
for (const [, children] of childrenOf) {
|
|
16484
|
+
if (children.length === 0) terminalCount++;
|
|
16485
|
+
}
|
|
16486
|
+
const uniqueAuthors = new Set(evidence.map((e) => e.author)).size;
|
|
16487
|
+
const timestamps = evidence.map((e) => e.timestamp).filter((t) => t > 0);
|
|
16488
|
+
const durationMs = timestamps.length >= 2 ? Math.max(...timestamps) - Math.min(...timestamps) : void 0;
|
|
16489
|
+
const maxDepth = computeDepth(evidence);
|
|
16490
|
+
return {
|
|
16491
|
+
totalNodes,
|
|
16492
|
+
rootCount,
|
|
16493
|
+
edgeCount,
|
|
16494
|
+
maxDepth,
|
|
16495
|
+
artifactCount,
|
|
16496
|
+
terminalCount,
|
|
16497
|
+
integrationNodeCount,
|
|
16498
|
+
uniqueAuthors,
|
|
16499
|
+
durationMs
|
|
16500
|
+
};
|
|
16501
|
+
}
|
|
16502
|
+
function computeComplianceSignal(evidence, _observed, scoring, mandate) {
|
|
16503
|
+
const compliance = scoring.compliance;
|
|
16504
|
+
const allArtifacts = /* @__PURE__ */ new Set();
|
|
16505
|
+
for (const e of evidence) {
|
|
16506
|
+
for (const a of e.artifact_ids) allArtifacts.add(a);
|
|
16507
|
+
}
|
|
16508
|
+
const testPatterns = ["test", "spec", ".test.", ".spec.", "__test__", "__spec__"];
|
|
16509
|
+
const testsPresent = [...allArtifacts].some((a) => {
|
|
16510
|
+
const lower = a.toLowerCase();
|
|
16511
|
+
return testPatterns.some((p) => lower.includes(p));
|
|
16512
|
+
});
|
|
16513
|
+
const requiredArtifacts = [
|
|
16514
|
+
...compliance.requiredArtifacts ?? [],
|
|
16515
|
+
...mandate?.constraints?.requiredArtifacts ?? []
|
|
16516
|
+
];
|
|
16517
|
+
const present = [];
|
|
16518
|
+
const missing = [];
|
|
16519
|
+
for (const req of requiredArtifacts) {
|
|
16520
|
+
const found = [...allArtifacts].some((a) => a.toLowerCase().includes(req.toLowerCase()));
|
|
16521
|
+
if (found) present.push(req);
|
|
16522
|
+
else missing.push(req);
|
|
16523
|
+
}
|
|
16524
|
+
const forbiddenPatterns = [
|
|
16525
|
+
...compliance.forbiddenPatterns ?? [],
|
|
16526
|
+
...mandate?.constraints?.forbiddenPatterns ?? []
|
|
16527
|
+
];
|
|
16528
|
+
const violations = [];
|
|
16529
|
+
for (const pattern of forbiddenPatterns) {
|
|
16530
|
+
const lower = pattern.toLowerCase();
|
|
16531
|
+
if ([...allArtifacts].some((a) => a.toLowerCase().includes(lower))) {
|
|
16532
|
+
violations.push(`forbidden pattern found: ${pattern}`);
|
|
16533
|
+
}
|
|
16534
|
+
}
|
|
16535
|
+
if (mandate?.constraints?.mustPassTests && !testsPresent) {
|
|
16536
|
+
violations.push("mandate requires tests but none detected");
|
|
16537
|
+
}
|
|
16538
|
+
const w = compliance.weights;
|
|
16539
|
+
const totalWeight = (w.testsPresent ?? 0) + (w.requiredArtifactsPresent ?? 0) + (w.noPolicyViolations ?? 0);
|
|
16540
|
+
if (totalWeight === 0) {
|
|
16541
|
+
return { signal: testsPresent ? 1 : 0, testsPresent, violations, present, missing };
|
|
16542
|
+
}
|
|
16543
|
+
const testsScore = testsPresent ? 1 : 0;
|
|
16544
|
+
const artifactScore = requiredArtifacts.length > 0 ? present.length / requiredArtifacts.length : 1;
|
|
16545
|
+
const violationScore = violations.length === 0 ? 1 : 0;
|
|
16546
|
+
const signal = Math.max(0, Math.min(
|
|
16547
|
+
1,
|
|
16548
|
+
(w.testsPresent * testsScore + w.requiredArtifactsPresent * artifactScore + w.noPolicyViolations * violationScore) / totalWeight
|
|
16549
|
+
));
|
|
16550
|
+
return { signal, testsPresent, violations, present, missing };
|
|
16551
|
+
}
|
|
16552
|
+
function computeEfficiencySignal(observed, scoring, mandate) {
|
|
16553
|
+
const eff = scoring.efficiency;
|
|
16554
|
+
const w = eff.weights;
|
|
16555
|
+
let totalWeight = 0;
|
|
16556
|
+
let weightedSum = 0;
|
|
16557
|
+
if (eff.durationRatio && w.durationRatio && observed.durationMs !== void 0) {
|
|
16558
|
+
const latencyBudget = mandate?.constraints?.latencyBudgetMs;
|
|
16559
|
+
if (latencyBudget && latencyBudget > 0) {
|
|
16560
|
+
const ratio = observed.durationMs / latencyBudget;
|
|
16561
|
+
weightedSum += w.durationRatio * rangeFit(ratio, eff.durationRatio.min, eff.durationRatio.target, eff.durationRatio.max);
|
|
16562
|
+
totalWeight += w.durationRatio;
|
|
16563
|
+
}
|
|
16564
|
+
}
|
|
16565
|
+
if (eff.artifactCountRatio && w.artifactCountRatio && observed.totalNodes > 0) {
|
|
16566
|
+
const ratio = observed.artifactCount / observed.totalNodes;
|
|
16567
|
+
weightedSum += w.artifactCountRatio * rangeFit(ratio, eff.artifactCountRatio.min, eff.artifactCountRatio.target, eff.artifactCountRatio.max);
|
|
16568
|
+
totalWeight += w.artifactCountRatio;
|
|
16569
|
+
}
|
|
16570
|
+
if (totalWeight === 0) return void 0;
|
|
16571
|
+
return Math.max(0, Math.min(1, weightedSum / totalWeight));
|
|
16572
|
+
}
|
|
16573
|
+
function extractAgencySignals(evidence, context) {
|
|
16574
|
+
const totalNodes = evidence.length;
|
|
16575
|
+
if (totalNodes === 0) {
|
|
16576
|
+
return {
|
|
16577
|
+
initiativeSignal: 0,
|
|
16578
|
+
collaborationSignal: 0,
|
|
16579
|
+
reasoningSignal: 0,
|
|
16580
|
+
observed: {
|
|
16581
|
+
totalNodes: 0,
|
|
16582
|
+
rootCount: 0,
|
|
16583
|
+
edgeCount: 0,
|
|
16584
|
+
maxDepth: 0,
|
|
16585
|
+
artifactCount: 0,
|
|
16586
|
+
terminalCount: 0,
|
|
16587
|
+
integrationNodeCount: 0
|
|
16588
|
+
}
|
|
16589
|
+
};
|
|
16590
|
+
}
|
|
16591
|
+
const observed = computeObserved(evidence);
|
|
16592
|
+
const rootRatio = observed.rootCount / totalNodes;
|
|
16593
|
+
const edgeDensity = observed.edgeCount / Math.max(totalNodes - 1, 1);
|
|
16594
|
+
const integrationRatio = observed.integrationNodeCount / totalNodes;
|
|
16595
|
+
const depthRatio = observed.maxDepth / totalNodes;
|
|
16596
|
+
const scoring = resolveScoring(context?.studioPolicy, context?.workMandate);
|
|
16597
|
+
let initiativeSignal;
|
|
16598
|
+
let collaborationSignal;
|
|
16599
|
+
let reasoningSignal;
|
|
16600
|
+
let complianceSignal;
|
|
16601
|
+
let efficiencySignal;
|
|
16602
|
+
const observedBlock = {
|
|
16603
|
+
totalNodes,
|
|
16604
|
+
rootCount: observed.rootCount,
|
|
16605
|
+
edgeCount: observed.edgeCount,
|
|
16606
|
+
maxDepth: observed.maxDepth,
|
|
16607
|
+
artifactCount: observed.artifactCount,
|
|
16608
|
+
terminalCount: observed.terminalCount,
|
|
16609
|
+
integrationNodeCount: observed.integrationNodeCount,
|
|
16610
|
+
uniqueAuthors: observed.uniqueAuthors,
|
|
16611
|
+
durationMs: observed.durationMs
|
|
16612
|
+
};
|
|
16613
|
+
if (!scoring) {
|
|
16614
|
+
const SOFT_CAP = 0.9;
|
|
16615
|
+
initiativeSignal = Math.max(0, Math.min(SOFT_CAP, rootRatio));
|
|
16616
|
+
collaborationSignal = Math.max(0, Math.min(SOFT_CAP, edgeDensity));
|
|
16617
|
+
reasoningSignal = Math.max(0, Math.min(SOFT_CAP, depthRatio));
|
|
16618
|
+
} else {
|
|
16619
|
+
const ir = scoring.initiative.rootRatio;
|
|
16620
|
+
const initiativeBase = rangeFit(rootRatio, ir.min, ir.target, ir.max);
|
|
16621
|
+
const cw = scoring.collaboration.weights;
|
|
16622
|
+
const ed = scoring.collaboration.edgeDensity;
|
|
16623
|
+
const intR = scoring.collaboration.integrationRatio;
|
|
16624
|
+
const collabWeightSum = (cw.edgeDensity || 0) + (cw.integrationRatio || 0);
|
|
16625
|
+
if (collabWeightSum > 0) {
|
|
16626
|
+
collaborationSignal = (cw.edgeDensity * rangeFit(edgeDensity, ed.min, ed.target, ed.max) + cw.integrationRatio * rangeFit(integrationRatio, intR.min, intR.target, intR.max)) / collabWeightSum;
|
|
16627
|
+
} else {
|
|
16628
|
+
collaborationSignal = 0;
|
|
16629
|
+
}
|
|
16630
|
+
collaborationSignal = Math.max(0, Math.min(1, collaborationSignal));
|
|
16631
|
+
const dr = scoring.reasoning.depthRatio;
|
|
16632
|
+
const reasoningBase = rangeFit(depthRatio, dr.min, dr.target, dr.max);
|
|
16633
|
+
const fragmentationPenalty = rootRatio > ir.max ? (rootRatio - ir.max) * 0.5 : 0;
|
|
16634
|
+
const overcomplexityPenalty = depthRatio > dr.max ? (depthRatio - dr.max) * 0.5 : 0;
|
|
16635
|
+
initiativeSignal = Math.max(0, Math.min(1, initiativeBase - fragmentationPenalty));
|
|
16636
|
+
reasoningSignal = Math.max(0, Math.min(1, reasoningBase - overcomplexityPenalty));
|
|
16637
|
+
observedBlock.fragmentationPenalty = fragmentationPenalty;
|
|
16638
|
+
observedBlock.overcomplexityPenalty = overcomplexityPenalty;
|
|
16639
|
+
const compResult = computeComplianceSignal(evidence, observed, scoring, context?.workMandate);
|
|
16640
|
+
complianceSignal = compResult.signal;
|
|
16641
|
+
observedBlock.testsPresent = compResult.testsPresent;
|
|
16642
|
+
observedBlock.policyViolations = compResult.violations;
|
|
16643
|
+
observedBlock.requiredArtifactsPresent = compResult.present;
|
|
16644
|
+
observedBlock.missingArtifacts = compResult.missing;
|
|
16645
|
+
efficiencySignal = computeEfficiencySignal(observed, scoring, context?.workMandate);
|
|
16646
|
+
}
|
|
16647
|
+
return {
|
|
16648
|
+
initiativeSignal,
|
|
16649
|
+
collaborationSignal,
|
|
16650
|
+
reasoningSignal,
|
|
16651
|
+
complianceSignal,
|
|
16652
|
+
efficiencySignal,
|
|
16653
|
+
observed: observedBlock
|
|
16654
|
+
};
|
|
16655
|
+
}
|
|
16656
|
+
function computeDepth(evidence) {
|
|
16657
|
+
if (evidence.length === 0) return 0;
|
|
16658
|
+
const byId = /* @__PURE__ */ new Map();
|
|
16659
|
+
for (const e of evidence) byId.set(e.arweave_tx_id, e);
|
|
16660
|
+
const memo = /* @__PURE__ */ new Map();
|
|
16661
|
+
function dfs(id) {
|
|
16662
|
+
if (memo.has(id)) return memo.get(id);
|
|
16663
|
+
const node = byId.get(id);
|
|
16664
|
+
if (!node || node.parent_ids.length === 0) {
|
|
16665
|
+
memo.set(id, 1);
|
|
16666
|
+
return 1;
|
|
16667
|
+
}
|
|
16668
|
+
let maxParent = 0;
|
|
16669
|
+
for (const pid of node.parent_ids) {
|
|
16670
|
+
maxParent = Math.max(maxParent, dfs(pid));
|
|
16671
|
+
}
|
|
16672
|
+
const depth = maxParent + 1;
|
|
16673
|
+
memo.set(id, depth);
|
|
16674
|
+
return depth;
|
|
16675
|
+
}
|
|
16676
|
+
let maxDepth = 0;
|
|
16677
|
+
for (const e of evidence) {
|
|
16678
|
+
maxDepth = Math.max(maxDepth, dfs(e.arweave_tx_id));
|
|
16679
|
+
}
|
|
16680
|
+
return maxDepth;
|
|
16681
|
+
}
|
|
16682
|
+
function normalizeInput(value) {
|
|
16683
|
+
const v = value > 1 ? value / 100 : value;
|
|
16684
|
+
return Math.max(0, Math.min(1, v));
|
|
16685
|
+
}
|
|
16686
|
+
var CLAMP_100 = (v) => Math.max(0, Math.min(100, Math.round(v)));
|
|
16687
|
+
function resolveDimension(override, signal) {
|
|
16688
|
+
if (override !== void 0) return normalizeInput(override);
|
|
16689
|
+
return signal ?? 0;
|
|
16690
|
+
}
|
|
16691
|
+
function composeScoreVector(signals, assessment) {
|
|
16692
|
+
if (assessment.complianceScore === void 0 || assessment.complianceScore === null) {
|
|
16693
|
+
throw new Error("complianceScore is required for production scoring");
|
|
16694
|
+
}
|
|
16695
|
+
if (assessment.efficiencyScore === void 0 || assessment.efficiencyScore === null) {
|
|
16696
|
+
throw new Error("efficiencyScore is required for production scoring");
|
|
16697
|
+
}
|
|
16698
|
+
return [
|
|
16699
|
+
CLAMP_100(resolveDimension(assessment.initiativeScore, signals.initiativeSignal) * 100),
|
|
16700
|
+
CLAMP_100(resolveDimension(assessment.collaborationScore, signals.collaborationSignal) * 100),
|
|
16701
|
+
CLAMP_100(resolveDimension(assessment.reasoningScore, signals.reasoningSignal) * 100),
|
|
16702
|
+
CLAMP_100(normalizeInput(assessment.complianceScore) * 100),
|
|
16703
|
+
CLAMP_100(normalizeInput(assessment.efficiencyScore) * 100)
|
|
16704
|
+
];
|
|
16705
|
+
}
|
|
16706
|
+
function composeScoreVectorWithDefaults(signals, assessment) {
|
|
16707
|
+
return [
|
|
16708
|
+
CLAMP_100(resolveDimension(assessment?.initiativeScore, signals.initiativeSignal) * 100),
|
|
16709
|
+
CLAMP_100(resolveDimension(assessment?.collaborationScore, signals.collaborationSignal) * 100),
|
|
16710
|
+
CLAMP_100(resolveDimension(assessment?.reasoningScore, signals.reasoningSignal) * 100),
|
|
16711
|
+
CLAMP_100(resolveDimension(assessment?.complianceScore, signals.complianceSignal) * 100),
|
|
16712
|
+
CLAMP_100(resolveDimension(assessment?.efficiencyScore, signals.efficiencySignal) * 100)
|
|
16713
|
+
];
|
|
16714
|
+
}
|
|
16715
|
+
function derivePoAScores(evidence, options) {
|
|
16716
|
+
if (evidence.length === 0) {
|
|
16717
|
+
return [
|
|
16718
|
+
0,
|
|
16719
|
+
0,
|
|
16720
|
+
0,
|
|
16721
|
+
CLAMP_100(options?.compliance !== void 0 ? normalizeInput(options.compliance) * 100 : 0),
|
|
16722
|
+
CLAMP_100(options?.efficiency !== void 0 ? normalizeInput(options.efficiency) * 100 : 0)
|
|
16723
|
+
];
|
|
16724
|
+
}
|
|
16725
|
+
const signals = extractAgencySignals(evidence);
|
|
16726
|
+
return composeScoreVectorWithDefaults(signals, {
|
|
16727
|
+
complianceScore: options?.compliance,
|
|
16728
|
+
efficiencyScore: options?.efficiency
|
|
16729
|
+
});
|
|
16730
|
+
}
|
|
16731
|
+
function validateEvidenceGraph(evidence) {
|
|
16732
|
+
const ids = new Set(evidence.map((e) => e.arweave_tx_id));
|
|
16733
|
+
for (const e of evidence) {
|
|
16734
|
+
for (const pid of e.parent_ids) {
|
|
16735
|
+
if (!ids.has(pid)) return false;
|
|
16736
|
+
}
|
|
16737
|
+
}
|
|
16738
|
+
const inDegree = /* @__PURE__ */ new Map();
|
|
16739
|
+
const children = /* @__PURE__ */ new Map();
|
|
16740
|
+
for (const e of evidence) {
|
|
16741
|
+
if (!inDegree.has(e.arweave_tx_id)) inDegree.set(e.arweave_tx_id, 0);
|
|
16742
|
+
if (!children.has(e.arweave_tx_id)) children.set(e.arweave_tx_id, []);
|
|
16743
|
+
}
|
|
16744
|
+
for (const e of evidence) {
|
|
16745
|
+
for (const pid of e.parent_ids) {
|
|
16746
|
+
inDegree.set(e.arweave_tx_id, (inDegree.get(e.arweave_tx_id) ?? 0) + 1);
|
|
16747
|
+
const c = children.get(pid) ?? [];
|
|
16748
|
+
c.push(e.arweave_tx_id);
|
|
16749
|
+
children.set(pid, c);
|
|
16750
|
+
}
|
|
16751
|
+
}
|
|
16752
|
+
const queue = [];
|
|
16753
|
+
for (const [id, deg] of inDegree) {
|
|
16754
|
+
if (deg === 0) queue.push(id);
|
|
16755
|
+
}
|
|
16756
|
+
let visited = 0;
|
|
16757
|
+
while (queue.length > 0) {
|
|
16758
|
+
const node = queue.shift();
|
|
16759
|
+
visited++;
|
|
16760
|
+
for (const child of children.get(node) ?? []) {
|
|
16761
|
+
const newDeg = (inDegree.get(child) ?? 1) - 1;
|
|
16762
|
+
inDegree.set(child, newDeg);
|
|
16763
|
+
if (newDeg === 0) queue.push(child);
|
|
16764
|
+
}
|
|
16765
|
+
}
|
|
16766
|
+
return visited === evidence.length;
|
|
16767
|
+
}
|
|
16768
|
+
function verifyWorkEvidence(evidence, context) {
|
|
16769
|
+
const valid = validateEvidenceGraph(evidence);
|
|
16770
|
+
if (!valid) {
|
|
16771
|
+
return { valid: false };
|
|
16772
|
+
}
|
|
16773
|
+
const signals = extractAgencySignals(evidence, context);
|
|
16774
|
+
return { valid: true, signals };
|
|
16775
|
+
}
|
|
16776
|
+
|
|
16373
16777
|
// src/index.ts
|
|
16374
|
-
var SDK_VERSION = "0.2.
|
|
16778
|
+
var SDK_VERSION = "0.2.4";
|
|
16375
16779
|
var ERC8004_VERSION = "1.0";
|
|
16376
16780
|
var X402_VERSION = "1.0";
|
|
16377
16781
|
var src_default = ChaosChainSDK;
|
|
@@ -16397,57 +16801,6 @@ mime-types/index.js:
|
|
|
16397
16801
|
*)
|
|
16398
16802
|
*/
|
|
16399
16803
|
|
|
16400
|
-
|
|
16401
|
-
exports.AgentRegistrationError = AgentRegistrationError;
|
|
16402
|
-
exports.AgentRole = AgentRole;
|
|
16403
|
-
exports.AutoStorageManager = AutoStorageManager;
|
|
16404
|
-
exports.CHAOS_CORE_ABI = CHAOS_CORE_ABI;
|
|
16405
|
-
exports.ChaosAgent = ChaosAgent;
|
|
16406
|
-
exports.ChaosChainSDK = ChaosChainSDK;
|
|
16407
|
-
exports.ChaosChainSDKError = ChaosChainSDKError;
|
|
16408
|
-
exports.ConfigurationError = ConfigurationError;
|
|
16409
|
-
exports.ContractError = ContractError;
|
|
16410
|
-
exports.ERC8004_VERSION = ERC8004_VERSION;
|
|
16411
|
-
exports.GatewayClient = GatewayClient;
|
|
16412
|
-
exports.GatewayConnectionError = GatewayConnectionError;
|
|
16413
|
-
exports.GatewayError = GatewayError;
|
|
16414
|
-
exports.GatewayTimeoutError = GatewayTimeoutError;
|
|
16415
|
-
exports.GoogleAP2Integration = GoogleAP2Integration;
|
|
16416
|
-
exports.IDENTITY_REGISTRY_ABI = IDENTITY_REGISTRY_ABI;
|
|
16417
|
-
exports.IPFSLocalStorage = IPFSLocalStorage;
|
|
16418
|
-
exports.IPFSPinataStorage = PinataStorage;
|
|
16419
|
-
exports.IntegrityVerificationError = IntegrityVerificationError;
|
|
16420
|
-
exports.IrysStorage = IrysStorage;
|
|
16421
|
-
exports.IrysStorageProvider = IrysStorage;
|
|
16422
|
-
exports.LocalIPFSStorage = LocalIPFSStorage;
|
|
16423
|
-
exports.MandateManager = MandateManager;
|
|
16424
|
-
exports.NetworkConfig = NetworkConfig;
|
|
16425
|
-
exports.PaymentError = PaymentError;
|
|
16426
|
-
exports.PaymentManager = PaymentManager;
|
|
16427
|
-
exports.PaymentMethod = PaymentMethod;
|
|
16428
|
-
exports.PinataStorage = PinataStorage;
|
|
16429
|
-
exports.REPUTATION_REGISTRY_ABI = REPUTATION_REGISTRY_ABI;
|
|
16430
|
-
exports.REWARDS_DISTRIBUTOR_ABI = REWARDS_DISTRIBUTOR_ABI;
|
|
16431
|
-
exports.SDKValidationError = ValidationError;
|
|
16432
|
-
exports.SDK_VERSION = SDK_VERSION;
|
|
16433
|
-
exports.STUDIO_FACTORY_ABI = STUDIO_FACTORY_ABI;
|
|
16434
|
-
exports.STUDIO_PROXY_ABI = STUDIO_PROXY_ABI;
|
|
16435
|
-
exports.StorageError = StorageError;
|
|
16436
|
-
exports.StudioClient = StudioClient;
|
|
16437
|
-
exports.StudioManager = StudioManager;
|
|
16438
|
-
exports.VALIDATION_REGISTRY_ABI = VALIDATION_REGISTRY_ABI;
|
|
16439
|
-
exports.ValidationStatus = ValidationStatus;
|
|
16440
|
-
exports.WalletManager = WalletManager;
|
|
16441
|
-
exports.WorkflowFailedError = WorkflowFailedError;
|
|
16442
|
-
exports.WorkflowState = WorkflowState;
|
|
16443
|
-
exports.WorkflowType = WorkflowType;
|
|
16444
|
-
exports.X402PaymentManager = X402PaymentManager;
|
|
16445
|
-
exports.X402Server = X402Server;
|
|
16446
|
-
exports.X402_VERSION = X402_VERSION;
|
|
16447
|
-
exports.ZeroGStorage = ZeroGStorage;
|
|
16448
|
-
exports.default = src_default;
|
|
16449
|
-
exports.getContractAddresses = getContractAddresses2;
|
|
16450
|
-
exports.getNetworkInfo = getNetworkInfo;
|
|
16451
|
-
exports.initChaosChainSDK = initChaosChainSDK;
|
|
16804
|
+
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, composeScoreVector, composeScoreVectorWithDefaults, computeDepth, src_default as default, derivePoAScores, extractAgencySignals, getContractAddresses2 as getContractAddresses, getNetworkInfo, initChaosChainSDK, rangeFit, validateEvidenceGraph, verifyWorkEvidence };
|
|
16452
16805
|
//# sourceMappingURL=index.js.map
|
|
16453
16806
|
//# sourceMappingURL=index.js.map
|