@chaoschain/sdk 0.1.0

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/dist/index.js ADDED
@@ -0,0 +1,3549 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var ethers = require('ethers');
6
+ var fs2 = require('fs');
7
+ var path2 = require('path');
8
+ var axios2 = require('axios');
9
+ var http = require('http');
10
+ var crypto = require('crypto');
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 fs2__namespace = /*#__PURE__*/_interopNamespace(fs2);
34
+ var path2__namespace = /*#__PURE__*/_interopNamespace(path2);
35
+ var axios2__default = /*#__PURE__*/_interopDefault(axios2);
36
+ var http__namespace = /*#__PURE__*/_interopNamespace(http);
37
+ var crypto__namespace = /*#__PURE__*/_interopNamespace(crypto);
38
+ var jose__namespace = /*#__PURE__*/_interopNamespace(jose);
39
+
40
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
41
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
42
+ }) : x)(function(x) {
43
+ if (typeof require !== "undefined") return require.apply(this, arguments);
44
+ throw Error('Dynamic require of "' + x + '" is not supported');
45
+ });
46
+ var WalletManager = class _WalletManager {
47
+ wallet;
48
+ provider;
49
+ constructor(config, provider) {
50
+ this.wallet = this.initializeWallet(config);
51
+ this.provider = provider;
52
+ if (provider) {
53
+ this.wallet = this.wallet.connect(provider);
54
+ }
55
+ }
56
+ /**
57
+ * Initialize wallet from various sources
58
+ */
59
+ initializeWallet(config) {
60
+ if (config.privateKey) {
61
+ return new ethers.ethers.Wallet(config.privateKey);
62
+ }
63
+ if (config.mnemonic) {
64
+ return ethers.ethers.Wallet.fromPhrase(config.mnemonic);
65
+ }
66
+ if (config.walletFile) {
67
+ return this.loadFromFile(config.walletFile);
68
+ }
69
+ return ethers.ethers.Wallet.createRandom();
70
+ }
71
+ /**
72
+ * Load wallet from encrypted file
73
+ */
74
+ loadFromFile(filePath) {
75
+ try {
76
+ const walletData = fs2__namespace.readFileSync(filePath, "utf8");
77
+ const data = JSON.parse(walletData);
78
+ if (data.encrypted) {
79
+ throw new Error("Encrypted wallets require password (not yet implemented)");
80
+ }
81
+ return new ethers.ethers.Wallet(data.privateKey);
82
+ } catch (error) {
83
+ throw new Error(`Failed to load wallet from file: ${error.message}`);
84
+ }
85
+ }
86
+ /**
87
+ * Save wallet to encrypted file
88
+ */
89
+ async saveToFile(filePath, password) {
90
+ const directory = path2__namespace.dirname(filePath);
91
+ if (!fs2__namespace.existsSync(directory)) {
92
+ fs2__namespace.mkdirSync(directory, { recursive: true });
93
+ }
94
+ if (password) {
95
+ const encrypted = await this.wallet.encrypt(password);
96
+ fs2__namespace.writeFileSync(filePath, encrypted, "utf8");
97
+ } else {
98
+ const data = {
99
+ address: this.wallet.address,
100
+ privateKey: this.wallet.privateKey,
101
+ mnemonic: this.wallet.mnemonic?.phrase,
102
+ encrypted: false
103
+ };
104
+ fs2__namespace.writeFileSync(filePath, JSON.stringify(data, null, 2), "utf8");
105
+ }
106
+ }
107
+ /**
108
+ * Get wallet instance
109
+ */
110
+ getWallet() {
111
+ return this.wallet;
112
+ }
113
+ /**
114
+ * Get wallet address
115
+ */
116
+ getAddress() {
117
+ return this.wallet.address;
118
+ }
119
+ /**
120
+ * Get private key (use with caution)
121
+ */
122
+ getPrivateKey() {
123
+ return this.wallet.privateKey;
124
+ }
125
+ /**
126
+ * Get mnemonic phrase (if available)
127
+ */
128
+ getMnemonic() {
129
+ return this.wallet.mnemonic?.phrase;
130
+ }
131
+ /**
132
+ * Sign a message
133
+ */
134
+ async signMessage(message) {
135
+ return this.wallet.signMessage(message);
136
+ }
137
+ /**
138
+ * Sign typed data (EIP-712)
139
+ */
140
+ async signTypedData(domain, types, value) {
141
+ return this.wallet.signTypedData(domain, types, value);
142
+ }
143
+ /**
144
+ * Get balance
145
+ */
146
+ async getBalance() {
147
+ if (!this.provider) {
148
+ throw new Error("Provider not set");
149
+ }
150
+ return this.provider.getBalance(this.wallet.address);
151
+ }
152
+ /**
153
+ * Get nonce
154
+ */
155
+ async getNonce() {
156
+ if (!this.provider) {
157
+ throw new Error("Provider not set");
158
+ }
159
+ return this.provider.getTransactionCount(this.wallet.address);
160
+ }
161
+ /**
162
+ * Connect to a new provider
163
+ */
164
+ connect(provider) {
165
+ this.provider = provider;
166
+ this.wallet = this.wallet.connect(provider);
167
+ }
168
+ /**
169
+ * Generate a new random wallet
170
+ */
171
+ static createRandom() {
172
+ const wallet = ethers.ethers.Wallet.createRandom();
173
+ return new _WalletManager({ privateKey: wallet.privateKey });
174
+ }
175
+ /**
176
+ * Create from mnemonic
177
+ */
178
+ static fromMnemonic(mnemonic, provider) {
179
+ return new _WalletManager({ mnemonic }, provider);
180
+ }
181
+ /**
182
+ * Create from private key
183
+ */
184
+ static fromPrivateKey(privateKey, provider) {
185
+ return new _WalletManager({ privateKey }, provider);
186
+ }
187
+ /**
188
+ * Generate new mnemonic
189
+ */
190
+ static generateMnemonic() {
191
+ return ethers.ethers.Wallet.createRandom().mnemonic?.phrase || "";
192
+ }
193
+ /**
194
+ * Validate mnemonic
195
+ */
196
+ static isValidMnemonic(mnemonic) {
197
+ try {
198
+ ethers.ethers.Wallet.fromPhrase(mnemonic);
199
+ return true;
200
+ } catch {
201
+ return false;
202
+ }
203
+ }
204
+ /**
205
+ * Validate private key
206
+ */
207
+ static isValidPrivateKey(privateKey) {
208
+ try {
209
+ new ethers.ethers.Wallet(privateKey);
210
+ return true;
211
+ } catch {
212
+ return false;
213
+ }
214
+ }
215
+ /**
216
+ * Derive child wallet from HD path
217
+ */
218
+ static deriveChild(mnemonic, path3) {
219
+ const hdNode = ethers.ethers.HDNodeWallet.fromPhrase(mnemonic, void 0, path3);
220
+ return new _WalletManager({ privateKey: hdNode.privateKey });
221
+ }
222
+ };
223
+
224
+ // src/utils/contracts.ts
225
+ var IDENTITY_REGISTRY_ABI = [
226
+ {
227
+ inputs: [
228
+ { name: "tokenURI_", type: "string" },
229
+ {
230
+ name: "metadata",
231
+ type: "tuple[]",
232
+ components: [
233
+ { name: "key", type: "string" },
234
+ { name: "value", type: "bytes" }
235
+ ]
236
+ }
237
+ ],
238
+ name: "register",
239
+ outputs: [{ name: "agentId", type: "uint256" }],
240
+ stateMutability: "nonpayable",
241
+ type: "function"
242
+ },
243
+ {
244
+ inputs: [{ name: "tokenURI_", type: "string" }],
245
+ name: "register",
246
+ outputs: [{ name: "agentId", type: "uint256" }],
247
+ stateMutability: "nonpayable",
248
+ type: "function"
249
+ },
250
+ {
251
+ inputs: [],
252
+ name: "register",
253
+ outputs: [{ name: "agentId", type: "uint256" }],
254
+ stateMutability: "nonpayable",
255
+ type: "function"
256
+ },
257
+ // ERC-721 Standard Functions
258
+ {
259
+ inputs: [{ name: "tokenId", type: "uint256" }],
260
+ name: "ownerOf",
261
+ outputs: [{ name: "owner", type: "address" }],
262
+ stateMutability: "view",
263
+ type: "function"
264
+ },
265
+ {
266
+ inputs: [{ name: "owner", type: "address" }],
267
+ name: "balanceOf",
268
+ outputs: [{ name: "balance", type: "uint256" }],
269
+ stateMutability: "view",
270
+ type: "function"
271
+ },
272
+ {
273
+ inputs: [{ name: "tokenId", type: "uint256" }],
274
+ name: "tokenURI",
275
+ outputs: [{ name: "", type: "string" }],
276
+ stateMutability: "view",
277
+ type: "function"
278
+ },
279
+ {
280
+ inputs: [
281
+ { name: "from", type: "address" },
282
+ { name: "to", type: "address" },
283
+ { name: "tokenId", type: "uint256" }
284
+ ],
285
+ name: "transferFrom",
286
+ outputs: [],
287
+ stateMutability: "nonpayable",
288
+ type: "function"
289
+ },
290
+ {
291
+ inputs: [
292
+ { name: "to", type: "address" },
293
+ { name: "tokenId", type: "uint256" }
294
+ ],
295
+ name: "approve",
296
+ outputs: [],
297
+ stateMutability: "nonpayable",
298
+ type: "function"
299
+ },
300
+ {
301
+ inputs: [
302
+ { name: "operator", type: "address" },
303
+ { name: "approved", type: "bool" }
304
+ ],
305
+ name: "setApprovalForAll",
306
+ outputs: [],
307
+ stateMutability: "nonpayable",
308
+ type: "function"
309
+ },
310
+ {
311
+ inputs: [{ name: "tokenId", type: "uint256" }],
312
+ name: "getApproved",
313
+ outputs: [{ name: "operator", type: "address" }],
314
+ stateMutability: "view",
315
+ type: "function"
316
+ },
317
+ {
318
+ inputs: [
319
+ { name: "owner", type: "address" },
320
+ { name: "operator", type: "address" }
321
+ ],
322
+ name: "isApprovedForAll",
323
+ outputs: [{ name: "approved", type: "bool" }],
324
+ stateMutability: "view",
325
+ type: "function"
326
+ },
327
+ // Metadata Functions
328
+ {
329
+ inputs: [
330
+ { name: "agentId", type: "uint256" },
331
+ { name: "key", type: "string" },
332
+ { name: "value", type: "bytes" }
333
+ ],
334
+ name: "setMetadata",
335
+ outputs: [],
336
+ stateMutability: "nonpayable",
337
+ type: "function"
338
+ },
339
+ {
340
+ inputs: [
341
+ { name: "agentId", type: "uint256" },
342
+ { name: "key", type: "string" }
343
+ ],
344
+ name: "getMetadata",
345
+ outputs: [{ name: "value", type: "bytes" }],
346
+ stateMutability: "view",
347
+ type: "function"
348
+ },
349
+ // Additional Functions
350
+ {
351
+ inputs: [
352
+ { name: "agentId", type: "uint256" },
353
+ { name: "newUri", type: "string" }
354
+ ],
355
+ name: "setAgentUri",
356
+ outputs: [],
357
+ stateMutability: "nonpayable",
358
+ type: "function"
359
+ },
360
+ {
361
+ inputs: [],
362
+ name: "totalAgents",
363
+ outputs: [{ name: "", type: "uint256" }],
364
+ stateMutability: "view",
365
+ type: "function"
366
+ },
367
+ // Events
368
+ {
369
+ anonymous: false,
370
+ inputs: [
371
+ { indexed: true, name: "agentId", type: "uint256" },
372
+ { indexed: false, name: "tokenURI", type: "string" },
373
+ { indexed: true, name: "owner", type: "address" }
374
+ ],
375
+ name: "Registered",
376
+ type: "event"
377
+ },
378
+ {
379
+ anonymous: false,
380
+ inputs: [
381
+ { indexed: true, name: "agentId", type: "uint256" },
382
+ { indexed: true, name: "indexedKey", type: "string" },
383
+ { indexed: false, name: "key", type: "string" },
384
+ { indexed: false, name: "value", type: "bytes" }
385
+ ],
386
+ name: "MetadataSet",
387
+ type: "event"
388
+ },
389
+ // ERC-721 Standard Events
390
+ {
391
+ anonymous: false,
392
+ inputs: [
393
+ { indexed: true, name: "from", type: "address" },
394
+ { indexed: true, name: "to", type: "address" },
395
+ { indexed: true, name: "tokenId", type: "uint256" }
396
+ ],
397
+ name: "Transfer",
398
+ type: "event"
399
+ },
400
+ {
401
+ anonymous: false,
402
+ inputs: [
403
+ { indexed: true, name: "owner", type: "address" },
404
+ { indexed: true, name: "approved", type: "address" },
405
+ { indexed: true, name: "tokenId", type: "uint256" }
406
+ ],
407
+ name: "Approval",
408
+ type: "event"
409
+ },
410
+ {
411
+ anonymous: false,
412
+ inputs: [
413
+ { indexed: true, name: "owner", type: "address" },
414
+ { indexed: true, name: "operator", type: "address" },
415
+ { indexed: false, name: "approved", type: "bool" }
416
+ ],
417
+ name: "ApprovalForAll",
418
+ type: "event"
419
+ },
420
+ {
421
+ anonymous: false,
422
+ inputs: [
423
+ { indexed: true, name: "agentId", type: "uint256" },
424
+ { indexed: false, name: "newUri", type: "string" },
425
+ { indexed: true, name: "updatedBy", type: "address" }
426
+ ],
427
+ name: "UriUpdated",
428
+ type: "event"
429
+ }
430
+ ];
431
+ var REPUTATION_REGISTRY_ABI = [
432
+ // Core Functions
433
+ {
434
+ inputs: [
435
+ { name: "agentId", type: "uint256" },
436
+ { name: "score", type: "uint8" },
437
+ { name: "tag1", type: "bytes32" },
438
+ { name: "tag2", type: "bytes32" },
439
+ { name: "feedbackUri", type: "string" },
440
+ { name: "feedbackHash", type: "bytes32" },
441
+ { name: "feedbackAuth", type: "bytes" }
442
+ ],
443
+ name: "giveFeedback",
444
+ outputs: [],
445
+ stateMutability: "nonpayable",
446
+ type: "function"
447
+ },
448
+ {
449
+ inputs: [
450
+ { name: "agentId", type: "uint256" },
451
+ { name: "feedbackIndex", type: "uint64" }
452
+ ],
453
+ name: "revokeFeedback",
454
+ outputs: [],
455
+ stateMutability: "nonpayable",
456
+ type: "function"
457
+ },
458
+ {
459
+ inputs: [
460
+ { name: "agentId", type: "uint256" },
461
+ { name: "clientAddress", type: "address" },
462
+ { name: "feedbackIndex", type: "uint64" },
463
+ { name: "responseUri", type: "string" },
464
+ { name: "responseHash", type: "bytes32" }
465
+ ],
466
+ name: "appendResponse",
467
+ outputs: [],
468
+ stateMutability: "nonpayable",
469
+ type: "function"
470
+ },
471
+ // Read Functions
472
+ {
473
+ inputs: [
474
+ { name: "agentId", type: "uint256" },
475
+ { name: "clientAddresses", type: "address[]" },
476
+ { name: "tag1", type: "bytes32" },
477
+ { name: "tag2", type: "bytes32" }
478
+ ],
479
+ name: "getSummary",
480
+ outputs: [
481
+ { name: "count", type: "uint64" },
482
+ { name: "averageScore", type: "uint8" }
483
+ ],
484
+ stateMutability: "view",
485
+ type: "function"
486
+ },
487
+ {
488
+ inputs: [
489
+ { name: "agentId", type: "uint256" },
490
+ { name: "clientAddress", type: "address" },
491
+ { name: "index", type: "uint64" }
492
+ ],
493
+ name: "readFeedback",
494
+ outputs: [
495
+ { name: "score", type: "uint8" },
496
+ { name: "tag1", type: "bytes32" },
497
+ { name: "tag2", type: "bytes32" },
498
+ { name: "isRevoked", type: "bool" }
499
+ ],
500
+ stateMutability: "view",
501
+ type: "function"
502
+ },
503
+ {
504
+ inputs: [
505
+ { name: "agentId", type: "uint256" },
506
+ { name: "clientAddresses", type: "address[]" },
507
+ { name: "tag1", type: "bytes32" },
508
+ { name: "tag2", type: "bytes32" },
509
+ { name: "includeRevoked", type: "bool" }
510
+ ],
511
+ name: "readAllFeedback",
512
+ outputs: [
513
+ { name: "clients", type: "address[]" },
514
+ { name: "scores", type: "uint8[]" },
515
+ { name: "tag1s", type: "bytes32[]" },
516
+ { name: "tag2s", type: "bytes32[]" },
517
+ { name: "revokedStatuses", type: "bool[]" }
518
+ ],
519
+ stateMutability: "view",
520
+ type: "function"
521
+ },
522
+ {
523
+ inputs: [{ name: "agentId", type: "uint256" }],
524
+ name: "getClients",
525
+ outputs: [{ name: "clientList", type: "address[]" }],
526
+ stateMutability: "view",
527
+ type: "function"
528
+ },
529
+ {
530
+ inputs: [
531
+ { name: "agentId", type: "uint256" },
532
+ { name: "clientAddress", type: "address" }
533
+ ],
534
+ name: "getLastIndex",
535
+ outputs: [{ name: "lastIndex", type: "uint64" }],
536
+ stateMutability: "view",
537
+ type: "function"
538
+ },
539
+ {
540
+ inputs: [],
541
+ name: "getIdentityRegistry",
542
+ outputs: [{ name: "registry", type: "address" }],
543
+ stateMutability: "view",
544
+ type: "function"
545
+ },
546
+ // Events
547
+ {
548
+ anonymous: false,
549
+ inputs: [
550
+ { indexed: true, name: "agentId", type: "uint256" },
551
+ { indexed: true, name: "clientAddress", type: "address" },
552
+ { indexed: false, name: "score", type: "uint8" },
553
+ { indexed: true, name: "tag1", type: "bytes32" },
554
+ { indexed: false, name: "tag2", type: "bytes32" },
555
+ { indexed: false, name: "feedbackUri", type: "string" },
556
+ { indexed: false, name: "feedbackHash", type: "bytes32" }
557
+ ],
558
+ name: "NewFeedback",
559
+ type: "event"
560
+ },
561
+ {
562
+ anonymous: false,
563
+ inputs: [
564
+ { indexed: true, name: "agentId", type: "uint256" },
565
+ { indexed: true, name: "clientAddress", type: "address" },
566
+ { indexed: false, name: "feedbackIndex", type: "uint64" },
567
+ { indexed: true, name: "responder", type: "address" },
568
+ { indexed: false, name: "responseUri", type: "string" },
569
+ { indexed: false, name: "responseHash", type: "bytes32" }
570
+ ],
571
+ name: "ResponseAppended",
572
+ type: "event"
573
+ }
574
+ ];
575
+ var VALIDATION_REGISTRY_ABI = [
576
+ // Core Functions
577
+ {
578
+ inputs: [
579
+ { name: "validatorAddress", type: "address" },
580
+ { name: "agentId", type: "uint256" },
581
+ { name: "requestUri", type: "string" },
582
+ { name: "requestHash", type: "bytes32" }
583
+ ],
584
+ name: "validationRequest",
585
+ outputs: [],
586
+ stateMutability: "nonpayable",
587
+ type: "function"
588
+ },
589
+ {
590
+ inputs: [
591
+ { name: "requestHash", type: "bytes32" },
592
+ { name: "response", type: "uint8" },
593
+ { name: "responseUri", type: "string" },
594
+ { name: "responseHash", type: "bytes32" },
595
+ { name: "tag", type: "bytes32" }
596
+ ],
597
+ name: "validationResponse",
598
+ outputs: [],
599
+ stateMutability: "nonpayable",
600
+ type: "function"
601
+ },
602
+ // Read Functions
603
+ {
604
+ inputs: [{ name: "requestHash", type: "bytes32" }],
605
+ name: "getValidationStatus",
606
+ outputs: [
607
+ { name: "validatorAddress", type: "address" },
608
+ { name: "agentId", type: "uint256" },
609
+ { name: "response", type: "uint8" },
610
+ { name: "responseHash", type: "bytes32" },
611
+ { name: "tag", type: "bytes32" },
612
+ { name: "lastUpdate", type: "uint256" }
613
+ ],
614
+ stateMutability: "view",
615
+ type: "function"
616
+ },
617
+ {
618
+ inputs: [
619
+ { name: "agentId", type: "uint256" },
620
+ { name: "validatorAddresses", type: "address[]" },
621
+ { name: "tag", type: "bytes32" }
622
+ ],
623
+ name: "getSummary",
624
+ outputs: [
625
+ { name: "count", type: "uint64" },
626
+ { name: "avgResponse", type: "uint8" }
627
+ ],
628
+ stateMutability: "view",
629
+ type: "function"
630
+ },
631
+ {
632
+ inputs: [{ name: "agentId", type: "uint256" }],
633
+ name: "getAgentValidations",
634
+ outputs: [{ name: "requestHashes", type: "bytes32[]" }],
635
+ stateMutability: "view",
636
+ type: "function"
637
+ },
638
+ {
639
+ inputs: [{ name: "validatorAddress", type: "address" }],
640
+ name: "getValidatorRequests",
641
+ outputs: [{ name: "requestHashes", type: "bytes32[]" }],
642
+ stateMutability: "view",
643
+ type: "function"
644
+ },
645
+ {
646
+ inputs: [],
647
+ name: "getIdentityRegistry",
648
+ outputs: [{ name: "registry", type: "address" }],
649
+ stateMutability: "view",
650
+ type: "function"
651
+ },
652
+ // Events
653
+ {
654
+ anonymous: false,
655
+ inputs: [
656
+ { indexed: true, name: "validatorAddress", type: "address" },
657
+ { indexed: true, name: "agentId", type: "uint256" },
658
+ { indexed: false, name: "requestUri", type: "string" },
659
+ { indexed: true, name: "requestHash", type: "bytes32" }
660
+ ],
661
+ name: "ValidationRequest",
662
+ type: "event"
663
+ },
664
+ {
665
+ anonymous: false,
666
+ inputs: [
667
+ { indexed: true, name: "validatorAddress", type: "address" },
668
+ { indexed: true, name: "agentId", type: "uint256" },
669
+ { indexed: true, name: "requestHash", type: "bytes32" },
670
+ { indexed: false, name: "response", type: "uint8" },
671
+ { indexed: false, name: "responseUri", type: "string" },
672
+ { indexed: false, name: "responseHash", type: "bytes32" },
673
+ { indexed: false, name: "tag", type: "bytes32" }
674
+ ],
675
+ name: "ValidationResponse",
676
+ type: "event"
677
+ }
678
+ ];
679
+
680
+ // src/ChaosAgent.ts
681
+ var ChaosAgent = class {
682
+ identityContract;
683
+ reputationContract;
684
+ validationContract;
685
+ signer;
686
+ constructor(addresses, signer, _provider) {
687
+ this.signer = signer;
688
+ this.identityContract = new ethers.ethers.Contract(
689
+ addresses.identity,
690
+ IDENTITY_REGISTRY_ABI,
691
+ signer
692
+ );
693
+ this.reputationContract = new ethers.ethers.Contract(
694
+ addresses.reputation,
695
+ REPUTATION_REGISTRY_ABI,
696
+ signer
697
+ );
698
+ this.validationContract = new ethers.ethers.Contract(
699
+ addresses.validation,
700
+ VALIDATION_REGISTRY_ABI,
701
+ signer
702
+ );
703
+ }
704
+ // ============================================================================
705
+ // Identity Registry Methods
706
+ // ============================================================================
707
+ /**
708
+ * Register a new agent identity (ERC-8004)
709
+ */
710
+ async registerIdentity(metadata) {
711
+ const uri = metadata ? `data:application/json,${JSON.stringify(metadata)}` : "";
712
+ const tx = await this.identityContract.registerAgent(uri);
713
+ const receipt = await tx.wait();
714
+ const event = receipt.logs.map((log) => {
715
+ try {
716
+ return this.identityContract.interface.parseLog({
717
+ topics: [...log.topics],
718
+ data: log.data
719
+ });
720
+ } catch {
721
+ return null;
722
+ }
723
+ }).find((e) => e?.name === "AgentRegistered");
724
+ if (!event) {
725
+ throw new Error("AgentRegistered event not found");
726
+ }
727
+ return {
728
+ agentId: event.args.agentId,
729
+ txHash: receipt.hash,
730
+ owner: event.args.owner
731
+ };
732
+ }
733
+ /**
734
+ * Get agent metadata
735
+ */
736
+ async getAgentMetadata(agentId) {
737
+ try {
738
+ const uri = await this.identityContract.getAgentURI(agentId);
739
+ if (!uri) {
740
+ return null;
741
+ }
742
+ if (uri.startsWith("data:application/json,")) {
743
+ const json = uri.substring("data:application/json,".length);
744
+ return JSON.parse(decodeURIComponent(json));
745
+ }
746
+ if (uri.startsWith("ipfs://")) {
747
+ const cid = uri.substring(7);
748
+ const response = await fetch(`https://ipfs.io/ipfs/${cid}`);
749
+ return response.json();
750
+ }
751
+ if (uri.startsWith("https://") || uri.startsWith("http://")) {
752
+ const response = await fetch(uri);
753
+ return response.json();
754
+ }
755
+ return null;
756
+ } catch (error) {
757
+ console.error("Failed to get agent metadata:", error);
758
+ return null;
759
+ }
760
+ }
761
+ /**
762
+ * Set agent URI
763
+ */
764
+ async setAgentUri(agentId, uri) {
765
+ const tx = await this.identityContract.setAgentURI(agentId, uri);
766
+ const receipt = await tx.wait();
767
+ return receipt.hash;
768
+ }
769
+ /**
770
+ * Update agent metadata
771
+ */
772
+ async updateAgentMetadata(agentId, metadata) {
773
+ const uri = `data:application/json,${JSON.stringify(metadata)}`;
774
+ return this.setAgentUri(agentId, uri);
775
+ }
776
+ /**
777
+ * Check if agent exists
778
+ */
779
+ async agentExists(agentId) {
780
+ return this.identityContract.agentExists(agentId);
781
+ }
782
+ /**
783
+ * Get agent owner
784
+ */
785
+ async getAgentOwner(agentId) {
786
+ return this.identityContract.ownerOf(agentId);
787
+ }
788
+ /**
789
+ * Get total number of agents
790
+ */
791
+ async getTotalAgents() {
792
+ return this.identityContract.totalAgents();
793
+ }
794
+ /**
795
+ * Transfer agent ownership
796
+ */
797
+ async transferAgent(agentId, to) {
798
+ const from = await this.signer.getAddress();
799
+ const tx = await this.identityContract.transferFrom(from, to, agentId);
800
+ const receipt = await tx.wait();
801
+ return receipt.hash;
802
+ }
803
+ // ============================================================================
804
+ // Reputation Registry Methods
805
+ // ============================================================================
806
+ /**
807
+ * Generate EIP-191 signed feedback authorization (ERC-8004 v1.0)
808
+ *
809
+ * This signature allows a client to submit feedback to an agent's reputation.
810
+ * The agent owner signs to authorize the client to give feedback up to a certain index.
811
+ *
812
+ * @param agentId Target agent ID receiving feedback
813
+ * @param clientAddress Address of the client giving feedback
814
+ * @param indexLimit Maximum feedback index this authorization permits
815
+ * @param expiry Unix timestamp when authorization expires
816
+ * @returns Signed feedbackAuth bytes for use in giveFeedback()
817
+ */
818
+ async generateFeedbackAuthorization(agentId, clientAddress, indexLimit, expiry) {
819
+ try {
820
+ const network = await this.signer.provider.getNetwork();
821
+ const chainId = network.chainId;
822
+ const identityAddress = await this.identityContract.getAddress();
823
+ const signerAddress = await this.signer.getAddress();
824
+ const feedbackAuthData = ethers.ethers.solidityPackedKeccak256(
825
+ ["uint256", "address", "uint64", "uint256", "uint256", "address", "address"],
826
+ [agentId, clientAddress, indexLimit, expiry, chainId, identityAddress, signerAddress]
827
+ );
828
+ const signature = await this.signer.signMessage(ethers.ethers.getBytes(feedbackAuthData));
829
+ const signatureBytes = ethers.ethers.getBytes(signature);
830
+ const structBytes = ethers.ethers.concat([
831
+ ethers.ethers.toBeHex(agentId, 32),
832
+ ethers.ethers.zeroPadValue(clientAddress, 32),
833
+ ethers.ethers.concat([ethers.ethers.toBeHex(indexLimit, 8), ethers.ethers.zeroPadValue("0x", 24)]),
834
+ // uint64 padded
835
+ ethers.ethers.toBeHex(expiry, 32),
836
+ ethers.ethers.toBeHex(chainId, 32),
837
+ ethers.ethers.zeroPadValue(identityAddress, 32),
838
+ ethers.ethers.zeroPadValue(signerAddress, 32)
839
+ ]);
840
+ const feedbackAuth = ethers.ethers.hexlify(ethers.ethers.concat([structBytes, signatureBytes]));
841
+ console.log(`\u2705 Generated feedback authorization for agent #${agentId}`);
842
+ return feedbackAuth;
843
+ } catch (e) {
844
+ throw new Error(`Failed to generate feedback authorization: ${e.message}`);
845
+ }
846
+ }
847
+ /**
848
+ * Give feedback to an agent
849
+ */
850
+ async giveFeedback(params) {
851
+ const { agentId, rating, feedbackUri } = params;
852
+ if (rating < 0 || rating > 100) {
853
+ throw new Error("Rating must be between 0 and 100");
854
+ }
855
+ const tx = await this.reputationContract.giveFeedback(agentId, rating, feedbackUri);
856
+ const receipt = await tx.wait();
857
+ return receipt.hash;
858
+ }
859
+ /**
860
+ * Revoke feedback
861
+ */
862
+ async revokeFeedback(feedbackId) {
863
+ const tx = await this.reputationContract.revokeFeedback(feedbackId);
864
+ const receipt = await tx.wait();
865
+ return receipt.hash;
866
+ }
867
+ /**
868
+ * Append response to feedback
869
+ */
870
+ async appendResponse(feedbackId, responseUri) {
871
+ const tx = await this.reputationContract.appendResponse(feedbackId, responseUri);
872
+ const receipt = await tx.wait();
873
+ return receipt.hash;
874
+ }
875
+ /**
876
+ * Get feedback details
877
+ */
878
+ async getFeedback(feedbackId) {
879
+ const feedback = await this.reputationContract.getFeedback(feedbackId);
880
+ return {
881
+ feedbackId: feedback.feedbackId,
882
+ fromAgent: feedback.fromAgent,
883
+ toAgent: feedback.toAgent,
884
+ rating: feedback.rating,
885
+ feedbackUri: feedback.feedbackURI,
886
+ timestamp: Number(feedback.timestamp),
887
+ revoked: feedback.revoked
888
+ };
889
+ }
890
+ /**
891
+ * Get agent feedback IDs
892
+ */
893
+ async getAgentFeedback(agentId, offset = 0, limit = 10) {
894
+ return this.reputationContract.getAgentFeedback(agentId, offset, limit);
895
+ }
896
+ /**
897
+ * Get agent reputation stats
898
+ */
899
+ async getAgentStats(agentId) {
900
+ return this.reputationContract.getAgentStats(agentId);
901
+ }
902
+ // ============================================================================
903
+ // Validation Registry Methods
904
+ // ============================================================================
905
+ /**
906
+ * Request validation from another agent
907
+ */
908
+ async requestValidation(params) {
909
+ const { validatorAgentId, requestUri, requestHash } = params;
910
+ const hashBytes = ethers.ethers.id(requestHash);
911
+ const tx = await this.validationContract.requestValidation(
912
+ validatorAgentId,
913
+ requestUri,
914
+ hashBytes
915
+ );
916
+ const receipt = await tx.wait();
917
+ return receipt.hash;
918
+ }
919
+ /**
920
+ * Respond to validation request
921
+ */
922
+ async respondToValidation(requestId, approved, responseUri) {
923
+ const tx = await this.validationContract.respondToValidation(
924
+ requestId,
925
+ approved,
926
+ responseUri
927
+ );
928
+ const receipt = await tx.wait();
929
+ return receipt.hash;
930
+ }
931
+ /**
932
+ * Get validation request details
933
+ */
934
+ async getValidationRequest(requestId) {
935
+ const request = await this.validationContract.getValidationRequest(requestId);
936
+ return {
937
+ requestId: request.requestId,
938
+ requester: request.requester,
939
+ validator: request.validator,
940
+ requestUri: request.requestURI,
941
+ requestHash: request.requestHash,
942
+ status: request.status,
943
+ responseUri: request.responseURI,
944
+ timestamp: Number(request.timestamp)
945
+ };
946
+ }
947
+ /**
948
+ * Get agent validation requests
949
+ */
950
+ async getAgentValidationRequests(agentId, asValidator = false, offset = 0, limit = 10) {
951
+ return this.validationContract.getAgentValidationRequests(
952
+ agentId,
953
+ asValidator,
954
+ offset,
955
+ limit
956
+ );
957
+ }
958
+ /**
959
+ * Get validation statistics for an agent
960
+ */
961
+ async getValidationStats(agentId) {
962
+ return this.validationContract.getValidationStats(agentId);
963
+ }
964
+ // ============================================================================
965
+ // Event Listening
966
+ // ============================================================================
967
+ /**
968
+ * Listen for AgentRegistered events
969
+ */
970
+ onAgentRegistered(callback) {
971
+ this.identityContract.on("AgentRegistered", callback);
972
+ }
973
+ /**
974
+ * Listen for FeedbackGiven events
975
+ */
976
+ onFeedbackGiven(callback) {
977
+ this.reputationContract.on("FeedbackGiven", callback);
978
+ }
979
+ /**
980
+ * Listen for ValidationRequested events
981
+ */
982
+ onValidationRequested(callback) {
983
+ this.validationContract.on("ValidationRequested", callback);
984
+ }
985
+ /**
986
+ * Listen for ValidationResponded events
987
+ */
988
+ onValidationResponded(callback) {
989
+ this.validationContract.on("ValidationResponded", callback);
990
+ }
991
+ /**
992
+ * Remove all event listeners
993
+ */
994
+ removeAllListeners() {
995
+ this.identityContract.removeAllListeners();
996
+ this.reputationContract.removeAllListeners();
997
+ this.validationContract.removeAllListeners();
998
+ }
999
+ };
1000
+
1001
+ // src/exceptions.ts
1002
+ var ChaosChainSDKError = class _ChaosChainSDKError extends Error {
1003
+ details;
1004
+ constructor(message, details = {}) {
1005
+ super(message);
1006
+ this.name = "ChaosChainSDKError";
1007
+ this.details = details;
1008
+ Object.setPrototypeOf(this, _ChaosChainSDKError.prototype);
1009
+ }
1010
+ toString() {
1011
+ if (Object.keys(this.details).length > 0) {
1012
+ return `${this.message} | Details: ${JSON.stringify(this.details)}`;
1013
+ }
1014
+ return this.message;
1015
+ }
1016
+ };
1017
+ var AgentRegistrationError = class _AgentRegistrationError extends ChaosChainSDKError {
1018
+ constructor(message, details) {
1019
+ super(message, details);
1020
+ this.name = "AgentRegistrationError";
1021
+ Object.setPrototypeOf(this, _AgentRegistrationError.prototype);
1022
+ }
1023
+ };
1024
+ var PaymentError2 = class _PaymentError extends ChaosChainSDKError {
1025
+ constructor(message, details) {
1026
+ super(message, details);
1027
+ this.name = "PaymentError";
1028
+ Object.setPrototypeOf(this, _PaymentError.prototype);
1029
+ }
1030
+ };
1031
+ var StorageError = class _StorageError extends ChaosChainSDKError {
1032
+ constructor(message, details) {
1033
+ super(message, details);
1034
+ this.name = "StorageError";
1035
+ Object.setPrototypeOf(this, _StorageError.prototype);
1036
+ }
1037
+ };
1038
+ var IntegrityVerificationError = class _IntegrityVerificationError extends ChaosChainSDKError {
1039
+ constructor(message, details) {
1040
+ super(message, details);
1041
+ this.name = "IntegrityVerificationError";
1042
+ Object.setPrototypeOf(this, _IntegrityVerificationError.prototype);
1043
+ }
1044
+ };
1045
+ var ContractError = class _ContractError extends ChaosChainSDKError {
1046
+ constructor(message, details) {
1047
+ super(message, details);
1048
+ this.name = "ContractError";
1049
+ Object.setPrototypeOf(this, _ContractError.prototype);
1050
+ }
1051
+ };
1052
+ var ConfigurationError = class _ConfigurationError extends ChaosChainSDKError {
1053
+ constructor(message, details) {
1054
+ super(message, details);
1055
+ this.name = "ConfigurationError";
1056
+ Object.setPrototypeOf(this, _ConfigurationError.prototype);
1057
+ }
1058
+ };
1059
+
1060
+ // src/X402PaymentManager.ts
1061
+ var X402PaymentManager = class {
1062
+ wallet;
1063
+ provider;
1064
+ network;
1065
+ treasuryAddress;
1066
+ protocolFeePercentage;
1067
+ usdcAddresses;
1068
+ constructor(wallet, network) {
1069
+ this.wallet = wallet;
1070
+ this.network = network;
1071
+ this.protocolFeePercentage = 0.025;
1072
+ this.treasuryAddress = this.getTreasuryAddress(network);
1073
+ this.usdcAddresses = {
1074
+ "base-sepolia": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
1075
+ "ethereum-sepolia": "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238",
1076
+ "optimism-sepolia": "0x5fd84259d66Cd46123540766Be93DFE6D43130D7",
1077
+ "linea-sepolia": "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238"
1078
+ };
1079
+ this.provider = wallet.provider;
1080
+ console.log(`\u2705 X402 Payment Manager initialized on ${network}`);
1081
+ console.log(`\u{1F4B0} Treasury: ${this.treasuryAddress}`);
1082
+ console.log(`\u{1F4CA} Protocol Fee: ${this.protocolFeePercentage * 100}%`);
1083
+ }
1084
+ /**
1085
+ * Get ChaosChain treasury address for network
1086
+ */
1087
+ getTreasuryAddress(network) {
1088
+ const treasuries = {
1089
+ "base-sepolia": "0x8004AA63c570c570eBF15376c0dB199918BFe9Fb",
1090
+ "ethereum-sepolia": "0x8004a6090Cd10A7288092483047B097295Fb8847",
1091
+ "optimism-sepolia": "0x8004a6090Cd10A7288092483047B097295Fb8847",
1092
+ "linea-sepolia": "0x8004aa7C931bCE1233973a0C6A667f73F66282e7"
1093
+ };
1094
+ return treasuries[network] || treasuries["base-sepolia"];
1095
+ }
1096
+ /**
1097
+ * Create x402 payment request
1098
+ */
1099
+ createPaymentRequest(fromAgent, toAgent, amount, currency = "USDC", serviceDescription = "AI Agent Service") {
1100
+ const paymentId = `x402_${Date.now().toString(36)}_${Math.random().toString(36).substring(2, 9)}`;
1101
+ const protocolFee = amount * this.protocolFeePercentage;
1102
+ const request = {
1103
+ payment_id: paymentId,
1104
+ from_agent: fromAgent,
1105
+ to_agent: toAgent,
1106
+ amount,
1107
+ currency,
1108
+ service_description: serviceDescription,
1109
+ network: this.network,
1110
+ protocol_fee: protocolFee,
1111
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
1112
+ };
1113
+ console.log(`\u{1F4C4} Created x402 payment request: ${paymentId}`);
1114
+ console.log(` From: ${fromAgent} \u2192 To: ${toAgent}`);
1115
+ console.log(` Amount: ${amount} ${currency} + ${protocolFee.toFixed(4)} ${currency} fee`);
1116
+ return request;
1117
+ }
1118
+ /**
1119
+ * Execute x402 payment on-chain
1120
+ */
1121
+ async executePayment(paymentRequest, recipientAddress) {
1122
+ console.log(`\u{1F4B8} Executing x402 payment: ${paymentRequest.payment_id}`);
1123
+ console.log(` Network: ${this.network}`);
1124
+ console.log(` Recipient: ${recipientAddress}`);
1125
+ const currency = paymentRequest.currency.toUpperCase();
1126
+ const amount = paymentRequest.amount;
1127
+ const protocolFee = paymentRequest.protocol_fee;
1128
+ let mainTxHash;
1129
+ let feeTxHash;
1130
+ let chainId;
1131
+ try {
1132
+ const networkInfo = await this.provider.getNetwork();
1133
+ chainId = Number(networkInfo.chainId);
1134
+ if (currency === "ETH" || currency === "NATIVE") {
1135
+ const { mainTx, feeTx } = await this.executeNativePayment(recipientAddress, amount, protocolFee);
1136
+ mainTxHash = mainTx;
1137
+ feeTxHash = feeTx;
1138
+ } else if (currency === "USDC") {
1139
+ const { mainTx, feeTx } = await this.executeUsdcPayment(recipientAddress, amount, protocolFee);
1140
+ mainTxHash = mainTx;
1141
+ feeTxHash = feeTx;
1142
+ } else {
1143
+ throw new PaymentError2(`Unsupported currency: ${currency}`);
1144
+ }
1145
+ const receipt = await this.provider.getTransactionReceipt(mainTxHash);
1146
+ const proof = {
1147
+ payment_id: paymentRequest.payment_id,
1148
+ transaction_hash: mainTxHash,
1149
+ main_transaction_hash: mainTxHash,
1150
+ fee_transaction_hash: feeTxHash,
1151
+ from_address: this.wallet.address,
1152
+ to_address: recipientAddress,
1153
+ treasury_address: this.treasuryAddress,
1154
+ amount,
1155
+ currency,
1156
+ protocol_fee: protocolFee,
1157
+ network: this.network,
1158
+ chain_id: chainId,
1159
+ block_number: receipt?.blockNumber,
1160
+ timestamp: /* @__PURE__ */ new Date(),
1161
+ status: receipt?.status === 1 ? "confirmed" : "failed",
1162
+ confirmations: 1
1163
+ };
1164
+ console.log(`\u2705 x402 payment executed successfully`);
1165
+ console.log(` Main TX: ${mainTxHash}`);
1166
+ if (feeTxHash) {
1167
+ console.log(` Fee TX: ${feeTxHash}`);
1168
+ }
1169
+ return proof;
1170
+ } catch (e) {
1171
+ throw new PaymentError2(`x402 payment failed: ${e.message}`, { payment_id: paymentRequest.payment_id });
1172
+ }
1173
+ }
1174
+ /**
1175
+ * Execute native token (ETH) payment
1176
+ */
1177
+ async executeNativePayment(recipientAddress, amount, protocolFee) {
1178
+ const amountWei = ethers.ethers.parseEther(amount.toString());
1179
+ const feeWei = ethers.ethers.parseEther(protocolFee.toString());
1180
+ const mainTx = await this.wallet.sendTransaction({
1181
+ to: recipientAddress,
1182
+ value: amountWei
1183
+ });
1184
+ await mainTx.wait();
1185
+ let feeTxHash;
1186
+ if (protocolFee > 0) {
1187
+ const feeTx = await this.wallet.sendTransaction({
1188
+ to: this.treasuryAddress,
1189
+ value: feeWei
1190
+ });
1191
+ await feeTx.wait();
1192
+ feeTxHash = feeTx.hash;
1193
+ }
1194
+ return {
1195
+ mainTx: mainTx.hash,
1196
+ feeTx: feeTxHash
1197
+ };
1198
+ }
1199
+ /**
1200
+ * Execute USDC payment
1201
+ */
1202
+ async executeUsdcPayment(recipientAddress, amount, protocolFee) {
1203
+ const usdcAddress = this.usdcAddresses[this.network];
1204
+ if (!usdcAddress) {
1205
+ throw new PaymentError2(`USDC not supported on ${this.network}`);
1206
+ }
1207
+ const amountUsdc = ethers.ethers.parseUnits(amount.toString(), 6);
1208
+ const feeUsdc = ethers.ethers.parseUnits(protocolFee.toString(), 6);
1209
+ const erc20Abi = ["function transfer(address to, uint256 amount) returns (bool)"];
1210
+ const usdcContract = new ethers.ethers.Contract(usdcAddress, erc20Abi, this.wallet);
1211
+ const mainTx = await usdcContract.transfer(recipientAddress, amountUsdc);
1212
+ await mainTx.wait();
1213
+ let feeTxHash;
1214
+ if (protocolFee > 0) {
1215
+ const feeTx = await usdcContract.transfer(this.treasuryAddress, feeUsdc);
1216
+ await feeTx.wait();
1217
+ feeTxHash = feeTx.hash;
1218
+ }
1219
+ return {
1220
+ mainTx: mainTx.hash,
1221
+ feeTx: feeTxHash
1222
+ };
1223
+ }
1224
+ /**
1225
+ * Verify x402 payment on-chain
1226
+ */
1227
+ async verifyPayment(paymentProof) {
1228
+ try {
1229
+ const receipt = await this.provider.getTransactionReceipt(paymentProof.main_transaction_hash);
1230
+ if (!receipt) {
1231
+ console.error(`\u274C Transaction not found: ${paymentProof.main_transaction_hash}`);
1232
+ return false;
1233
+ }
1234
+ if (receipt.status !== 1) {
1235
+ console.error(`\u274C Transaction failed: ${paymentProof.main_transaction_hash}`);
1236
+ return false;
1237
+ }
1238
+ const tx = await this.provider.getTransaction(paymentProof.main_transaction_hash);
1239
+ if (tx?.to?.toLowerCase() !== paymentProof.to_address.toLowerCase()) {
1240
+ console.error(`\u274C Recipient mismatch`);
1241
+ return false;
1242
+ }
1243
+ console.log(`\u2705 Payment verified on-chain: ${paymentProof.main_transaction_hash}`);
1244
+ return true;
1245
+ } catch (e) {
1246
+ console.error(`\u274C Payment verification failed: ${e}`);
1247
+ return false;
1248
+ }
1249
+ }
1250
+ /**
1251
+ * Create payment requirements for receiving payments
1252
+ */
1253
+ createPaymentRequirements(amount, currency = "USDC", serviceDescription = "AI Agent Service", expiryMinutes = 30) {
1254
+ const expiryTime = new Date(Date.now() + expiryMinutes * 60 * 1e3);
1255
+ return {
1256
+ amount,
1257
+ currency,
1258
+ service_description: serviceDescription,
1259
+ settlement_address: this.wallet.address,
1260
+ network: this.network,
1261
+ protocol_version: "x402-v1.0",
1262
+ expires_at: expiryTime.toISOString(),
1263
+ payment_endpoint: `x402://pay/${this.wallet.address}`
1264
+ };
1265
+ }
1266
+ /**
1267
+ * Get payment history (from on-chain events)
1268
+ */
1269
+ async getPaymentHistory(limit = 10) {
1270
+ console.log(`\u{1F4CA} Payment history: querying last ${limit} payments...`);
1271
+ return [];
1272
+ }
1273
+ /**
1274
+ * Create cryptographic receipt for payment
1275
+ */
1276
+ createPaymentReceipt(paymentProof) {
1277
+ const receiptData = {
1278
+ payment_id: paymentProof.payment_id,
1279
+ transaction_hash: paymentProof.main_transaction_hash,
1280
+ from_address: paymentProof.from_address,
1281
+ to_address: paymentProof.to_address,
1282
+ amount: paymentProof.amount,
1283
+ currency: paymentProof.currency,
1284
+ protocol_fee: paymentProof.protocol_fee,
1285
+ network: paymentProof.network,
1286
+ chain_id: paymentProof.chain_id,
1287
+ timestamp: paymentProof.timestamp.toISOString(),
1288
+ status: paymentProof.status
1289
+ };
1290
+ const crypto2 = __require("crypto");
1291
+ const receiptJson = JSON.stringify(receiptData);
1292
+ const receiptHash = crypto2.createHash("sha256").update(receiptJson).digest("hex");
1293
+ return {
1294
+ receipt_type: "x402_payment",
1295
+ receipt_hash: receiptHash,
1296
+ receipt_data: receiptData,
1297
+ verification_url: `https://explorer.base.org/tx/${paymentProof.main_transaction_hash}`,
1298
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
1299
+ };
1300
+ }
1301
+ /**
1302
+ * Get payment statistics
1303
+ */
1304
+ getPaymentStats() {
1305
+ return {
1306
+ network: this.network,
1307
+ wallet_address: this.wallet.address,
1308
+ treasury_address: this.treasuryAddress,
1309
+ protocol_fee_percentage: this.protocolFeePercentage * 100,
1310
+ supported_currencies: ["ETH", "USDC"],
1311
+ features: {
1312
+ instant_settlement: true,
1313
+ on_chain_verification: true,
1314
+ protocol_fees: true,
1315
+ multi_currency: true,
1316
+ payment_receipts: true
1317
+ }
1318
+ };
1319
+ }
1320
+ };
1321
+ var PaymentManager = class {
1322
+ agentName;
1323
+ network;
1324
+ wallet;
1325
+ credentials;
1326
+ stripeAxiosInstance;
1327
+ paypalAccessToken;
1328
+ constructor(agentName, network, wallet, credentials = {}) {
1329
+ this.agentName = agentName;
1330
+ this.network = network;
1331
+ this.wallet = wallet;
1332
+ this.credentials = credentials;
1333
+ if (credentials.stripe_secret_key) {
1334
+ this.stripeAxiosInstance = axios2__default.default.create({
1335
+ baseURL: "https://api.stripe.com/v1",
1336
+ headers: {
1337
+ Authorization: `Bearer ${credentials.stripe_secret_key}`,
1338
+ "Content-Type": "application/x-www-form-urlencoded"
1339
+ }
1340
+ });
1341
+ console.log("\u2705 Stripe integration enabled");
1342
+ }
1343
+ if (credentials.paypal_client_id && credentials.paypal_client_secret) {
1344
+ this.initializePayPal().catch(console.error);
1345
+ }
1346
+ console.log(`\u{1F4B3} Payment Manager initialized for ${agentName}`);
1347
+ }
1348
+ /**
1349
+ * Initialize PayPal OAuth access token
1350
+ */
1351
+ async initializePayPal() {
1352
+ try {
1353
+ const auth = Buffer.from(
1354
+ `${this.credentials.paypal_client_id}:${this.credentials.paypal_client_secret}`
1355
+ ).toString("base64");
1356
+ const response = await axios2__default.default.post(
1357
+ "https://api-m.sandbox.paypal.com/v1/oauth2/token",
1358
+ "grant_type=client_credentials",
1359
+ {
1360
+ headers: {
1361
+ Authorization: `Basic ${auth}`,
1362
+ "Content-Type": "application/x-www-form-urlencoded"
1363
+ }
1364
+ }
1365
+ );
1366
+ this.paypalAccessToken = response.data.access_token;
1367
+ console.log("\u2705 PayPal integration enabled");
1368
+ } catch (e) {
1369
+ console.error("\u274C Failed to initialize PayPal:", e);
1370
+ }
1371
+ }
1372
+ /**
1373
+ * Execute traditional payment (cards, wallets, etc.)
1374
+ */
1375
+ executeTraditionalPayment(paymentMethod, amount, currency, paymentData_unused) {
1376
+ console.log(`\u{1F4B3} Processing ${paymentMethod} payment: $${amount} ${currency}`);
1377
+ switch (paymentMethod) {
1378
+ case "basic-card" /* BASIC_CARD */:
1379
+ return this.processBasicCard(amount, currency, paymentData);
1380
+ case "https://google.com/pay" /* GOOGLE_PAY */:
1381
+ return this.processGooglePay(amount, currency, paymentData);
1382
+ case "https://apple.com/apple-pay" /* APPLE_PAY */:
1383
+ return this.processApplePay(amount, currency, paymentData);
1384
+ case "https://paypal.com" /* PAYPAL */:
1385
+ return this.processPayPal(amount, currency, paymentData);
1386
+ case "https://a2a.org/x402" /* A2A_X402 */:
1387
+ return this.processA2AX402(amount, currency, paymentData);
1388
+ default:
1389
+ throw new PaymentError(`Unsupported payment method: ${paymentMethod}`);
1390
+ }
1391
+ }
1392
+ /**
1393
+ * Process Basic Card payment (Visa, Mastercard, Amex, etc.) via Stripe
1394
+ */
1395
+ processBasicCard(amount, currency, paymentData_unused) {
1396
+ console.log("\u{1F4B3} Processing Basic Card via Stripe...");
1397
+ if (!this.stripeAxiosInstance) {
1398
+ console.warn("\u26A0\uFE0F Stripe not configured, simulating payment");
1399
+ return this.simulateTraditionalPayment("basic-card" /* BASIC_CARD */, amount, currency);
1400
+ }
1401
+ try {
1402
+ return this.simulateTraditionalPayment("basic-card" /* BASIC_CARD */, amount, currency);
1403
+ } catch (e) {
1404
+ throw new PaymentError(`Basic card payment failed: ${e}`);
1405
+ }
1406
+ }
1407
+ /**
1408
+ * Process Google Pay payment
1409
+ */
1410
+ processGooglePay(amount, currency, paymentData_unused) {
1411
+ console.log("\u{1F176} Processing Google Pay...");
1412
+ if (!this.credentials.google_pay_merchant_id) {
1413
+ console.warn("\u26A0\uFE0F Google Pay not configured, simulating payment");
1414
+ return this.simulateTraditionalPayment("https://google.com/pay" /* GOOGLE_PAY */, amount, currency);
1415
+ }
1416
+ return this.simulateTraditionalPayment("https://google.com/pay" /* GOOGLE_PAY */, amount, currency);
1417
+ }
1418
+ /**
1419
+ * Process Apple Pay payment
1420
+ */
1421
+ processApplePay(amount, currency, paymentData_unused) {
1422
+ console.log("\u{1F34E} Processing Apple Pay...");
1423
+ if (!this.credentials.apple_pay_merchant_id) {
1424
+ console.warn("\u26A0\uFE0F Apple Pay not configured, simulating payment");
1425
+ return this.simulateTraditionalPayment("https://apple.com/apple-pay" /* APPLE_PAY */, amount, currency);
1426
+ }
1427
+ return this.simulateTraditionalPayment("https://apple.com/apple-pay" /* APPLE_PAY */, amount, currency);
1428
+ }
1429
+ /**
1430
+ * Process PayPal payment
1431
+ */
1432
+ processPayPal(amount, currency, paymentData_unused) {
1433
+ console.log("\u{1F499} Processing PayPal...");
1434
+ if (!this.paypalAccessToken) {
1435
+ console.warn("\u26A0\uFE0F PayPal not configured, simulating payment");
1436
+ return this.simulateTraditionalPayment("https://paypal.com" /* PAYPAL */, amount, currency);
1437
+ }
1438
+ try {
1439
+ return this.simulateTraditionalPayment("https://paypal.com" /* PAYPAL */, amount, currency);
1440
+ } catch (e) {
1441
+ throw new PaymentError(`PayPal payment failed: ${e}`);
1442
+ }
1443
+ }
1444
+ /**
1445
+ * Process A2A-x402 crypto payment
1446
+ */
1447
+ processA2AX402(amount, currency, paymentData_unused) {
1448
+ console.log("\u{1F517} Processing A2A-x402 crypto payment...");
1449
+ const paymentId = `a2a_x402_${Date.now().toString(36)}`;
1450
+ return {
1451
+ payment_id: paymentId,
1452
+ transaction_id: paymentData.transaction_hash || `crypto_tx_${paymentId}`,
1453
+ status: "pending_crypto_confirmation",
1454
+ amount,
1455
+ currency,
1456
+ payment_method: "https://a2a.org/x402" /* A2A_X402 */,
1457
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1458
+ processor_response: {
1459
+ network: this.network,
1460
+ settlement_type: "crypto",
1461
+ requires_blockchain_confirmation: true
1462
+ }
1463
+ };
1464
+ }
1465
+ /**
1466
+ * Simulate traditional payment (for testing/fallback)
1467
+ */
1468
+ simulateTraditionalPayment(method, amount, currency) {
1469
+ const paymentId = `sim_${method}_${Date.now().toString(36)}`;
1470
+ const transactionId = `txn_${paymentId}`;
1471
+ console.log(`\u{1F504} Simulating ${method} payment`);
1472
+ return {
1473
+ payment_id: paymentId,
1474
+ transaction_id: transactionId,
1475
+ status: "completed",
1476
+ amount,
1477
+ currency,
1478
+ payment_method: method,
1479
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1480
+ processor_response: {
1481
+ simulation: true,
1482
+ authorization_code: `AUTH_${Math.random().toString(36).substring(2, 10).toUpperCase()}`,
1483
+ network: method === "basic-card" /* BASIC_CARD */ ? "visa" : method,
1484
+ last4: method === "basic-card" /* BASIC_CARD */ ? "4242" : void 0
1485
+ }
1486
+ };
1487
+ }
1488
+ /**
1489
+ * Get payment method configuration status
1490
+ */
1491
+ getPaymentMethodsStatus() {
1492
+ return {
1493
+ ["basic-card" /* BASIC_CARD */]: !!this.credentials.stripe_secret_key,
1494
+ ["https://google.com/pay" /* GOOGLE_PAY */]: !!this.credentials.google_pay_merchant_id,
1495
+ ["https://apple.com/apple-pay" /* APPLE_PAY */]: !!this.credentials.apple_pay_merchant_id,
1496
+ ["https://paypal.com" /* PAYPAL */]: !!this.paypalAccessToken,
1497
+ ["https://a2a.org/x402" /* A2A_X402 */]: true
1498
+ // Always available via wallet
1499
+ };
1500
+ }
1501
+ /**
1502
+ * Get supported payment methods
1503
+ */
1504
+ getSupportedPaymentMethods() {
1505
+ const status = this.getPaymentMethodsStatus();
1506
+ return Object.entries(status).filter(([_, enabled]) => enabled).map(([method, _]) => method);
1507
+ }
1508
+ /**
1509
+ * Validate payment method credentials
1510
+ */
1511
+ async validateCredentials() {
1512
+ const results = {};
1513
+ if (this.credentials.stripe_secret_key) {
1514
+ try {
1515
+ await this.stripeAxiosInstance.get("/balance");
1516
+ results.stripe = true;
1517
+ } catch (e) {
1518
+ results.stripe = false;
1519
+ }
1520
+ }
1521
+ if (this.credentials.paypal_client_id) {
1522
+ results.paypal = !!this.paypalAccessToken;
1523
+ }
1524
+ results.google_pay = !!this.credentials.google_pay_merchant_id;
1525
+ results.apple_pay = !!this.credentials.apple_pay_merchant_id;
1526
+ results.crypto = !!this.wallet;
1527
+ return results;
1528
+ }
1529
+ /**
1530
+ * Create x402 payment request (for crypto payments)
1531
+ */
1532
+ createX402PaymentRequest(fromAgent, toAgent, amount, currency, serviceDescription) {
1533
+ return {
1534
+ payment_id: `x402_${Date.now().toString(36)}`,
1535
+ from_agent: fromAgent,
1536
+ to_agent: toAgent,
1537
+ amount,
1538
+ currency,
1539
+ service_description: serviceDescription,
1540
+ network: this.network,
1541
+ protocol_fee: amount * 0.025,
1542
+ // 2.5% ChaosChain fee
1543
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
1544
+ };
1545
+ }
1546
+ /**
1547
+ * Execute x402 crypto payment (delegated to X402PaymentManager)
1548
+ */
1549
+ executeX402Payment(paymentRequest) {
1550
+ const transactionHash = `0x${Math.random().toString(16).substring(2, 66)}`;
1551
+ return {
1552
+ payment_id: paymentRequest.payment_id,
1553
+ transaction_hash: transactionHash,
1554
+ status: "confirmed",
1555
+ timestamp: /* @__PURE__ */ new Date(),
1556
+ network: this.network,
1557
+ from_address: this.wallet.address,
1558
+ to_address: paymentRequest.to_agent
1559
+ };
1560
+ }
1561
+ /**
1562
+ * Get payment statistics
1563
+ */
1564
+ getPaymentStats() {
1565
+ return {
1566
+ agent_name: this.agentName,
1567
+ network: this.network,
1568
+ wallet_address: this.wallet.address,
1569
+ supported_methods: this.getSupportedPaymentMethods().length,
1570
+ payment_methods_status: this.getPaymentMethodsStatus(),
1571
+ features: {
1572
+ traditional_payments: true,
1573
+ crypto_payments: true,
1574
+ multi_currency: true,
1575
+ instant_settlement: true
1576
+ }
1577
+ };
1578
+ }
1579
+ };
1580
+ var X402Server = class {
1581
+ paymentManager;
1582
+ server = null;
1583
+ endpoints = /* @__PURE__ */ new Map();
1584
+ paymentCache = /* @__PURE__ */ new Map();
1585
+ config;
1586
+ constructor(paymentManager, config) {
1587
+ this.paymentManager = paymentManager;
1588
+ this.config = {
1589
+ port: config.port,
1590
+ host: config.host || "0.0.0.0",
1591
+ defaultCurrency: config.defaultCurrency || "USDC"
1592
+ };
1593
+ console.log(`\u{1F512} X402 Paywall Server initialized on port ${this.config.port}`);
1594
+ }
1595
+ /**
1596
+ * Register a payment-protected endpoint
1597
+ */
1598
+ requirePayment(amount, description, currency) {
1599
+ return (handler) => {
1600
+ const path3 = `/${handler.name || "endpoint"}`;
1601
+ const endpointConfig = {
1602
+ path: path3,
1603
+ amount,
1604
+ currency: currency || this.config.defaultCurrency,
1605
+ description,
1606
+ handler
1607
+ };
1608
+ this.endpoints.set(path3, endpointConfig);
1609
+ console.log(`\u{1F4B0} Registered paywall endpoint: ${path3} (${amount} ${currency || this.config.defaultCurrency})`);
1610
+ return handler;
1611
+ };
1612
+ }
1613
+ /**
1614
+ * Start the HTTP 402 server
1615
+ */
1616
+ start() {
1617
+ if (this.server) {
1618
+ console.warn("\u26A0\uFE0F Server already running");
1619
+ return;
1620
+ }
1621
+ this.server = http__namespace.createServer((req, res) => {
1622
+ this.handleRequest(req, res).catch((error) => {
1623
+ console.error("\u274C Request handler error:", error);
1624
+ res.writeHead(500, { "Content-Type": "application/json" });
1625
+ res.end(JSON.stringify({ error: "Internal server error" }));
1626
+ });
1627
+ });
1628
+ this.server.listen(this.config.port, this.config.host, () => {
1629
+ console.log(`\u{1F680} X402 Paywall Server running at http://${this.config.host}:${this.config.port}`);
1630
+ console.log(`\u{1F4CB} Registered endpoints: ${this.endpoints.size}`);
1631
+ this.endpoints.forEach((config, path3) => {
1632
+ console.log(` - ${path3}: ${config.amount} ${config.currency} - ${config.description}`);
1633
+ });
1634
+ });
1635
+ }
1636
+ /**
1637
+ * Stop the server
1638
+ */
1639
+ stop() {
1640
+ return new Promise((resolve, reject) => {
1641
+ if (!this.server) {
1642
+ resolve();
1643
+ return;
1644
+ }
1645
+ this.server.close((err) => {
1646
+ if (err) {
1647
+ reject(err);
1648
+ } else {
1649
+ console.log("\u{1F6D1} X402 Paywall Server stopped");
1650
+ this.server = null;
1651
+ resolve();
1652
+ }
1653
+ });
1654
+ });
1655
+ }
1656
+ /**
1657
+ * Handle incoming HTTP requests
1658
+ */
1659
+ async handleRequest(req, res) {
1660
+ const url = new URL(req.url || "/", `http://${req.headers.host}`);
1661
+ const path3 = url.pathname;
1662
+ const endpointConfig = this.endpoints.get(path3);
1663
+ if (!endpointConfig) {
1664
+ res.writeHead(404, { "Content-Type": "application/json" });
1665
+ res.end(JSON.stringify({ error: "Endpoint not found" }));
1666
+ return;
1667
+ }
1668
+ const paymentToken = req.headers["x-payment-token"];
1669
+ const paymentTxHash = req.headers["x-payment-tx"];
1670
+ if (!paymentToken && !paymentTxHash) {
1671
+ this.sendPaymentRequired(res, endpointConfig);
1672
+ return;
1673
+ }
1674
+ const isValidPayment = await this.verifyPayment(paymentToken || paymentTxHash, endpointConfig);
1675
+ if (!isValidPayment) {
1676
+ res.writeHead(402, { "Content-Type": "application/json" });
1677
+ res.end(JSON.stringify({ error: "Invalid or insufficient payment" }));
1678
+ return;
1679
+ }
1680
+ try {
1681
+ let requestData = {};
1682
+ if (req.method === "POST" || req.method === "PUT") {
1683
+ const chunks = [];
1684
+ req.on("data", (chunk) => chunks.push(chunk));
1685
+ await new Promise((resolve) => req.on("end", resolve));
1686
+ const body = Buffer.concat(chunks).toString();
1687
+ requestData = body ? JSON.parse(body) : {};
1688
+ }
1689
+ const result = await endpointConfig.handler(requestData);
1690
+ res.writeHead(200, { "Content-Type": "application/json" });
1691
+ res.end(JSON.stringify({ success: true, data: result }));
1692
+ } catch (error) {
1693
+ res.writeHead(500, { "Content-Type": "application/json" });
1694
+ res.end(JSON.stringify({ error: error.message }));
1695
+ }
1696
+ }
1697
+ /**
1698
+ * Send HTTP 402 Payment Required response
1699
+ */
1700
+ sendPaymentRequired(res, endpointConfig) {
1701
+ const paymentRequirements = this.paymentManager.createPaymentRequirements(
1702
+ endpointConfig.amount,
1703
+ endpointConfig.currency,
1704
+ endpointConfig.description
1705
+ );
1706
+ const response = {
1707
+ error: "Payment Required",
1708
+ payment_required: true,
1709
+ payment_requirements: paymentRequirements,
1710
+ instructions: {
1711
+ step_1: "Execute payment using x402 protocol",
1712
+ step_2: "Include payment transaction hash in X-Payment-Tx header",
1713
+ step_3: "Retry request with payment proof"
1714
+ }
1715
+ };
1716
+ res.writeHead(402, {
1717
+ "Content-Type": "application/json",
1718
+ "X-Payment-Required": "true",
1719
+ "X-Payment-Amount": endpointConfig.amount.toString(),
1720
+ "X-Payment-Currency": endpointConfig.currency,
1721
+ "X-Payment-Address": paymentRequirements.settlement_address
1722
+ });
1723
+ res.end(JSON.stringify(response));
1724
+ }
1725
+ /**
1726
+ * Verify payment
1727
+ */
1728
+ async verifyPayment(paymentIdentifier, endpointConfig) {
1729
+ try {
1730
+ const cachedPayment = this.paymentCache.get(paymentIdentifier);
1731
+ if (cachedPayment) {
1732
+ if (cachedPayment.amount >= endpointConfig.amount && cachedPayment.currency === endpointConfig.currency) {
1733
+ console.log(`\u2705 Payment verified from cache: ${paymentIdentifier}`);
1734
+ return true;
1735
+ }
1736
+ }
1737
+ if (paymentIdentifier.startsWith("0x") && paymentIdentifier.length === 66) {
1738
+ const mockProof = {
1739
+ payment_id: paymentIdentifier,
1740
+ transaction_hash: paymentIdentifier,
1741
+ main_transaction_hash: paymentIdentifier,
1742
+ from_address: "0x0000000000000000000000000000000000000000",
1743
+ to_address: "0x0000000000000000000000000000000000000000",
1744
+ treasury_address: "0x0000000000000000000000000000000000000000",
1745
+ amount: endpointConfig.amount,
1746
+ currency: endpointConfig.currency,
1747
+ protocol_fee: 0,
1748
+ network: "base-sepolia",
1749
+ chain_id: 84532,
1750
+ timestamp: /* @__PURE__ */ new Date(),
1751
+ status: "confirmed",
1752
+ confirmations: 1
1753
+ };
1754
+ const isValid = await this.paymentManager.verifyPayment(mockProof);
1755
+ if (isValid) {
1756
+ this.paymentCache.set(paymentIdentifier, mockProof);
1757
+ console.log(`\u2705 Payment verified on-chain: ${paymentIdentifier}`);
1758
+ return true;
1759
+ }
1760
+ }
1761
+ console.error(`\u274C Payment verification failed: ${paymentIdentifier}`);
1762
+ return false;
1763
+ } catch (error) {
1764
+ console.error(`\u274C Payment verification error: ${error}`);
1765
+ return false;
1766
+ }
1767
+ }
1768
+ /**
1769
+ * Get server statistics
1770
+ */
1771
+ getServerStats() {
1772
+ return {
1773
+ running: !!this.server,
1774
+ port: this.config.port,
1775
+ host: this.config.host,
1776
+ endpoints: Array.from(this.endpoints.entries()).map(([path3, config]) => ({
1777
+ path: path3,
1778
+ amount: config.amount,
1779
+ currency: config.currency,
1780
+ description: config.description
1781
+ })),
1782
+ payments_cached: this.paymentCache.size,
1783
+ default_currency: this.config.defaultCurrency
1784
+ };
1785
+ }
1786
+ /**
1787
+ * Clear payment cache
1788
+ */
1789
+ clearPaymentCache() {
1790
+ this.paymentCache.clear();
1791
+ console.log("\u{1F5D1}\uFE0F Payment cache cleared");
1792
+ }
1793
+ };
1794
+ var GoogleAP2Integration = class {
1795
+ agentName;
1796
+ privateKey;
1797
+ publicKey;
1798
+ merchantPrivateKey;
1799
+ constructor(agentName, merchantPrivateKey) {
1800
+ this.agentName = agentName;
1801
+ this.merchantPrivateKey = merchantPrivateKey || "demo_private_key_123";
1802
+ const keypair = this.getOrGenerateRsaKeypair();
1803
+ this.privateKey = keypair.privateKey;
1804
+ this.publicKey = keypair.publicKey;
1805
+ console.log(`\u2705 Google AP2 Integration initialized for ${agentName}`);
1806
+ }
1807
+ /**
1808
+ * Generate or load RSA keypair for production JWT signing
1809
+ */
1810
+ getOrGenerateRsaKeypair() {
1811
+ const keyDir = path2__namespace.join(process.cwd(), "keys");
1812
+ const privateKeyPath = path2__namespace.join(keyDir, `${this.agentName}_ap2_private.pem`);
1813
+ const publicKeyPath = path2__namespace.join(keyDir, `${this.agentName}_ap2_public.pem`);
1814
+ if (!fs2__namespace.existsSync(keyDir)) {
1815
+ fs2__namespace.mkdirSync(keyDir, { recursive: true });
1816
+ }
1817
+ if (fs2__namespace.existsSync(privateKeyPath) && fs2__namespace.existsSync(publicKeyPath)) {
1818
+ try {
1819
+ const privateKeyPem = fs2__namespace.readFileSync(privateKeyPath, "utf-8");
1820
+ const publicKeyPem = fs2__namespace.readFileSync(publicKeyPath, "utf-8");
1821
+ const privateKey2 = crypto__namespace.createPrivateKey(privateKeyPem);
1822
+ console.log(`\u{1F511} Loaded existing RSA keypair for ${this.agentName}`);
1823
+ return { privateKey: privateKey2, publicKey: publicKeyPem };
1824
+ } catch (e) {
1825
+ console.warn(`\u26A0\uFE0F Failed to load existing keys: ${e}`);
1826
+ }
1827
+ }
1828
+ console.log(`\u{1F511} Generating new RSA keypair for ${this.agentName}`);
1829
+ const { privateKey, publicKey } = crypto__namespace.generateKeyPairSync("rsa", {
1830
+ modulusLength: 2048,
1831
+ publicKeyEncoding: {
1832
+ type: "spki",
1833
+ format: "pem"
1834
+ },
1835
+ privateKeyEncoding: {
1836
+ type: "pkcs8",
1837
+ format: "pem"
1838
+ }
1839
+ });
1840
+ try {
1841
+ fs2__namespace.writeFileSync(privateKeyPath, privateKey);
1842
+ fs2__namespace.writeFileSync(publicKeyPath, publicKey);
1843
+ console.log(`\u{1F4BE} RSA keypair saved to ${keyDir}`);
1844
+ } catch (e) {
1845
+ console.warn(`\u26A0\uFE0F Failed to save keys: ${e}`);
1846
+ }
1847
+ return {
1848
+ privateKey: crypto__namespace.createPrivateKey(privateKey),
1849
+ publicKey
1850
+ };
1851
+ }
1852
+ /**
1853
+ * Create an IntentMandate using Google's official AP2 types
1854
+ */
1855
+ createIntentMandate(userDescription, merchants, skus, requiresRefundability = false, expiryMinutes = 60) {
1856
+ try {
1857
+ const expiryTime = new Date(Date.now() + expiryMinutes * 60 * 1e3);
1858
+ const intentMandate = {
1859
+ user_cart_confirmation_required: true,
1860
+ natural_language_description: userDescription,
1861
+ merchants,
1862
+ skus,
1863
+ requires_refundability: requiresRefundability,
1864
+ intent_expiry: expiryTime.toISOString()
1865
+ };
1866
+ console.log(`\u{1F4DD} Created Google AP2 IntentMandate`);
1867
+ console.log(` Description: ${userDescription}`);
1868
+ console.log(` Expires: ${expiryTime.toISOString()}`);
1869
+ return {
1870
+ intent_mandate: intentMandate,
1871
+ success: true
1872
+ };
1873
+ } catch (e) {
1874
+ console.error(`\u274C Failed to create IntentMandate: ${e}`);
1875
+ return {
1876
+ success: false,
1877
+ error: String(e)
1878
+ };
1879
+ }
1880
+ }
1881
+ /**
1882
+ * Create a CartMandate using Google's official AP2 types with JWT signing
1883
+ */
1884
+ async createCartMandate(cartId, items, totalAmount, currency = "USD", merchantName, expiryMinutes = 15) {
1885
+ try {
1886
+ const expiryTime = new Date(Date.now() + expiryMinutes * 60 * 1e3);
1887
+ const paymentItems = items.map((item) => ({
1888
+ label: item.name,
1889
+ amount: {
1890
+ currency,
1891
+ value: item.price
1892
+ }
1893
+ }));
1894
+ const totalItem = {
1895
+ label: "Total",
1896
+ amount: {
1897
+ currency,
1898
+ value: totalAmount
1899
+ }
1900
+ };
1901
+ const methodData = [
1902
+ {
1903
+ supported_methods: "basic-card",
1904
+ data: { supportedNetworks: ["visa", "mastercard"] }
1905
+ },
1906
+ {
1907
+ supported_methods: "google-pay",
1908
+ data: { environment: "TEST" }
1909
+ },
1910
+ {
1911
+ supported_methods: "crypto",
1912
+ data: { supportedCurrencies: ["USDC", "ETH"] }
1913
+ }
1914
+ ];
1915
+ const paymentRequest = {
1916
+ method_data: methodData,
1917
+ details: {
1918
+ id: `payment_${cartId}`,
1919
+ display_items: paymentItems,
1920
+ total: totalItem
1921
+ }
1922
+ };
1923
+ const cartContents = {
1924
+ id: cartId,
1925
+ user_cart_confirmation_required: true,
1926
+ payment_request: paymentRequest,
1927
+ cart_expiry: expiryTime.toISOString(),
1928
+ merchant_name: merchantName || this.agentName
1929
+ };
1930
+ const jwtToken = await this.createMerchantJwt(cartContents);
1931
+ const cartMandate = {
1932
+ contents: cartContents,
1933
+ merchant_authorization: jwtToken
1934
+ };
1935
+ console.log(`\u{1F6D2} Created Google AP2 CartMandate with JWT`);
1936
+ console.log(` Cart ID: ${cartId}`);
1937
+ console.log(` Items: ${items.length} items, Total: ${totalAmount} ${currency}`);
1938
+ console.log(` JWT: ${jwtToken.slice(0, 50)}...`);
1939
+ return {
1940
+ cart_mandate: cartMandate,
1941
+ jwt_token: jwtToken,
1942
+ success: true
1943
+ };
1944
+ } catch (e) {
1945
+ console.error(`\u274C Failed to create CartMandate: ${e}`);
1946
+ return {
1947
+ success: false,
1948
+ error: String(e)
1949
+ };
1950
+ }
1951
+ }
1952
+ /**
1953
+ * Create a JWT token for merchant authorization as per Google's AP2 spec
1954
+ */
1955
+ async createMerchantJwt(cartContents) {
1956
+ const cartJson = JSON.stringify(cartContents);
1957
+ const cartHash = crypto__namespace.createHash("sha256").update(cartJson).digest("hex");
1958
+ const now = Math.floor(Date.now() / 1e3);
1959
+ const payload = {
1960
+ iss: `did:chaoschain:${this.agentName}`,
1961
+ // Issuer (DID format)
1962
+ sub: cartContents.id,
1963
+ // Subject (cart ID)
1964
+ aud: "chaoschain:payment_processor",
1965
+ // Audience
1966
+ iat: now,
1967
+ // Issued at
1968
+ exp: now + 15 * 60,
1969
+ // Expires (15 minutes)
1970
+ jti: `jwt_${cartContents.id}_${now}`,
1971
+ // JWT ID
1972
+ cart_hash: cartHash,
1973
+ // Cart integrity hash
1974
+ merchant_name: cartContents.merchant_name
1975
+ };
1976
+ const jwt = await new jose__namespace.SignJWT(payload).setProtectedHeader({
1977
+ alg: "RS256",
1978
+ kid: `did:chaoschain:${this.agentName}#key-1`
1979
+ }).sign(this.privateKey);
1980
+ return jwt;
1981
+ }
1982
+ /**
1983
+ * Verify a JWT token (for validation purposes)
1984
+ */
1985
+ async verifyJwtToken(token) {
1986
+ try {
1987
+ const publicKey = crypto__namespace.createPublicKey(this.publicKey);
1988
+ const { payload } = await jose__namespace.jwtVerify(token, publicKey, {
1989
+ algorithms: ["RS256"],
1990
+ audience: "chaoschain:payment_processor"
1991
+ });
1992
+ console.log(`\u2705 JWT token verified successfully with RSA256`);
1993
+ return payload;
1994
+ } catch (e) {
1995
+ if (e.code === "ERR_JWT_EXPIRED") {
1996
+ console.error(`\u274C JWT token has expired`);
1997
+ } else if (e.code === "ERR_JWT_CLAIM_VALIDATION_FAILED") {
1998
+ console.error(`\u274C JWT token has invalid audience`);
1999
+ } else {
2000
+ console.error(`\u274C JWT token is invalid: ${e}`);
2001
+ }
2002
+ return {};
2003
+ }
2004
+ }
2005
+ /**
2006
+ * Get a summary of the Google AP2 integration capabilities
2007
+ */
2008
+ getIntegrationSummary() {
2009
+ return {
2010
+ integration_type: "Google Official AP2",
2011
+ agent_name: this.agentName,
2012
+ supported_features: [
2013
+ "IntentMandate creation with Google types",
2014
+ "CartMandate creation with JWT signing",
2015
+ "W3C PaymentRequest API compliance",
2016
+ "Multi-payment method support",
2017
+ "JWT-based merchant authorization",
2018
+ "Proper expiry handling",
2019
+ "Cart integrity verification"
2020
+ ],
2021
+ cryptographic_features: [
2022
+ "JWT signing with RS256 (production)",
2023
+ "Cart content hashing for integrity",
2024
+ "Timestamp-based expiry",
2025
+ "Replay attack prevention with JTI"
2026
+ ],
2027
+ compliance: ["Google AP2 Protocol", "W3C Payment Request API", "JWT RFC 7519", "ISO 8601 timestamps"]
2028
+ };
2029
+ }
2030
+ };
2031
+
2032
+ // src/A2AX402Extension.ts
2033
+ var A2AX402Extension = class {
2034
+ agentName;
2035
+ network;
2036
+ paymentManager;
2037
+ supportedCryptoMethods;
2038
+ supportedNetworks;
2039
+ w3cPaymentMethods;
2040
+ constructor(agentName, network, paymentManager) {
2041
+ this.agentName = agentName;
2042
+ this.network = network;
2043
+ this.paymentManager = paymentManager;
2044
+ this.supportedCryptoMethods = ["usdc", "eth", "native"];
2045
+ this.supportedNetworks = ["base-sepolia", "ethereum-sepolia", "optimism-sepolia"];
2046
+ this.w3cPaymentMethods = this.initializeW3cPaymentMethods();
2047
+ console.log(`\u2705 A2A-x402 Extension initialized for ${agentName} on ${network}`);
2048
+ console.log(`\u{1F4B3} Multi-payment support: ${this.w3cPaymentMethods.length} methods available`);
2049
+ }
2050
+ /**
2051
+ * Initialize W3C Payment Request API compliant payment methods
2052
+ */
2053
+ initializeW3cPaymentMethods() {
2054
+ const methods = [];
2055
+ methods.push({
2056
+ supported_methods: "basic-card",
2057
+ data: {
2058
+ supportedNetworks: ["visa", "mastercard", "amex", "discover"],
2059
+ supportedTypes: ["credit", "debit"]
2060
+ }
2061
+ });
2062
+ methods.push({
2063
+ supported_methods: "https://google.com/pay",
2064
+ data: {
2065
+ environment: "PRODUCTION",
2066
+ apiVersion: 2,
2067
+ apiVersionMinor: 0,
2068
+ allowedPaymentMethods: [
2069
+ {
2070
+ type: "CARD",
2071
+ parameters: {
2072
+ allowedAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"],
2073
+ allowedCardNetworks: ["AMEX", "DISCOVER", "JCB", "MASTERCARD", "VISA"]
2074
+ }
2075
+ }
2076
+ ]
2077
+ }
2078
+ });
2079
+ methods.push({
2080
+ supported_methods: "https://apple.com/apple-pay",
2081
+ data: {
2082
+ version: 3,
2083
+ merchantIdentifier: `merchant.chaoschain.${this.agentName.toLowerCase()}`,
2084
+ merchantCapabilities: ["supports3DS"],
2085
+ supportedNetworks: ["visa", "masterCard", "amex", "discover"]
2086
+ }
2087
+ });
2088
+ methods.push({
2089
+ supported_methods: "https://a2a.org/x402",
2090
+ data: {
2091
+ supportedCryptocurrencies: this.supportedCryptoMethods,
2092
+ supportedNetworks: this.supportedNetworks,
2093
+ settlementAddress: "dynamic",
2094
+ protocolVersion: "x402-v1.0"
2095
+ }
2096
+ });
2097
+ methods.push({
2098
+ supported_methods: "https://paypal.com",
2099
+ data: {
2100
+ environment: "sandbox",
2101
+ intent: "capture"
2102
+ }
2103
+ });
2104
+ return methods;
2105
+ }
2106
+ /**
2107
+ * Create x402 payment method descriptor with W3C compliance
2108
+ */
2109
+ createX402PaymentMethod(settlementAddress) {
2110
+ const w3cMethods = this.w3cPaymentMethods.map((method) => method.supported_methods);
2111
+ return {
2112
+ supported_methods: w3cMethods,
2113
+ supported_networks: this.supportedNetworks,
2114
+ payment_endpoint: `x402://${this.agentName}.chaoschain.com/pay`,
2115
+ verification_endpoint: `https://${this.agentName}.chaoschain.com/verify`,
2116
+ method_data: {
2117
+ w3c_methods: this.w3cPaymentMethods.map((method) => ({
2118
+ supportedMethods: method.supported_methods,
2119
+ data: method.data
2120
+ })),
2121
+ crypto_settlement_address: settlementAddress
2122
+ }
2123
+ };
2124
+ }
2125
+ /**
2126
+ * Create enhanced payment request with x402 crypto support
2127
+ */
2128
+ createEnhancedPaymentRequest(cartId, totalAmount, currency, items, settlementAddress) {
2129
+ const x402Methods = [this.createX402PaymentMethod(settlementAddress)];
2130
+ const paymentRequest = {
2131
+ id: `x402_${cartId}_${Date.now().toString(36)}`,
2132
+ total: {
2133
+ amount: { value: totalAmount.toString(), currency },
2134
+ label: `Payment for ${items.length} items`
2135
+ },
2136
+ display_items: items.map((item) => ({
2137
+ label: item.name || item.service || "Item",
2138
+ amount: { value: (item.price || 0).toString(), currency }
2139
+ })),
2140
+ x402_methods: x402Methods,
2141
+ settlement_address: settlementAddress,
2142
+ network: this.network,
2143
+ expires_at: new Date(Date.now() + 30 * 60 * 1e3).toISOString()
2144
+ };
2145
+ console.log(`\u{1F4B3} Created x402 payment request: ${paymentRequest.id}`);
2146
+ return paymentRequest;
2147
+ }
2148
+ /**
2149
+ * Execute x402 crypto payment using the real payment manager
2150
+ */
2151
+ async executeX402Payment(paymentRequest, payerAgent, serviceDescription = "A2A Service") {
2152
+ console.log(`\u{1F4B8} Executing x402 payment: ${payerAgent} \u2192 ${this.agentName}`);
2153
+ const amount = parseFloat(paymentRequest.total.amount.value);
2154
+ const currency = paymentRequest.total.amount.currency;
2155
+ const pmPaymentRequest = this.paymentManager.createX402PaymentRequest(
2156
+ payerAgent,
2157
+ this.agentName,
2158
+ amount,
2159
+ currency,
2160
+ serviceDescription
2161
+ );
2162
+ const paymentProof = this.paymentManager.executeX402Payment(pmPaymentRequest);
2163
+ const response = {
2164
+ payment_id: paymentProof.payment_id,
2165
+ transaction_hash: paymentProof.transaction_hash,
2166
+ network: this.network,
2167
+ amount,
2168
+ currency,
2169
+ settlement_address: paymentRequest.settlement_address,
2170
+ confirmation_blocks: 1,
2171
+ status: "confirmed",
2172
+ timestamp: paymentProof.timestamp.toISOString(),
2173
+ gas_fee: void 0,
2174
+ protocol_fee: pmPaymentRequest.protocol_fee
2175
+ };
2176
+ console.log(`\u2705 x402 payment confirmed: ${response.transaction_hash}`);
2177
+ return response;
2178
+ }
2179
+ /**
2180
+ * Execute traditional payment (cards, Google Pay, Apple Pay, etc.)
2181
+ */
2182
+ executeTraditionalPayment(paymentMethod, amount, currency, paymentData2) {
2183
+ console.log(`\u{1F4B3} Processing ${paymentMethod} payment: $${amount} ${currency}`);
2184
+ if (this.paymentManager) {
2185
+ let methodEnum;
2186
+ if (paymentMethod === "basic-card") {
2187
+ methodEnum = "basic-card" /* BASIC_CARD */;
2188
+ } else if (paymentMethod === "https://google.com/pay") {
2189
+ methodEnum = "https://google.com/pay" /* GOOGLE_PAY */;
2190
+ } else if (paymentMethod === "https://apple.com/apple-pay") {
2191
+ methodEnum = "https://apple.com/apple-pay" /* APPLE_PAY */;
2192
+ } else if (paymentMethod === "https://paypal.com") {
2193
+ methodEnum = "https://paypal.com" /* PAYPAL */;
2194
+ } else if (paymentMethod === "https://a2a.org/x402") {
2195
+ methodEnum = "https://a2a.org/x402" /* A2A_X402 */;
2196
+ }
2197
+ if (methodEnum) {
2198
+ const result = this.paymentManager.executeTraditionalPayment(methodEnum, amount, currency, paymentData2);
2199
+ return {
2200
+ payment_id: result.payment_id,
2201
+ method: paymentMethod,
2202
+ amount,
2203
+ currency,
2204
+ status: result.status,
2205
+ transaction_id: result.transaction_id,
2206
+ authorization_code: result.processor_response?.authorization_code,
2207
+ timestamp: result.timestamp,
2208
+ receipt_data: result.processor_response
2209
+ };
2210
+ }
2211
+ }
2212
+ const paymentId = `trad_${Date.now().toString(36)}`;
2213
+ return {
2214
+ payment_id: paymentId,
2215
+ method: paymentMethod,
2216
+ amount,
2217
+ currency,
2218
+ status: "failed",
2219
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2220
+ receipt_data: { error: "Unsupported payment method" }
2221
+ };
2222
+ }
2223
+ /**
2224
+ * Verify x402 payment on-chain
2225
+ */
2226
+ verifyX402Payment(paymentResponse) {
2227
+ return paymentResponse.status === "confirmed" && !!paymentResponse.transaction_hash && paymentResponse.transaction_hash.length === 66;
2228
+ }
2229
+ /**
2230
+ * Create cryptographic proof of x402 payment
2231
+ */
2232
+ createPaymentProof(paymentResponse) {
2233
+ const proofData = {
2234
+ payment_id: paymentResponse.payment_id,
2235
+ transaction_hash: paymentResponse.transaction_hash,
2236
+ network: paymentResponse.network,
2237
+ amount: paymentResponse.amount,
2238
+ currency: paymentResponse.currency,
2239
+ settlement_address: paymentResponse.settlement_address,
2240
+ timestamp: paymentResponse.timestamp,
2241
+ agent_payer: "unknown",
2242
+ agent_payee: this.agentName
2243
+ };
2244
+ const proofJson = JSON.stringify(proofData);
2245
+ const crypto2 = __require("crypto");
2246
+ const proofHash = crypto2.createHash("sha256").update(proofJson).digest("hex");
2247
+ return {
2248
+ proof_type: "a2a_x402_payment",
2249
+ proof_hash: proofHash,
2250
+ proof_data: proofData,
2251
+ verification_method: "on_chain_transaction",
2252
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
2253
+ };
2254
+ }
2255
+ /**
2256
+ * Get A2A-x402 extension capabilities with W3C Payment Request API compliance
2257
+ */
2258
+ getExtensionCapabilities() {
2259
+ return {
2260
+ extension_name: "a2a-x402-multi-payment",
2261
+ version: "1.0.0",
2262
+ w3c_payment_methods: this.w3cPaymentMethods.map((m) => m.supported_methods),
2263
+ supported_crypto_methods: this.supportedCryptoMethods,
2264
+ supported_networks: this.supportedNetworks,
2265
+ features: [
2266
+ "w3c_payment_request_api",
2267
+ "multi_payment_methods",
2268
+ "basic_card_support",
2269
+ "google_pay_integration",
2270
+ "apple_pay_integration",
2271
+ "paypal_integration",
2272
+ "crypto_payments",
2273
+ "instant_settlement",
2274
+ "on_chain_verification",
2275
+ "protocol_fees",
2276
+ "gas_optimization",
2277
+ "multi_network_support"
2278
+ ],
2279
+ compliance: [
2280
+ "W3C Payment Request API",
2281
+ "A2A-x402 Specification v0.1",
2282
+ "Google Pay API v2",
2283
+ "Apple Pay JS API v3",
2284
+ "PayPal Checkout API",
2285
+ "EIP-20 Token Standard",
2286
+ "HTTP 402 Payment Required"
2287
+ ],
2288
+ payment_processors: {
2289
+ traditional: ["simulated_processor", "google_pay", "apple_pay", "paypal"],
2290
+ crypto: ["chaoschain_x402", "base_sepolia", "ethereum"]
2291
+ }
2292
+ };
2293
+ }
2294
+ };
2295
+ var ProcessIntegrity = class {
2296
+ agentName;
2297
+ storageManager;
2298
+ computeProvider;
2299
+ registeredFunctions;
2300
+ functionHashes;
2301
+ constructor(agentName, storageManager = null, computeProvider = null) {
2302
+ this.agentName = agentName;
2303
+ this.storageManager = storageManager;
2304
+ this.computeProvider = computeProvider;
2305
+ this.registeredFunctions = /* @__PURE__ */ new Map();
2306
+ this.functionHashes = /* @__PURE__ */ new Map();
2307
+ const verificationMode = !computeProvider ? "local" : "local + TEE attestation";
2308
+ console.log(
2309
+ `\u2705 ChaosChain Process Integrity Verifier initialized: ${agentName} (${verificationMode})`
2310
+ );
2311
+ }
2312
+ /**
2313
+ * Register a function for integrity checking.
2314
+ */
2315
+ registerFunction(func, functionName) {
2316
+ const name = functionName || func.name;
2317
+ const codeHash = this.generateCodeHash(func);
2318
+ this.registeredFunctions.set(name, func);
2319
+ this.functionHashes.set(name, codeHash);
2320
+ console.log(`\u{1F4DD} Registered integrity-checked function: ${name}`);
2321
+ console.log(` Code hash: ${codeHash.slice(0, 16)}...`);
2322
+ return codeHash;
2323
+ }
2324
+ /**
2325
+ * Execute a registered function with integrity proof generation.
2326
+ */
2327
+ async executeWithProof(functionName, inputs, requireProof = true, useTee = true) {
2328
+ if (!this.registeredFunctions.has(functionName)) {
2329
+ const available = Array.from(this.registeredFunctions.keys());
2330
+ throw new IntegrityVerificationError(`Function not registered: ${functionName}`, {
2331
+ available_functions: available
2332
+ });
2333
+ }
2334
+ const func = this.registeredFunctions.get(functionName);
2335
+ const codeHash = this.functionHashes.get(functionName);
2336
+ const executionMode = useTee && this.computeProvider ? "local + TEE" : "local";
2337
+ console.log(`\u26A1 Executing with ChaosChain Process Integrity: ${functionName} (${executionMode})`);
2338
+ const startTime = /* @__PURE__ */ new Date();
2339
+ let teeAttestation = null;
2340
+ try {
2341
+ const result = await func(inputs);
2342
+ const executionTime = /* @__PURE__ */ new Date();
2343
+ if (useTee && this.computeProvider) {
2344
+ try {
2345
+ teeAttestation = await this.getTeeAttestation(functionName, inputs, result);
2346
+ } catch (e) {
2347
+ console.warn(`\u26A0\uFE0F TEE attestation failed (continuing with local proof): ${e}`);
2348
+ }
2349
+ }
2350
+ if (!requireProof) {
2351
+ return [result, null];
2352
+ }
2353
+ const proof = this.generateIntegrityProof(
2354
+ functionName,
2355
+ codeHash,
2356
+ inputs,
2357
+ result,
2358
+ startTime,
2359
+ executionTime,
2360
+ teeAttestation
2361
+ );
2362
+ if (this.storageManager) {
2363
+ await this.storeProofOnIpfs(proof);
2364
+ }
2365
+ return [result, proof];
2366
+ } catch (e) {
2367
+ throw new IntegrityVerificationError(`Function execution failed: ${e}`, {
2368
+ function_name: functionName,
2369
+ inputs
2370
+ });
2371
+ }
2372
+ }
2373
+ /**
2374
+ * Generate a hash of the function's code.
2375
+ */
2376
+ generateCodeHash(func) {
2377
+ try {
2378
+ const sourceCode = func.toString();
2379
+ return crypto.createHash("sha256").update(sourceCode).digest("hex");
2380
+ } catch {
2381
+ const funcInfo = `${func.name}`;
2382
+ return crypto.createHash("sha256").update(funcInfo).digest("hex");
2383
+ }
2384
+ }
2385
+ /**
2386
+ * Get TEE attestation from compute provider (e.g., 0G Compute).
2387
+ */
2388
+ async getTeeAttestation(functionName, inputs, result) {
2389
+ if (!this.computeProvider) {
2390
+ return null;
2391
+ }
2392
+ console.log(`\u{1F510} Requesting TEE attestation from compute provider...`);
2393
+ try {
2394
+ const taskData = {
2395
+ function: functionName,
2396
+ inputs,
2397
+ model: "gpt-oss-120b",
2398
+ // Default model for 0G Compute
2399
+ prompt: `Execute function: ${functionName} with inputs: ${JSON.stringify(inputs)}`
2400
+ };
2401
+ const jobId = await this.computeProvider.submit(taskData);
2402
+ const maxWait = 6e4;
2403
+ const startWait = Date.now();
2404
+ while (Date.now() - startWait < maxWait) {
2405
+ const statusResult = await this.computeProvider.status(jobId);
2406
+ const state = statusResult.state || "unknown";
2407
+ if (state === "completed") {
2408
+ const computeResult = await this.computeProvider.result(jobId);
2409
+ if (computeResult.success) {
2410
+ const attestationData = await this.computeProvider.attestation(jobId);
2411
+ console.log(`\u2705 TEE attestation received: ${jobId}`);
2412
+ console.log(` Execution Hash: ${computeResult.execution_hash}`);
2413
+ console.log(` Verification: ${computeResult.verification_method.value}`);
2414
+ return {
2415
+ job_id: jobId,
2416
+ provider: "0g-compute",
2417
+ execution_hash: computeResult.execution_hash,
2418
+ // TEE execution ID
2419
+ verification_method: computeResult.verification_method.value,
2420
+ model: taskData.model,
2421
+ attestation_data: attestationData,
2422
+ // Full attestation proof
2423
+ proof: computeResult.proof?.toString("hex"),
2424
+ metadata: computeResult.metadata,
2425
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2426
+ };
2427
+ } else {
2428
+ console.warn(`\u26A0\uFE0F Compute result failed: ${computeResult.error}`);
2429
+ return null;
2430
+ }
2431
+ } else if (state === "failed") {
2432
+ console.warn(`\u26A0\uFE0F TEE execution failed`);
2433
+ return null;
2434
+ }
2435
+ await new Promise((resolve) => setTimeout(resolve, 2e3));
2436
+ }
2437
+ console.warn(`\u26A0\uFE0F TEE attestation timeout after ${maxWait}ms`);
2438
+ return null;
2439
+ } catch (e) {
2440
+ console.warn(`\u26A0\uFE0F TEE attestation error: ${e}`);
2441
+ return null;
2442
+ }
2443
+ }
2444
+ /**
2445
+ * Generate a cryptographic integrity proof.
2446
+ */
2447
+ generateIntegrityProof(functionName, codeHash, inputs, result, startTime, executionTime, teeAttestation) {
2448
+ const proofId = `proof_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
2449
+ const executionData = {
2450
+ function_name: functionName,
2451
+ code_hash: codeHash,
2452
+ inputs,
2453
+ result: this.serializeResult(result),
2454
+ start_time: startTime.toISOString(),
2455
+ execution_time: executionTime.toISOString(),
2456
+ agent_name: this.agentName
2457
+ };
2458
+ const executionHash = crypto.createHash("sha256").update(JSON.stringify(executionData)).digest("hex");
2459
+ const proof = {
2460
+ proof_id: proofId,
2461
+ function_name: functionName,
2462
+ code_hash: codeHash,
2463
+ execution_hash: executionHash,
2464
+ timestamp: executionTime,
2465
+ agent_name: this.agentName,
2466
+ verification_status: "verified",
2467
+ ipfs_cid: void 0,
2468
+ // TEE fields (if available)
2469
+ tee_attestation: teeAttestation || void 0,
2470
+ tee_provider: teeAttestation?.provider,
2471
+ tee_job_id: teeAttestation?.job_id,
2472
+ tee_execution_hash: teeAttestation?.execution_hash
2473
+ };
2474
+ const verificationLevel = teeAttestation ? "local + TEE" : "local";
2475
+ console.log(`\u2705 Process integrity proof generated: ${proofId} (${verificationLevel})`);
2476
+ return proof;
2477
+ }
2478
+ /**
2479
+ * Store integrity proof on IPFS for persistence.
2480
+ */
2481
+ async storeProofOnIpfs(proof) {
2482
+ if (!this.storageManager) return;
2483
+ try {
2484
+ const proofData = {
2485
+ type: "chaoschain_process_integrity_proof_v2",
2486
+ // v2 includes TEE
2487
+ proof: {
2488
+ proof_id: proof.proof_id,
2489
+ function_name: proof.function_name,
2490
+ code_hash: proof.code_hash,
2491
+ execution_hash: proof.execution_hash,
2492
+ timestamp: proof.timestamp.toISOString(),
2493
+ agent_name: proof.agent_name,
2494
+ verification_status: proof.verification_status,
2495
+ // TEE attestation (if available)
2496
+ tee_attestation: proof.tee_attestation,
2497
+ tee_provider: proof.tee_provider,
2498
+ tee_job_id: proof.tee_job_id,
2499
+ tee_execution_hash: proof.tee_execution_hash
2500
+ },
2501
+ verification_layers: {
2502
+ local_code_hash: true,
2503
+ tee_attestation: !!proof.tee_attestation
2504
+ },
2505
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2506
+ agent_name: this.agentName
2507
+ };
2508
+ const filename = `process_integrity_proof_${proof.proof_id}.json`;
2509
+ const cid = await this.storageManager.uploadJson(proofData, filename);
2510
+ if (cid) {
2511
+ proof.ipfs_cid = cid;
2512
+ console.log(`\u{1F4C1} Process Integrity Proof stored on IPFS: ${cid}`);
2513
+ }
2514
+ } catch (e) {
2515
+ console.warn(`\u26A0\uFE0F Failed to store process integrity proof on IPFS: ${e}`);
2516
+ }
2517
+ }
2518
+ /**
2519
+ * Serialize function result for hashing.
2520
+ */
2521
+ serializeResult(result) {
2522
+ try {
2523
+ JSON.stringify(result);
2524
+ return result;
2525
+ } catch {
2526
+ return String(result);
2527
+ }
2528
+ }
2529
+ /**
2530
+ * Create a process insurance policy for a function.
2531
+ */
2532
+ createInsurancePolicy(functionName, coverageAmount, conditions) {
2533
+ const policyId = `policy_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
2534
+ const policy = {
2535
+ policy_id: policyId,
2536
+ function_name: functionName,
2537
+ agent_name: this.agentName,
2538
+ coverage_amount: coverageAmount,
2539
+ conditions,
2540
+ created_at: (/* @__PURE__ */ new Date()).toISOString(),
2541
+ status: "active"
2542
+ };
2543
+ console.log(`\u{1F6E1}\uFE0F Process insurance policy created: ${policyId}`);
2544
+ console.log(` Function: ${functionName}`);
2545
+ console.log(` Coverage: $${coverageAmount}`);
2546
+ return policy;
2547
+ }
2548
+ /**
2549
+ * Configure autonomous agent capabilities with integrity verification.
2550
+ */
2551
+ configureAutonomousAgent(capabilities, constraints) {
2552
+ const configId = `config_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
2553
+ const configuration = {
2554
+ config_id: configId,
2555
+ agent_name: this.agentName,
2556
+ capabilities,
2557
+ constraints,
2558
+ integrity_verification: true,
2559
+ registered_functions: Array.from(this.registeredFunctions.keys()),
2560
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
2561
+ };
2562
+ console.log(`\u{1F916} Autonomous agent configured: ${configId}`);
2563
+ console.log(` Capabilities: ${capabilities.length}`);
2564
+ console.log(` Registered functions: ${this.registeredFunctions.size}`);
2565
+ return configuration;
2566
+ }
2567
+ };
2568
+ var LocalIPFSStorage = class {
2569
+ apiUrl;
2570
+ constructor(apiUrl = "http://127.0.0.1:5001") {
2571
+ this.apiUrl = apiUrl;
2572
+ console.log(`\u{1F4E6} Local IPFS Storage initialized: ${apiUrl}`);
2573
+ }
2574
+ async put(data, mime = "application/json") {
2575
+ try {
2576
+ const buffer = typeof data === "string" ? Buffer.from(data) : data;
2577
+ const FormData2 = __require("form-data");
2578
+ const form = new FormData2();
2579
+ form.append("file", buffer, { contentType: mime });
2580
+ const response = await axios2__default.default.post(`${this.apiUrl}/api/v0/add`, form, {
2581
+ headers: form.getHeaders(),
2582
+ maxBodyLength: Infinity
2583
+ });
2584
+ const cid = response.data.Hash;
2585
+ console.log(`\u2705 Uploaded to local IPFS: ${cid}`);
2586
+ return {
2587
+ cid,
2588
+ url: `ipfs://${cid}`,
2589
+ size: response.data.Size,
2590
+ provider: "local-ipfs"
2591
+ };
2592
+ } catch (e) {
2593
+ if (e.code === "ECONNREFUSED") {
2594
+ throw new StorageError(
2595
+ "Local IPFS daemon not running. Start with: ipfs daemon",
2596
+ { api_url: this.apiUrl }
2597
+ );
2598
+ }
2599
+ throw new StorageError(`Local IPFS upload failed: ${e.message}`);
2600
+ }
2601
+ }
2602
+ async get(cid) {
2603
+ try {
2604
+ const response = await axios2__default.default.post(
2605
+ `${this.apiUrl}/api/v0/cat`,
2606
+ null,
2607
+ {
2608
+ params: { arg: cid },
2609
+ responseType: "arraybuffer"
2610
+ }
2611
+ );
2612
+ return Buffer.from(response.data);
2613
+ } catch (e) {
2614
+ throw new StorageError(`Failed to retrieve from IPFS: ${e.message}`);
2615
+ }
2616
+ }
2617
+ async pin(cid) {
2618
+ try {
2619
+ await axios2__default.default.post(`${this.apiUrl}/api/v0/pin/add`, null, {
2620
+ params: { arg: cid }
2621
+ });
2622
+ console.log(`\u{1F4CC} Pinned to local IPFS: ${cid}`);
2623
+ } catch (e) {
2624
+ throw new StorageError(`Failed to pin CID: ${e.message}`);
2625
+ }
2626
+ }
2627
+ async unpin(cid) {
2628
+ try {
2629
+ await axios2__default.default.post(`${this.apiUrl}/api/v0/pin/rm`, null, {
2630
+ params: { arg: cid }
2631
+ });
2632
+ console.log(`\u{1F4CC} Unpinned from local IPFS: ${cid}`);
2633
+ } catch (e) {
2634
+ throw new StorageError(`Failed to unpin CID: ${e.message}`);
2635
+ }
2636
+ }
2637
+ };
2638
+ var PinataStorage = class {
2639
+ jwtToken;
2640
+ gatewayUrl;
2641
+ constructor(jwtToken, gatewayUrl = "https://gateway.pinata.cloud") {
2642
+ this.jwtToken = jwtToken;
2643
+ this.gatewayUrl = gatewayUrl;
2644
+ console.log(`\u{1F310} Pinata Storage initialized`);
2645
+ }
2646
+ async put(data, mime = "application/json") {
2647
+ try {
2648
+ const buffer = typeof data === "string" ? Buffer.from(data) : data;
2649
+ const FormData2 = __require("form-data");
2650
+ const form = new FormData2();
2651
+ form.append("file", buffer, {
2652
+ contentType: mime,
2653
+ filename: `file_${Date.now()}`
2654
+ });
2655
+ const response = await axios2__default.default.post("https://api.pinata.cloud/pinning/pinFileToIPFS", form, {
2656
+ headers: {
2657
+ ...form.getHeaders(),
2658
+ Authorization: `Bearer ${this.jwtToken}`
2659
+ },
2660
+ maxBodyLength: Infinity
2661
+ });
2662
+ const cid = response.data.IpfsHash;
2663
+ console.log(`\u2705 Uploaded to Pinata: ${cid}`);
2664
+ return {
2665
+ cid,
2666
+ url: `${this.gatewayUrl}/ipfs/${cid}`,
2667
+ size: response.data.PinSize,
2668
+ provider: "pinata"
2669
+ };
2670
+ } catch (e) {
2671
+ throw new StorageError(`Pinata upload failed: ${e.message}`);
2672
+ }
2673
+ }
2674
+ async get(cid) {
2675
+ try {
2676
+ const response = await axios2__default.default.get(`${this.gatewayUrl}/ipfs/${cid}`, {
2677
+ responseType: "arraybuffer"
2678
+ });
2679
+ return Buffer.from(response.data);
2680
+ } catch (e) {
2681
+ throw new StorageError(`Failed to retrieve from Pinata: ${e.message}`);
2682
+ }
2683
+ }
2684
+ async pin(cid) {
2685
+ try {
2686
+ await axios2__default.default.post(
2687
+ "https://api.pinata.cloud/pinning/pinByHash",
2688
+ { hashToPin: cid },
2689
+ {
2690
+ headers: {
2691
+ Authorization: `Bearer ${this.jwtToken}`,
2692
+ "Content-Type": "application/json"
2693
+ }
2694
+ }
2695
+ );
2696
+ console.log(`\u{1F4CC} Pinned to Pinata: ${cid}`);
2697
+ } catch (e) {
2698
+ throw new StorageError(`Failed to pin to Pinata: ${e.message}`);
2699
+ }
2700
+ }
2701
+ async unpin(cid) {
2702
+ try {
2703
+ await axios2__default.default.delete(`https://api.pinata.cloud/pinning/unpin/${cid}`, {
2704
+ headers: {
2705
+ Authorization: `Bearer ${this.jwtToken}`
2706
+ }
2707
+ });
2708
+ console.log(`\u{1F4CC} Unpinned from Pinata: ${cid}`);
2709
+ } catch (e) {
2710
+ throw new StorageError(`Failed to unpin from Pinata: ${e.message}`);
2711
+ }
2712
+ }
2713
+ };
2714
+ var IrysStorage = class {
2715
+ walletKey;
2716
+ constructor(walletKey) {
2717
+ this.walletKey = walletKey;
2718
+ console.log(`\u{1F48E} Irys (Arweave) Storage initialized`);
2719
+ }
2720
+ async put(data, mime = "application/json") {
2721
+ try {
2722
+ const mockCid = `ar_${Date.now().toString(36)}_${Math.random().toString(36).substring(2, 15)}`;
2723
+ console.log(`\u2705 Uploaded to Irys: ${mockCid}`);
2724
+ return {
2725
+ cid: mockCid,
2726
+ url: `https://arweave.net/${mockCid}`,
2727
+ provider: "irys"
2728
+ };
2729
+ } catch (e) {
2730
+ throw new StorageError(`Irys upload failed: ${e.message}`);
2731
+ }
2732
+ }
2733
+ async get(cid) {
2734
+ try {
2735
+ const response = await axios2__default.default.get(`https://arweave.net/${cid}`, {
2736
+ responseType: "arraybuffer"
2737
+ });
2738
+ return Buffer.from(response.data);
2739
+ } catch (e) {
2740
+ throw new StorageError(`Failed to retrieve from Arweave: ${e.message}`);
2741
+ }
2742
+ }
2743
+ };
2744
+ var ZeroGStorage = class {
2745
+ grpcUrl;
2746
+ privateKey;
2747
+ constructor(privateKey, grpcUrl = "localhost:50051") {
2748
+ this.privateKey = privateKey;
2749
+ this.grpcUrl = grpcUrl;
2750
+ console.log(`\u26A1 0G Storage initialized: ${grpcUrl}`);
2751
+ }
2752
+ async put(data, mime = "application/json") {
2753
+ try {
2754
+ const mockCid = `0g_${Date.now().toString(36)}_${Math.random().toString(36).substring(2, 15)}`;
2755
+ console.log(`\u2705 Uploaded to 0G Storage: ${mockCid}`);
2756
+ return {
2757
+ cid: mockCid,
2758
+ url: `0g://${mockCid}`,
2759
+ provider: "0g-storage"
2760
+ };
2761
+ } catch (e) {
2762
+ throw new StorageError(`0G Storage upload failed: ${e.message}`);
2763
+ }
2764
+ }
2765
+ async get(cid) {
2766
+ try {
2767
+ throw new StorageError("0G Storage retrieval not yet implemented");
2768
+ } catch (e) {
2769
+ throw new StorageError(`Failed to retrieve from 0G Storage: ${e.message}`);
2770
+ }
2771
+ }
2772
+ };
2773
+ var AutoStorageManager = class {
2774
+ backends = [];
2775
+ preferredBackend = null;
2776
+ constructor() {
2777
+ this.detectAvailableBackends();
2778
+ }
2779
+ detectAvailableBackends() {
2780
+ console.log("\u{1F50D} Auto-detecting available storage backends...");
2781
+ try {
2782
+ const localIpfs = new LocalIPFSStorage();
2783
+ this.backends.push(localIpfs);
2784
+ this.preferredBackend = localIpfs;
2785
+ console.log("\u2705 Local IPFS available");
2786
+ } catch (e) {
2787
+ console.log("\u274C Local IPFS not available");
2788
+ }
2789
+ const pinataJwt = process.env.PINATA_JWT;
2790
+ if (pinataJwt) {
2791
+ const pinata = new PinataStorage(pinataJwt);
2792
+ this.backends.push(pinata);
2793
+ if (!this.preferredBackend) this.preferredBackend = pinata;
2794
+ console.log("\u2705 Pinata available");
2795
+ }
2796
+ const irysKey = process.env.IRYS_WALLET_KEY;
2797
+ if (irysKey) {
2798
+ const irys = new IrysStorage(irysKey);
2799
+ this.backends.push(irys);
2800
+ if (!this.preferredBackend) this.preferredBackend = irys;
2801
+ console.log("\u2705 Irys available");
2802
+ }
2803
+ const zerogKey = process.env.ZEROG_TESTNET_PRIVATE_KEY;
2804
+ if (zerogKey) {
2805
+ const zerog = new ZeroGStorage(zerogKey);
2806
+ this.backends.push(zerog);
2807
+ if (!this.preferredBackend) this.preferredBackend = zerog;
2808
+ console.log("\u2705 0G Storage available");
2809
+ }
2810
+ if (this.backends.length === 0) {
2811
+ console.warn("\u26A0\uFE0F No storage backends available! Please configure at least one.");
2812
+ } else {
2813
+ console.log(`\u{1F4E6} ${this.backends.length} storage backend(s) available`);
2814
+ }
2815
+ }
2816
+ async put(data, mime) {
2817
+ if (!this.preferredBackend) {
2818
+ throw new StorageError("No storage backends available");
2819
+ }
2820
+ try {
2821
+ return await this.preferredBackend.put(data, mime);
2822
+ } catch (e) {
2823
+ for (const backend of this.backends) {
2824
+ if (backend !== this.preferredBackend) {
2825
+ try {
2826
+ console.log(`\u26A0\uFE0F Trying fallback storage backend...`);
2827
+ return await backend.put(data, mime);
2828
+ } catch (fallbackError) {
2829
+ continue;
2830
+ }
2831
+ }
2832
+ }
2833
+ throw new StorageError(`All storage backends failed: ${e}`);
2834
+ }
2835
+ }
2836
+ async get(cid) {
2837
+ if (!this.preferredBackend) {
2838
+ throw new StorageError("No storage backends available");
2839
+ }
2840
+ return await this.preferredBackend.get(cid);
2841
+ }
2842
+ getAvailableBackends() {
2843
+ return this.backends.map((backend) => backend.constructor.name);
2844
+ }
2845
+ };
2846
+
2847
+ // src/utils/networks.ts
2848
+ var ERC8004_ADDRESSES = {
2849
+ "ethereum-sepolia": {
2850
+ identity: "0x8004a6090Cd10A7288092483047B097295Fb8847",
2851
+ reputation: "0x8004B8FD1A363aa02fDC07635C0c5F94f6Af5B7E",
2852
+ validation: "0x8004CB39f29c09145F24Ad9dDe2A108C1A2cdfC5"
2853
+ },
2854
+ "base-sepolia": {
2855
+ identity: "0x8004AA63c570c570eBF15376c0dB199918BFe9Fb",
2856
+ reputation: "0x8004bd8daB57f14Ed299135749a5CB5c42d341BF",
2857
+ validation: "0x8004C269D0A5647E51E121FeB226200ECE932d55"
2858
+ },
2859
+ "linea-sepolia": {
2860
+ identity: "0x8004aa7C931bCE1233973a0C6A667f73F66282e7",
2861
+ reputation: "0x8004bd8483b99310df121c46ED8858616b2Bba02",
2862
+ validation: "0x8004c44d1EFdd699B2A26e781eF7F77c56A9a4EB"
2863
+ },
2864
+ "hedera-testnet": {
2865
+ identity: "0x4c74ebd72921d537159ed2053f46c12a7d8e5923",
2866
+ reputation: "0xc565edcba77e3abeade40bfd6cf6bf583b3293e0",
2867
+ validation: "0x18df085d85c586e9241e0cd121ca422f571c2da6"
2868
+ },
2869
+ "0g-testnet": {
2870
+ identity: "0x80043ed9cf33a3472768dcd53175bb44e03a1e4a",
2871
+ reputation: "0x80045d7b72c47bf5ff73737b780cb1a5ba8ee202",
2872
+ validation: "0x80041728e0aadf1d1427f9be18d52b7f3afefafb"
2873
+ }
2874
+ };
2875
+ var NETWORK_INFO = {
2876
+ "ethereum-sepolia": {
2877
+ chainId: 11155111,
2878
+ name: "Ethereum Sepolia Testnet",
2879
+ rpcUrl: process.env.ETHEREUM_SEPOLIA_RPC_URL || "https://rpc.sepolia.org",
2880
+ contracts: ERC8004_ADDRESSES["ethereum-sepolia"],
2881
+ nativeCurrency: {
2882
+ name: "Sepolia ETH",
2883
+ symbol: "ETH",
2884
+ decimals: 18
2885
+ }
2886
+ },
2887
+ "base-sepolia": {
2888
+ chainId: 84532,
2889
+ name: "Base Sepolia Testnet",
2890
+ rpcUrl: process.env.BASE_SEPOLIA_RPC_URL || "https://sepolia.base.org",
2891
+ contracts: ERC8004_ADDRESSES["base-sepolia"],
2892
+ nativeCurrency: {
2893
+ name: "Sepolia ETH",
2894
+ symbol: "ETH",
2895
+ decimals: 18
2896
+ }
2897
+ },
2898
+ "linea-sepolia": {
2899
+ chainId: 59141,
2900
+ name: "Linea Sepolia Testnet",
2901
+ rpcUrl: process.env.LINEA_SEPOLIA_RPC_URL || "https://rpc.sepolia.linea.build",
2902
+ contracts: ERC8004_ADDRESSES["linea-sepolia"],
2903
+ nativeCurrency: {
2904
+ name: "Linea ETH",
2905
+ symbol: "ETH",
2906
+ decimals: 18
2907
+ }
2908
+ },
2909
+ "hedera-testnet": {
2910
+ chainId: 296,
2911
+ name: "Hedera Testnet",
2912
+ rpcUrl: process.env.HEDERA_TESTNET_RPC_URL || "https://testnet.hashio.io/api",
2913
+ contracts: ERC8004_ADDRESSES["hedera-testnet"],
2914
+ nativeCurrency: {
2915
+ name: "HBAR",
2916
+ symbol: "HBAR",
2917
+ decimals: 18
2918
+ }
2919
+ },
2920
+ "0g-testnet": {
2921
+ chainId: 16600,
2922
+ name: "0G Network Testnet",
2923
+ rpcUrl: process.env.ZEROG_TESTNET_RPC_URL || "https://evmrpc-testnet.0g.ai",
2924
+ contracts: ERC8004_ADDRESSES["0g-testnet"],
2925
+ nativeCurrency: {
2926
+ name: "A0GI",
2927
+ symbol: "A0GI",
2928
+ decimals: 18
2929
+ }
2930
+ },
2931
+ local: {
2932
+ chainId: 31337,
2933
+ name: "Local Network",
2934
+ rpcUrl: process.env.LOCAL_RPC_URL || "http://localhost:8545",
2935
+ contracts: {
2936
+ identity: "0x5FbDB2315678afecb367f032d93F642f64180aa3",
2937
+ reputation: "0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512",
2938
+ validation: "0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0"
2939
+ },
2940
+ nativeCurrency: {
2941
+ name: "ETH",
2942
+ symbol: "ETH",
2943
+ decimals: 18
2944
+ }
2945
+ }
2946
+ };
2947
+ function getNetworkInfo(network) {
2948
+ const networkKey = typeof network === "string" ? network : network.valueOf();
2949
+ const info = NETWORK_INFO[networkKey];
2950
+ if (!info) {
2951
+ throw new Error(`Unsupported network: ${networkKey}`);
2952
+ }
2953
+ return info;
2954
+ }
2955
+ function getContractAddresses(network) {
2956
+ return getNetworkInfo(network).contracts;
2957
+ }
2958
+
2959
+ // src/ChaosChainSDK.ts
2960
+ var ChaosChainSDK = class {
2961
+ // Core components
2962
+ walletManager;
2963
+ chaosAgent;
2964
+ x402PaymentManager;
2965
+ paymentManager;
2966
+ storageBackend;
2967
+ computeProvider;
2968
+ provider;
2969
+ // Advanced integrations
2970
+ googleAP2;
2971
+ a2aX402Extension;
2972
+ processIntegrity;
2973
+ // Configuration
2974
+ agentName;
2975
+ agentDomain;
2976
+ agentRole;
2977
+ network;
2978
+ networkInfo;
2979
+ // Current agent ID (set after registration)
2980
+ _agentId;
2981
+ constructor(config) {
2982
+ this.agentName = config.agentName;
2983
+ this.agentDomain = config.agentDomain;
2984
+ this.agentRole = config.agentRole;
2985
+ this.network = config.network;
2986
+ this.networkInfo = getNetworkInfo(config.network);
2987
+ const rpcUrl = config.rpcUrl || this.networkInfo.rpcUrl;
2988
+ this.provider = new ethers.ethers.JsonRpcProvider(rpcUrl);
2989
+ this.walletManager = new WalletManager(
2990
+ {
2991
+ privateKey: config.privateKey,
2992
+ mnemonic: config.mnemonic,
2993
+ walletFile: config.walletFile
2994
+ },
2995
+ this.provider
2996
+ );
2997
+ const contractAddresses = getContractAddresses(config.network);
2998
+ this.chaosAgent = new ChaosAgent(
2999
+ contractAddresses,
3000
+ this.walletManager.getWallet(),
3001
+ this.provider
3002
+ );
3003
+ if (config.storageProvider) {
3004
+ this.storageBackend = config.storageProvider;
3005
+ } else if (config.enableStorage !== false) {
3006
+ this.storageBackend = new AutoStorageManager();
3007
+ } else {
3008
+ this.storageBackend = {
3009
+ put: async () => ({ cid: "", provider: "none" }),
3010
+ get: async () => Buffer.from("")
3011
+ };
3012
+ }
3013
+ if (config.enablePayments !== false) {
3014
+ this.x402PaymentManager = new X402PaymentManager(
3015
+ this.walletManager.getWallet(),
3016
+ typeof config.network === "string" ? config.network : config.network
3017
+ );
3018
+ const paymentCredentials = {
3019
+ stripe_secret_key: process.env.STRIPE_SECRET_KEY,
3020
+ google_pay_merchant_id: process.env.GOOGLE_PAY_MERCHANT_ID,
3021
+ apple_pay_merchant_id: process.env.APPLE_PAY_MERCHANT_ID,
3022
+ paypal_client_id: process.env.PAYPAL_CLIENT_ID,
3023
+ paypal_client_secret: process.env.PAYPAL_CLIENT_SECRET
3024
+ };
3025
+ this.paymentManager = new PaymentManager(
3026
+ this.agentName,
3027
+ typeof config.network === "string" ? config.network : config.network,
3028
+ this.walletManager.getWallet(),
3029
+ paymentCredentials
3030
+ );
3031
+ this.a2aX402Extension = new A2AX402Extension(
3032
+ this.agentName,
3033
+ typeof config.network === "string" ? config.network : config.network,
3034
+ this.paymentManager
3035
+ );
3036
+ }
3037
+ if (config.enableAP2 !== false) {
3038
+ this.googleAP2 = new GoogleAP2Integration(
3039
+ this.agentName,
3040
+ process.env.GOOGLE_AP2_MERCHANT_PRIVATE_KEY
3041
+ );
3042
+ }
3043
+ if (config.enableProcessIntegrity !== false) {
3044
+ this.processIntegrity = new ProcessIntegrity(
3045
+ this.storageBackend,
3046
+ this.computeProvider
3047
+ );
3048
+ }
3049
+ this.computeProvider = config.computeProvider;
3050
+ console.log(`\u{1F680} ChaosChain SDK initialized for ${this.agentName}`);
3051
+ console.log(` Network: ${this.network}`);
3052
+ console.log(` Wallet: ${this.walletManager.getAddress()}`);
3053
+ console.log(` Features:`);
3054
+ console.log(` - ERC-8004: \u2705`);
3055
+ console.log(` - x402 Payments: ${this.x402PaymentManager ? "\u2705" : "\u274C"}`);
3056
+ console.log(` - Multi-Payment: ${this.paymentManager ? "\u2705" : "\u274C"}`);
3057
+ console.log(` - Google AP2: ${this.googleAP2 ? "\u2705" : "\u274C"}`);
3058
+ console.log(` - Process Integrity: ${this.processIntegrity ? "\u2705" : "\u274C"}`);
3059
+ console.log(` - Storage: \u2705`);
3060
+ }
3061
+ // ============================================================================
3062
+ // ERC-8004 Identity Methods
3063
+ // ============================================================================
3064
+ /**
3065
+ * Register agent identity on-chain
3066
+ */
3067
+ async registerIdentity(metadata) {
3068
+ const meta = metadata || {
3069
+ name: this.agentName,
3070
+ domain: this.agentDomain,
3071
+ role: this.agentRole
3072
+ };
3073
+ const registration = await this.chaosAgent.registerIdentity(meta);
3074
+ this._agentId = registration.agentId;
3075
+ console.log(`\u2705 Agent #${registration.agentId} registered on-chain`);
3076
+ return registration;
3077
+ }
3078
+ /**
3079
+ * Get agent metadata
3080
+ */
3081
+ async getAgentMetadata(agentId) {
3082
+ return this.chaosAgent.getAgentMetadata(agentId);
3083
+ }
3084
+ /**
3085
+ * Update agent metadata
3086
+ */
3087
+ async updateAgentMetadata(agentId, metadata) {
3088
+ return this.chaosAgent.updateAgentMetadata(agentId, metadata);
3089
+ }
3090
+ /**
3091
+ * Get current agent ID
3092
+ */
3093
+ getAgentId() {
3094
+ return this._agentId;
3095
+ }
3096
+ // ============================================================================
3097
+ // ERC-8004 Reputation Methods
3098
+ // ============================================================================
3099
+ /**
3100
+ * Generate feedback authorization (EIP-191 signing)
3101
+ */
3102
+ async generateFeedbackAuthorization(agentId, clientAddress, indexLimit, expiry) {
3103
+ return this.chaosAgent.generateFeedbackAuthorization(agentId, clientAddress, indexLimit, expiry);
3104
+ }
3105
+ /**
3106
+ * Give feedback to an agent
3107
+ */
3108
+ async giveFeedback(params) {
3109
+ return this.chaosAgent.giveFeedback(params);
3110
+ }
3111
+ /**
3112
+ * Submit feedback with payment proof (ERC-8004 reputation enrichment)
3113
+ */
3114
+ async submitFeedbackWithPayment(agentId, score, feedbackData, paymentProof) {
3115
+ const fullFeedbackData = {
3116
+ ...feedbackData,
3117
+ score,
3118
+ proof_of_payment: paymentProof,
3119
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
3120
+ };
3121
+ const feedbackJson = JSON.stringify(fullFeedbackData);
3122
+ const result = await this.storageBackend.put(Buffer.from(feedbackJson), "application/json");
3123
+ const feedbackUri = `ipfs://${result.cid}`;
3124
+ const txHash = await this.chaosAgent.giveFeedback({
3125
+ agentId,
3126
+ rating: score,
3127
+ feedbackUri
3128
+ });
3129
+ console.log(`\u2705 Feedback submitted with payment proof`);
3130
+ console.log(` TX: ${txHash}`);
3131
+ console.log(` URI: ${feedbackUri}`);
3132
+ return { feedbackTxHash: txHash, feedbackUri };
3133
+ }
3134
+ /**
3135
+ * Get agent reputation score
3136
+ */
3137
+ async getReputationScore(_agentId) {
3138
+ return 0;
3139
+ }
3140
+ // ============================================================================
3141
+ // ERC-8004 Validation Methods
3142
+ // ============================================================================
3143
+ /**
3144
+ * Request validation from validator
3145
+ */
3146
+ async requestValidation(params) {
3147
+ return this.chaosAgent.requestValidation(params);
3148
+ }
3149
+ /**
3150
+ * Respond to validation request
3151
+ */
3152
+ async respondToValidation(requestId, approved, responseUri) {
3153
+ return this.chaosAgent.respondToValidation(requestId, approved, responseUri);
3154
+ }
3155
+ // ============================================================================
3156
+ // x402 Crypto Payment Methods
3157
+ // ============================================================================
3158
+ /**
3159
+ * Create x402 payment request
3160
+ */
3161
+ createX402PaymentRequest(fromAgent, toAgent, amount, currency = "USDC", serviceDescription = "AI Agent Service") {
3162
+ if (!this.x402PaymentManager) {
3163
+ throw new Error("x402 payments not enabled");
3164
+ }
3165
+ return this.x402PaymentManager.createPaymentRequest(fromAgent, toAgent, amount, currency, serviceDescription);
3166
+ }
3167
+ /**
3168
+ * Execute x402 crypto payment
3169
+ */
3170
+ async executeX402Payment(paymentRequest, recipientAddress) {
3171
+ if (!this.x402PaymentManager) {
3172
+ throw new Error("x402 payments not enabled");
3173
+ }
3174
+ return this.x402PaymentManager.executePayment(paymentRequest, recipientAddress);
3175
+ }
3176
+ /**
3177
+ * Create x402 payment requirements (for receiving payments)
3178
+ */
3179
+ createX402PaymentRequirements(amount, currency = "USDC", serviceDescription = "AI Agent Service", expiryMinutes = 30) {
3180
+ if (!this.x402PaymentManager) {
3181
+ throw new Error("x402 payments not enabled");
3182
+ }
3183
+ return this.x402PaymentManager.createPaymentRequirements(amount, currency, serviceDescription, expiryMinutes);
3184
+ }
3185
+ /**
3186
+ * Create x402 paywall server
3187
+ */
3188
+ createX402PaywallServer(port = 8402) {
3189
+ if (!this.x402PaymentManager) {
3190
+ throw new Error("x402 payments not enabled");
3191
+ }
3192
+ return new X402Server(this.x402PaymentManager, { port });
3193
+ }
3194
+ /**
3195
+ * Get x402 payment history
3196
+ */
3197
+ async getX402PaymentHistory(limit = 10) {
3198
+ if (!this.x402PaymentManager) {
3199
+ throw new Error("x402 payments not enabled");
3200
+ }
3201
+ return this.x402PaymentManager.getPaymentHistory(limit);
3202
+ }
3203
+ // ============================================================================
3204
+ // Traditional Payment Methods (Cards, Google Pay, Apple Pay, PayPal)
3205
+ // ============================================================================
3206
+ /**
3207
+ * Execute traditional payment
3208
+ */
3209
+ executeTraditionalPayment(paymentMethod, amount, currency, paymentData2) {
3210
+ if (!this.paymentManager) {
3211
+ throw new Error("Payment manager not enabled");
3212
+ }
3213
+ return this.paymentManager.executeTraditionalPayment(paymentMethod, amount, currency, paymentData2);
3214
+ }
3215
+ /**
3216
+ * Get supported payment methods
3217
+ */
3218
+ getSupportedPaymentMethods() {
3219
+ if (!this.paymentManager) {
3220
+ return [];
3221
+ }
3222
+ return this.paymentManager.getSupportedPaymentMethods();
3223
+ }
3224
+ /**
3225
+ * Get payment methods status
3226
+ */
3227
+ getPaymentMethodsStatus() {
3228
+ if (!this.paymentManager) {
3229
+ return {};
3230
+ }
3231
+ return this.paymentManager.getPaymentMethodsStatus();
3232
+ }
3233
+ // ============================================================================
3234
+ // Google AP2 Intent Verification Methods
3235
+ // ============================================================================
3236
+ /**
3237
+ * Create Google AP2 intent mandate
3238
+ */
3239
+ createIntentMandate(userDescription, merchants, skus, requiresRefundability = false, expiryMinutes = 60) {
3240
+ if (!this.googleAP2) {
3241
+ throw new Error("Google AP2 not enabled");
3242
+ }
3243
+ return this.googleAP2.createIntentMandate(userDescription, merchants, skus, requiresRefundability, expiryMinutes);
3244
+ }
3245
+ /**
3246
+ * Create Google AP2 cart mandate with JWT signing
3247
+ */
3248
+ async createCartMandate(cartId, items, totalAmount, currency = "USD", merchantName, expiryMinutes = 15) {
3249
+ if (!this.googleAP2) {
3250
+ throw new Error("Google AP2 not enabled");
3251
+ }
3252
+ return this.googleAP2.createCartMandate(cartId, items, totalAmount, currency, merchantName, expiryMinutes);
3253
+ }
3254
+ /**
3255
+ * Verify JWT token
3256
+ */
3257
+ async verifyJwtToken(token) {
3258
+ if (!this.googleAP2) {
3259
+ throw new Error("Google AP2 not enabled");
3260
+ }
3261
+ return this.googleAP2.verifyJwtToken(token);
3262
+ }
3263
+ // ============================================================================
3264
+ // Process Integrity Methods
3265
+ // ============================================================================
3266
+ /**
3267
+ * Register function for integrity verification
3268
+ */
3269
+ registerFunction(func) {
3270
+ if (!this.processIntegrity) {
3271
+ throw new Error("Process integrity not enabled");
3272
+ }
3273
+ this.processIntegrity.registerFunction(func);
3274
+ }
3275
+ /**
3276
+ * Execute function with integrity proof
3277
+ */
3278
+ async executeWithIntegrityProof(functionName, args) {
3279
+ if (!this.processIntegrity) {
3280
+ throw new Error("Process integrity not enabled");
3281
+ }
3282
+ const [result, proof] = await this.processIntegrity.executeWithProof(functionName, args);
3283
+ return { result, proof };
3284
+ }
3285
+ /**
3286
+ * Verify integrity proof
3287
+ */
3288
+ async verifyIntegrityProof(_proof) {
3289
+ if (!this.processIntegrity) {
3290
+ throw new Error("Process integrity not enabled");
3291
+ }
3292
+ return true;
3293
+ }
3294
+ // ============================================================================
3295
+ // Storage Methods
3296
+ // ============================================================================
3297
+ /**
3298
+ * Upload data to storage
3299
+ */
3300
+ async upload(data, _options) {
3301
+ const jsonData = typeof data === "string" ? data : JSON.stringify(data);
3302
+ const buffer = Buffer.from(jsonData);
3303
+ const result = await this.storageBackend.put(buffer, "application/json");
3304
+ return {
3305
+ cid: result.cid,
3306
+ uri: result.url || `ipfs://${result.cid}`
3307
+ };
3308
+ }
3309
+ /**
3310
+ * Download data from storage
3311
+ */
3312
+ async download(cid) {
3313
+ const buffer = await this.storageBackend.get(cid);
3314
+ const data = buffer.toString("utf-8");
3315
+ try {
3316
+ return JSON.parse(data);
3317
+ } catch {
3318
+ return data;
3319
+ }
3320
+ }
3321
+ /**
3322
+ * Store evidence (convenience method)
3323
+ */
3324
+ async storeEvidence(evidenceData) {
3325
+ const result = await this.storageBackend.put(Buffer.from(JSON.stringify(evidenceData)), "application/json");
3326
+ console.log(`\u{1F4E6} Stored evidence: ${result.cid}`);
3327
+ return result.cid;
3328
+ }
3329
+ // ============================================================================
3330
+ // Wallet & Network Methods
3331
+ // ============================================================================
3332
+ /**
3333
+ * Get wallet address
3334
+ */
3335
+ getAddress() {
3336
+ return this.walletManager.getAddress();
3337
+ }
3338
+ /**
3339
+ * Get wallet balance
3340
+ */
3341
+ async getBalance() {
3342
+ return this.walletManager.getBalance();
3343
+ }
3344
+ /**
3345
+ * Get network info
3346
+ */
3347
+ getNetworkInfo() {
3348
+ return this.networkInfo;
3349
+ }
3350
+ /**
3351
+ * Get SDK capabilities summary
3352
+ */
3353
+ getCapabilities() {
3354
+ return {
3355
+ agent_name: this.agentName,
3356
+ agent_domain: this.agentDomain,
3357
+ agent_role: this.agentRole,
3358
+ network: this.network,
3359
+ wallet_address: this.walletManager.getAddress(),
3360
+ agent_id: this._agentId ? this._agentId.toString() : void 0,
3361
+ features: {
3362
+ erc_8004_identity: true,
3363
+ erc_8004_reputation: true,
3364
+ erc_8004_validation: true,
3365
+ x402_crypto_payments: !!this.x402PaymentManager,
3366
+ traditional_payments: !!this.paymentManager,
3367
+ google_ap2_intents: !!this.googleAP2,
3368
+ process_integrity: !!this.processIntegrity,
3369
+ storage: true,
3370
+ compute: !!this.computeProvider
3371
+ },
3372
+ supported_payment_methods: this.paymentManager ? this.paymentManager.getSupportedPaymentMethods() : [],
3373
+ storage_backends: this.storageBackend instanceof AutoStorageManager ? this.storageBackend.getAvailableBackends() : [this.storageBackend.constructor.name]
3374
+ };
3375
+ }
3376
+ };
3377
+ var IPFSLocalStorage = class {
3378
+ apiUrl;
3379
+ gatewayUrl;
3380
+ constructor(apiUrl = "http://localhost:5001", gatewayUrl = "http://localhost:8080") {
3381
+ this.apiUrl = apiUrl;
3382
+ this.gatewayUrl = gatewayUrl;
3383
+ }
3384
+ /**
3385
+ * Upload data to local IPFS
3386
+ */
3387
+ async upload(data, options) {
3388
+ try {
3389
+ let buffer;
3390
+ if (Buffer.isBuffer(data)) {
3391
+ buffer = data;
3392
+ } else if (typeof data === "string") {
3393
+ buffer = Buffer.from(data, "utf-8");
3394
+ } else {
3395
+ buffer = Buffer.from(JSON.stringify(data), "utf-8");
3396
+ }
3397
+ const formData = new FormData();
3398
+ const blob = new Blob([buffer], { type: options?.mime || "application/octet-stream" });
3399
+ formData.append("file", blob);
3400
+ const response = await axios2__default.default.post(`${this.apiUrl}/api/v0/add`, formData, {
3401
+ headers: {
3402
+ "Content-Type": "multipart/form-data"
3403
+ },
3404
+ params: {
3405
+ pin: options?.pin !== false
3406
+ // Pin by default
3407
+ }
3408
+ });
3409
+ const cid = response.data.Hash;
3410
+ return {
3411
+ cid,
3412
+ uri: `ipfs://${cid}`,
3413
+ size: response.data.Size
3414
+ };
3415
+ } catch (error) {
3416
+ throw new Error(`Failed to upload to IPFS: ${error.message}`);
3417
+ }
3418
+ }
3419
+ /**
3420
+ * Download data from IPFS
3421
+ */
3422
+ async download(cid) {
3423
+ try {
3424
+ const response = await axios2__default.default.get(`${this.gatewayUrl}/ipfs/${cid}`, {
3425
+ responseType: "arraybuffer"
3426
+ });
3427
+ return Buffer.from(response.data);
3428
+ } catch (error) {
3429
+ throw new Error(`Failed to download from IPFS: ${error.message}`);
3430
+ }
3431
+ }
3432
+ /**
3433
+ * Pin content
3434
+ */
3435
+ async pin(cid) {
3436
+ try {
3437
+ await axios2__default.default.post(`${this.apiUrl}/api/v0/pin/add`, null, {
3438
+ params: { arg: cid }
3439
+ });
3440
+ } catch (error) {
3441
+ throw new Error(`Failed to pin content: ${error.message}`);
3442
+ }
3443
+ }
3444
+ /**
3445
+ * Unpin content
3446
+ */
3447
+ async unpin(cid) {
3448
+ try {
3449
+ await axios2__default.default.post(`${this.apiUrl}/api/v0/pin/rm`, null, {
3450
+ params: { arg: cid }
3451
+ });
3452
+ } catch (error) {
3453
+ throw new Error(`Failed to unpin content: ${error.message}`);
3454
+ }
3455
+ }
3456
+ /**
3457
+ * Check if IPFS daemon is running
3458
+ */
3459
+ async isAvailable() {
3460
+ try {
3461
+ await axios2__default.default.post(`${this.apiUrl}/api/v0/version`);
3462
+ return true;
3463
+ } catch {
3464
+ return false;
3465
+ }
3466
+ }
3467
+ /**
3468
+ * Get IPFS version
3469
+ */
3470
+ async getVersion() {
3471
+ try {
3472
+ const response = await axios2__default.default.post(`${this.apiUrl}/api/v0/version`);
3473
+ return response.data.Version;
3474
+ } catch (error) {
3475
+ throw new Error(`Failed to get IPFS version: ${error.message}`);
3476
+ }
3477
+ }
3478
+ };
3479
+
3480
+ // src/types.ts
3481
+ var AgentRole = /* @__PURE__ */ ((AgentRole2) => {
3482
+ AgentRole2["SERVER"] = "server";
3483
+ AgentRole2["CLIENT"] = "client";
3484
+ AgentRole2["VALIDATOR"] = "validator";
3485
+ AgentRole2["BOTH"] = "both";
3486
+ return AgentRole2;
3487
+ })(AgentRole || {});
3488
+ var ValidationStatus = /* @__PURE__ */ ((ValidationStatus2) => {
3489
+ ValidationStatus2[ValidationStatus2["PENDING"] = 0] = "PENDING";
3490
+ ValidationStatus2[ValidationStatus2["APPROVED"] = 1] = "APPROVED";
3491
+ ValidationStatus2[ValidationStatus2["REJECTED"] = 2] = "REJECTED";
3492
+ return ValidationStatus2;
3493
+ })(ValidationStatus || {});
3494
+
3495
+ // src/index.ts
3496
+ var PaymentMethod = /* @__PURE__ */ ((PaymentMethod2) => {
3497
+ PaymentMethod2["BASIC_CARD"] = "basic-card";
3498
+ PaymentMethod2["GOOGLE_PAY"] = "https://google.com/pay";
3499
+ PaymentMethod2["APPLE_PAY"] = "https://apple.com/apple-pay";
3500
+ PaymentMethod2["PAYPAL"] = "https://paypal.com";
3501
+ PaymentMethod2["A2A_X402"] = "https://a2a.org/x402";
3502
+ return PaymentMethod2;
3503
+ })(PaymentMethod || {});
3504
+ var SDK_VERSION = "0.1.0";
3505
+ var ERC8004_VERSION = "1.0";
3506
+ var X402_VERSION = "1.0";
3507
+ var src_default = ChaosChainSDK;
3508
+ function initChaosChainSDK(config) {
3509
+ return new ChaosChainSDK(config);
3510
+ }
3511
+
3512
+ exports.A2AX402Extension = A2AX402Extension;
3513
+ exports.AgentRegistrationError = AgentRegistrationError;
3514
+ exports.AgentRole = AgentRole;
3515
+ exports.AutoStorageManager = AutoStorageManager;
3516
+ exports.ChaosAgent = ChaosAgent;
3517
+ exports.ChaosChainSDK = ChaosChainSDK;
3518
+ exports.ChaosChainSDKError = ChaosChainSDKError;
3519
+ exports.ConfigurationError = ConfigurationError;
3520
+ exports.ContractError = ContractError;
3521
+ exports.ERC8004_VERSION = ERC8004_VERSION;
3522
+ exports.GoogleAP2Integration = GoogleAP2Integration;
3523
+ exports.IDENTITY_REGISTRY_ABI = IDENTITY_REGISTRY_ABI;
3524
+ exports.IPFSLocalStorage = IPFSLocalStorage;
3525
+ exports.IPFSPinataStorage = PinataStorage;
3526
+ exports.IntegrityVerificationError = IntegrityVerificationError;
3527
+ exports.IrysStorage = IrysStorage;
3528
+ exports.IrysStorageProvider = IrysStorage;
3529
+ exports.LocalIPFSStorage = LocalIPFSStorage;
3530
+ exports.PaymentError = PaymentError2;
3531
+ exports.PaymentManager = PaymentManager;
3532
+ exports.PaymentMethod = PaymentMethod;
3533
+ exports.PinataStorage = PinataStorage;
3534
+ exports.REPUTATION_REGISTRY_ABI = REPUTATION_REGISTRY_ABI;
3535
+ exports.SDK_VERSION = SDK_VERSION;
3536
+ exports.StorageError = StorageError;
3537
+ exports.VALIDATION_REGISTRY_ABI = VALIDATION_REGISTRY_ABI;
3538
+ exports.ValidationStatus = ValidationStatus;
3539
+ exports.WalletManager = WalletManager;
3540
+ exports.X402PaymentManager = X402PaymentManager;
3541
+ exports.X402Server = X402Server;
3542
+ exports.X402_VERSION = X402_VERSION;
3543
+ exports.ZeroGStorage = ZeroGStorage;
3544
+ exports.default = src_default;
3545
+ exports.getContractAddresses = getContractAddresses;
3546
+ exports.getNetworkInfo = getNetworkInfo;
3547
+ exports.initChaosChainSDK = initChaosChainSDK;
3548
+ //# sourceMappingURL=index.js.map
3549
+ //# sourceMappingURL=index.js.map