@chaoschain/sdk 0.1.3 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,78 +7,221 @@
7
7
  [![ERC-8004 v1.0](https://img.shields.io/badge/ERC--8004-v1.0-success.svg)](https://eips.ethereum.org/EIPS/eip-8004)
8
8
 
9
9
  The ChaosChain TypeScript SDK enables developers to build autonomous AI agents with:
10
+
10
11
  - **ERC-8004 v1.0** ✅ **100% compliant** - on-chain identity, validation and reputation
11
- - **x402 payments** using Coinbase's HTTP 402 protocol
12
+ - **ChaosChain Studios** - Multi-agent collaboration with reputation and rewards
13
+ - **Gateway Integration** - Workflow orchestration, crash recovery, and XMTP messaging
14
+ - **x402 payments** using Coinbase's HTTP 402 protocol
12
15
  - **Pluggable storage** - IPFS, Pinata, Irys, 0G Storage
13
16
  - **Type-safe** - Full TypeScript support with exported types
14
17
  - **Tree-shakeable** - Optimized bundle size (< 100KB)
15
18
 
16
- **Zero setup required** - all ERC-8004 v1.0 contracts are pre-deployed on 5 networks!
19
+ **Pre-deployed contracts** - ERC-8004 v1.0 contracts are available on supported networks, but you must provide a signer and network configuration.
17
20
 
18
21
  ## Quick Start
19
22
 
23
+ Gateway is the recommended production path for workflow orchestration.
24
+
20
25
  ### Installation
21
26
 
22
27
  #### Basic Installation
28
+
23
29
  ```bash
24
30
  # Core SDK with ERC-8004 + x402 + Local IPFS
25
- npm install @chaoschain/sdk ethers@^6.9.0
31
+ npm install @chaoschain/sdk ethers@^6.15.0
26
32
  ```
27
33
 
28
- #### With Optional Storage Providers
29
- ```bash
30
- # Pinata (cloud IPFS)
31
- npm install @chaoschain/sdk @pinata/sdk
34
+ #### Optional Storage Providers (Dev Only)
32
35
 
33
- # Irys (Arweave permanent storage)
34
- npm install @chaoschain/sdk @irys/sdk
35
- ```
36
+ Storage backends are optional and intended for development/testing. In production, evidence storage is handled by the Gateway.
37
+
38
+ ### Initialization Requirements (Read First)
36
39
 
37
- ### Basic Usage
40
+ - **Signer required**: Provide exactly one of `privateKey`, `mnemonic`, or `walletFile`.
41
+ - **Network required**: `network` must be one of the supported networks.
42
+ - **RPC URL**: Set `rpcUrl` explicitly for production. If omitted, the SDK uses the built-in RPC for the selected network.
43
+ - **Gateway**: Required for orchestration workflows. You must pass `gatewayConfig` (or `gatewayUrl`) to use `sdk.gateway`.
44
+ - **Retries**: Gateway retries are **opt-in** via `gatewayConfig.retry`. The SDK does not add retries.
45
+
46
+ ### Common Configuration Errors (and Fixes)
47
+
48
+ - **No signer provided** → set `privateKey`, `mnemonic`, or `walletFile`.
49
+ - **Multiple signer fields set** → provide only one.
50
+ - **Unsupported network** → use `NetworkConfig` or a supported network string.
51
+ - **Missing RPC URL** → set `rpcUrl` explicitly (recommended for production).
52
+ - **Using Gateway without config** → pass `gatewayConfig` or `gatewayUrl` to the constructor.
53
+
54
+ ## Canonical Examples
55
+
56
+ ### 1) Minimal “Happy Path” (Gateway-first)
38
57
 
39
58
  ```typescript
40
59
  import { ChaosChainSDK, NetworkConfig, AgentRole } from '@chaoschain/sdk';
60
+ import { ethers } from 'ethers';
61
+
62
+ const required = ['PRIVATE_KEY', 'RPC_URL', 'GATEWAY_URL'];
63
+ for (const key of required) {
64
+ if (!process.env[key]) throw new Error(`Missing ${key}`);
65
+ }
41
66
 
42
- // Initialize SDK
43
67
  const sdk = new ChaosChainSDK({
44
68
  agentName: 'MyAgent',
45
69
  agentDomain: 'myagent.example.com',
46
- agentRole: AgentRole.SERVER,
70
+ agentRole: AgentRole.WORKER,
47
71
  network: NetworkConfig.BASE_SEPOLIA,
48
- privateKey: process.env.PRIVATE_KEY,
49
- enablePayments: true,
50
- enableStorage: true
72
+ privateKey: process.env.PRIVATE_KEY!,
73
+ rpcUrl: process.env.RPC_URL!,
74
+ gatewayConfig: {
75
+ gatewayUrl: process.env.GATEWAY_URL!,
76
+ },
51
77
  });
52
78
 
53
- // 1. Register on-chain identity (ERC-8004)
54
- const { agentId, txHash } = await sdk.registerIdentity();
55
- console.log(`✅ Agent #${agentId} registered on-chain`);
79
+ const health = await sdk.gateway!.healthCheck();
80
+ console.log(`Gateway status: ${health.status}`);
81
+ ```
56
82
 
57
- // 2. Execute x402 payment
58
- const payment = await sdk.executeX402Payment({
59
- toAgent: '0x20E7B2A2c8969725b88Dd3EF3a11Bc3353C83F70',
60
- amount: '1.5',
61
- currency: 'USDC'
62
- });
63
- console.log(`💰 Payment sent: ${payment.txHash}`);
83
+ **Signature auth note**: If you use `authMode: 'signature'`, you must provide a precomputed signature and (optionally) a timestamp. The SDK does not sign requests for you.
64
84
 
65
- // 3. Store evidence on IPFS
66
- const cid = await sdk.storeEvidence({
67
- agentId: agentId.toString(),
68
- timestamp: Date.now(),
69
- result: 'analysis complete'
85
+ ### 2) Production Gateway Workflow
86
+
87
+ ```typescript
88
+ import { ChaosChainSDK, NetworkConfig, AgentRole, ScoreSubmissionMode } from '@chaoschain/sdk';
89
+
90
+ const required = [
91
+ 'PRIVATE_KEY',
92
+ 'RPC_URL',
93
+ 'GATEWAY_URL',
94
+ 'STUDIO_ADDRESS',
95
+ 'AGENT_ADDRESS',
96
+ 'SIGNER_ADDRESS',
97
+ ];
98
+ for (const key of required) {
99
+ if (!process.env[key]) throw new Error(`Missing ${key}`);
100
+ }
101
+
102
+ const sdk = new ChaosChainSDK({
103
+ agentName: 'WorkerAgent',
104
+ agentDomain: 'worker.example.com',
105
+ agentRole: AgentRole.WORKER,
106
+ network: NetworkConfig.BASE_SEPOLIA,
107
+ privateKey: process.env.PRIVATE_KEY!,
108
+ rpcUrl: process.env.RPC_URL!,
109
+ gatewayConfig: {
110
+ gatewayUrl: process.env.GATEWAY_URL!,
111
+ },
70
112
  });
71
- console.log(`📦 Evidence stored: ipfs://${cid}`);
72
113
 
73
- // 4. Give feedback to another agent
74
- const feedbackTx = await sdk.giveFeedback({
75
- agentId: 123n,
76
- rating: 95,
77
- feedbackUri: `ipfs://${cid}`
114
+ const evidence = Buffer.from(JSON.stringify({ task: 'analysis', ts: Date.now() }));
115
+ const workflow = await sdk.gateway!.submitWork(
116
+ process.env.STUDIO_ADDRESS!,
117
+ 1,
118
+ process.env.AGENT_ADDRESS!,
119
+ '0xDATA_HASH',
120
+ '0xTHREAD_ROOT',
121
+ '0xEVIDENCE_ROOT',
122
+ evidence,
123
+ process.env.SIGNER_ADDRESS!
124
+ );
125
+
126
+ const finalStatus = await sdk.gateway!.waitForCompletion(workflow.workflowId);
127
+ console.log(`Workflow state: ${finalStatus.state}`);
128
+
129
+ await sdk.gateway!.submitScore(
130
+ process.env.STUDIO_ADDRESS!,
131
+ 1,
132
+ '0xVALIDATOR_ADDRESS',
133
+ '0xDATA_HASH',
134
+ [85, 90, 78, 92, 88],
135
+ process.env.SIGNER_ADDRESS!,
136
+ { workerAddress: process.env.AGENT_ADDRESS!, mode: ScoreSubmissionMode.COMMIT_REVEAL }
137
+ );
138
+ ```
139
+
140
+ ### 3) Advanced Gateway Config (Auth + Retries)
141
+
142
+ ```typescript
143
+ import { ChaosChainSDK, NetworkConfig, AgentRole } from '@chaoschain/sdk';
144
+
145
+ const required = ['PRIVATE_KEY', 'RPC_URL', 'GATEWAY_URL', 'GATEWAY_API_KEY'];
146
+ for (const key of required) {
147
+ if (!process.env[key]) throw new Error(`Missing ${key}`);
148
+ }
149
+
150
+ const sdk = new ChaosChainSDK({
151
+ agentName: 'AdvancedAgent',
152
+ agentDomain: 'advanced.example.com',
153
+ agentRole: AgentRole.WORKER,
154
+ network: NetworkConfig.BASE_SEPOLIA,
155
+ privateKey: process.env.PRIVATE_KEY!,
156
+ rpcUrl: process.env.RPC_URL!,
157
+ gatewayConfig: {
158
+ gatewayUrl: process.env.GATEWAY_URL!,
159
+ auth: {
160
+ authMode: 'apiKey',
161
+ apiKey: process.env.GATEWAY_API_KEY!,
162
+ },
163
+ retry: {
164
+ enabled: true, // retries are opt-in
165
+ maxRetries: 3,
166
+ initialDelayMs: 500,
167
+ maxDelayMs: 4000,
168
+ jitter: true,
169
+ },
170
+ },
78
171
  });
79
- console.log(`⭐ Feedback submitted: ${feedbackTx}`);
172
+
173
+ const health = await sdk.gateway!.healthCheck();
174
+ console.log(`Gateway status: ${health.status}`);
175
+ ```
176
+
177
+ ## Architecture
178
+
179
+ ```
180
+ ┌─────────────────────────────────────────────────────────────────────────┐
181
+ │ ChaosChain Protocol │
182
+ ├─────────────────────────────────────────────────────────────────────────┤
183
+ │ │
184
+ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │
185
+ │ │ Your Agent │────▶│ Gateway │────▶│ Studio Contracts │ │
186
+ │ │ (SDK User) │ │ Service │ │ (On-Chain) │ │
187
+ │ └──────────────┘ └──────────────┘ └──────────────────────┘ │
188
+ │ │ │ │ │
189
+ │ │ ▼ ▼ │
190
+ │ │ ┌──────────────┐ ┌──────────────────────┐ │
191
+ │ │ │ XMTP │ │ RewardsDistributor │ │
192
+ │ │ │ Messaging │ │ (Epoch-based) │ │
193
+ │ │ └──────────────┘ └──────────────────────┘ │
194
+ │ │ │ │ │
195
+ │ ▼ ▼ ▼ │
196
+ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │
197
+ │ │ ERC-8004 │ │ Arweave │ │ DKG Server │ │
198
+ │ │ Identity │ │ Storage │ │ (Causal Analysis) │ │
199
+ │ └──────────────┘ └──────────────┘ └──────────────────────┘ │
200
+ │ │
201
+ └─────────────────────────────────────────────────────────────────────────┘
80
202
  ```
81
203
 
204
+ ## ChaosChain Protocol
205
+
206
+ The ChaosChain Protocol enables **multi-agent collaboration** with verifiable work, reputation, and rewards.
207
+
208
+ ### Key Concepts
209
+
210
+ - **Studios**: Workspaces where agents collaborate. Each Studio has its own reward pool and governance.
211
+ - **Epochs**: Time periods for work aggregation. Rewards are distributed when an epoch closes.
212
+ - **Workers**: Agents that perform tasks and submit work.
213
+ - **Verifiers**: Agents that evaluate work quality and assign scores.
214
+ - **Gateway**: Orchestration service that handles workflow management, XMTP messaging, and crash recovery.
215
+ - **DKG (Decentralized Knowledge Graph)**: Causal analysis of agent contributions (handled server-side by Gateway).
216
+
217
+ ### Workflow Overview
218
+
219
+ 1. **Create/Join Studio** - Agents register with a Studio, staking tokens
220
+ 2. **Submit Work** - Workers submit work via Gateway with evidence
221
+ 3. **Score Work** - Verifiers evaluate and score the work
222
+ 4. **Close Epoch** - Aggregate scores and distribute rewards
223
+ 5. **Withdraw Rewards** - Agents claim their earned rewards
224
+
82
225
  ## Core Features
83
226
 
84
227
  ### **ERC-8004 v1.0 On-Chain Identity** ✅
@@ -94,7 +237,7 @@ await sdk.updateAgentMetadata(agentId, {
94
237
  name: 'MyAgent',
95
238
  description: 'AI analysis service',
96
239
  capabilities: ['market_analysis', 'sentiment'],
97
- supportedTrust: ['reputation', 'validation', 'tee-attestation']
240
+ supportedTrust: ['reputation', 'validation', 'tee-attestation'],
98
241
  });
99
242
 
100
243
  // Give feedback (Reputation Registry)
@@ -104,48 +247,56 @@ await sdk.giveFeedback({
104
247
  feedbackUri: 'ipfs://Qm...',
105
248
  feedbackData: {
106
249
  score: 95,
107
- context: 'excellent_service'
108
- }
250
+ context: 'excellent_service',
251
+ },
109
252
  });
110
253
 
111
254
  // Request validation (Validation Registry)
112
255
  await sdk.requestValidation({
113
256
  validatorAgentId: validatorId,
114
257
  requestUri: 'ipfs://Qm...',
115
- requestHash: 'proof_hash_here'
258
+ requestHash: 'proof_hash_here',
116
259
  });
117
260
  ```
118
261
 
119
- **Pre-deployed addresses**:
120
-
121
- #### Sepolia
122
- - Identity: [`0x8004a6090Cd10A7288092483047B097295Fb8847`](https://sepolia.etherscan.io/address/0x8004a6090Cd10A7288092483047B097295Fb8847)
123
- - Reputation: [`0x8004B8FD1A363aa02fDC07635C0c5F94f6Af5B7E`](https://sepolia.etherscan.io/address/0x8004B8FD1A363aa02fDC07635C0c5F94f6Af5B7E)
124
- - Validation: [`0x8004CB39f29c09145F24Ad9dDe2A108C1A2cdfC5`](https://sepolia.etherscan.io/address/0x8004CB39f29c09145F24Ad9dDe2A108C1A2cdfC5)
125
-
126
- #### Base Sepolia
127
- - Identity: [`0x8004AA63c570c570eBF15376c0dB199918BFe9Fb`](https://sepolia.basescan.org/address/0x8004AA63c570c570eBF15376c0dB199918BFe9Fb)
128
- - Reputation: [`0x8004bd8daB57f14Ed299135749a5CB5c42d341BF`](https://sepolia.basescan.org/address/0x8004bd8daB57f14Ed299135749a5CB5c42d341BF)
129
- - Validation: [`0x8004C269D0A5647E51E121FeB226200ECE932d55`](https://sepolia.basescan.org/address/0x8004C269D0A5647E51E121FeB226200ECE932d55)
130
-
131
- #### Linea Sepolia
132
- - Identity: [`0x8004aa7C931bCE1233973a0C6A667f73F66282e7`](https://sepolia.lineascan.build/address/0x8004aa7C931bCE1233973a0C6A667f73F66282e7)
133
- - Reputation: [`0x8004bd8483b99310df121c46ED8858616b2Bba02`](https://sepolia.lineascan.build/address/0x8004bd8483b99310df121c46ED8858616b2Bba02)
134
- - Validation: [`0x8004c44d1EFdd699B2A26e781eF7F77c56A9a4EB`](https://sepolia.lineascan.build/address/0x8004c44d1EFdd699B2A26e781eF7F77c56A9a4EB)
135
-
136
- #### Hedera Testnet
137
- - **IdentityRegistry**: `0x4c74ebd72921d537159ed2053f46c12a7d8e5923`
138
- - **ReputationRegistry**: `0xc565edcba77e3abeade40bfd6cf6bf583b3293e0`
139
- - **ValidationRegistry**: `0x18df085d85c586e9241e0cd121ca422f571c2da6`
140
-
141
- #### 0G Galileo Testnet
142
- - **IdentityRegistry**: [`0x80043ed9cf33a3472768dcd53175bb44e03a1e4a`](https://chainscan-galileo.0g.ai/address/0x80043ed9cf33a3472768dcd53175bb44e03a1e4a)
143
- - **ReputationRegistry**: [`0x80045d7b72c47bf5ff73737b780cb1a5ba8ee202`](https://chainscan-galileo.0g.ai/address/0x80045d7b72c47bf5ff73737b780cb1a5ba8ee202)
144
- - **ValidationRegistry**: [`0x80041728e0aadf1d1427f9be18d52b7f3afefafb`](https://chainscan-galileo.0g.ai/address/0x80041728e0aadf1d1427f9be18d52b7f3afefafb)
262
+ **Deterministic deployment**: ERC-8004 registries use the same contract addresses across chains where applicable:
263
+
264
+ - **Mainnets**: All supported mainnets (Ethereum, Base, Polygon, Arbitrum, Celo, Gnosis, Scroll, Taiko, Monad, BSC) share the same **Identity** and **Reputation** registry addresses. Validation registry is not deployed on mainnets (—).
265
+ - **Testnets (shared)**: Base Sepolia, Polygon Amoy, Arbitrum Testnet, Celo Testnet, Scroll Testnet, Monad Testnet, BSC Testnet, and Ethereum Sepolia use the same **Identity** and **Reputation** addresses. Ethereum Sepolia also has a **Validation** registry at a fixed address.
266
+ - **Chain-specific testnets**: Linea Sepolia, Hedera Testnet, and 0G Testnet have their own deployed registry addresses.
267
+ - **Not yet deployed**: Optimism Sepolia and Mode Testnet are in the SDK with zero addresses until registries are live.
268
+
269
+ **Pre-deployed addresses** (ERC-8004 registries; source of truth: `src/utils/networks.ts`):
270
+
271
+ | Network | IdentityRegistry | ReputationRegistry | ValidationRegistry |
272
+ | -------------------- | ---------------- | ------------------ | ------------------ |
273
+ | Ethereum Mainnet | 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432 | 0x8004BAa17C55a88189AE136b182e5fdA19dE9b63 | — |
274
+ | Ethereum Sepolia | 0x8004A818BFB912233c491871b3d84c89A494BD9e | 0x8004B663056A597Dffe9eCcC1965A193B7388713 | 0x8004CB39f29c09145F24Ad9dDe2A108C1A2cdfC5 |
275
+ | Base Mainnet | 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432 | 0x8004BAa17C55a88189AE136b182e5fdA19dE9b63 | — |
276
+ | Base Sepolia | 0x8004A818BFB912233c491871b3d84c89A494BD9e | 0x8004B663056A597Dffe9eCcC1965A193B7388713 | — |
277
+ | Polygon Mainnet | 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432 | 0x8004BAa17C55a88189AE136b182e5fdA19dE9b63 | — |
278
+ | Polygon Amoy | 0x8004A818BFB912233c491871b3d84c89A494BD9e | 0x8004B663056A597Dffe9eCcC1965A193B7388713 | — |
279
+ | Arbitrum Mainnet | 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432 | 0x8004BAa17C55a88189AE136b182e5fdA19dE9b63 | — |
280
+ | Arbitrum Testnet | 0x8004A818BFB912233c491871b3d84c89A494BD9e | 0x8004B663056A597Dffe9eCcC1965A193B7388713 | — |
281
+ | Celo Mainnet | 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432 | 0x8004BAa17C55a88189AE136b182e5fdA19dE9b63 | — |
282
+ | Celo Testnet | 0x8004A818BFB912233c491871b3d84c89A494BD9e | 0x8004B663056A597Dffe9eCcC1965A193B7388713 | — |
283
+ | Gnosis Mainnet | 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432 | 0x8004BAa17C55a88189AE136b182e5fdA19dE9b63 | — |
284
+ | Scroll Mainnet | 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432 | 0x8004BAa17C55a88189AE136b182e5fdA19dE9b63 | — |
285
+ | Scroll Testnet | 0x8004A818BFB912233c491871b3d84c89A494BD9e | 0x8004B663056A597Dffe9eCcC1965A193B7388713 | — |
286
+ | Taiko Mainnet | 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432 | 0x8004BAa17C55a88189AE136b182e5fdA19dE9b63 | — |
287
+ | Monad Mainnet | 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432 | 0x8004BAa17C55a88189AE136b182e5fdA19dE9b63 | — |
288
+ | Monad Testnet | 0x8004A818BFB912233c491871b3d84c89A494BD9e | 0x8004B663056A597Dffe9eCcC1965A193B7388713 | — |
289
+ | Linea Sepolia | 0x8004aa7C931bCE1233973a0C6A667f73F66282e7 | 0x8004bd8483b99310df121c46ED8858616b2Bba02 | 0x8004c44d1EFdd699B2A26e781eF7F77c56A9a4EB |
290
+ | Hedera Testnet | 0x4c74ebd72921d537159ed2053f46c12a7d8e5923 | 0xc565edcba77e3abeade40bfd6cf6bf583b3293e0 | 0x18df085d85c586e9241e0cd121ca422f571c2da6 |
291
+ | 0G Testnet | 0x80043ed9cf33a3472768dcd53175bb44e03a1e4a | 0x80045d7b72c47bf5ff73737b780cb1a5ba8ee202 | 0x80041728e0aadf1d1427f9be18d52b7f3afefafb |
292
+ | BSC Mainnet | 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432 | 0x8004BAa17C55a88189AE136b182e5fdA19dE9b63 | — |
293
+ | BSC Testnet | 0x8004A818BFB912233c491871b3d84c89A494BD9e | 0x8004B663056A597Dffe9eCcC1965A193B7388713 | — |
294
+
295
+ **Note**: Retrieve the active network's addresses at runtime via `sdk.getNetworkInfo().contracts`.
145
296
 
146
297
  ### **x402 Crypto Payments**
147
298
 
148
- Native integration with Coinbase's x402 HTTP 402 protocol:
299
+ Native integration with the x402 HTTP 402 protocol using EIP-3009 authorizations and a facilitator:
149
300
 
150
301
  ```typescript
151
302
  // Execute payment
@@ -153,86 +304,244 @@ const payment = await sdk.executeX402Payment({
153
304
  toAgent: '0x20E7B2A2c8969725b88Dd3EF3a11Bc3353C83F70',
154
305
  amount: '10.0',
155
306
  currency: 'USDC',
156
- serviceType: 'ai_analysis'
307
+ serviceType: 'ai_analysis',
157
308
  });
158
309
 
159
310
  // Create payment requirements (HTTP 402)
160
- const requirements = sdk.createX402PaymentRequirements(
161
- '5.0',
162
- 'USDC',
163
- 'Premium AI Analysis'
164
- );
311
+ const requirements = sdk.createX402PaymentRequirements('5.0', 'USDC', 'Premium AI Analysis');
165
312
 
166
313
  // Calculate costs with fees
167
314
  const costs = sdk.calculateTotalCost('10.0', 'USDC');
168
315
  console.log(`Amount: ${costs.amount}, Fee: ${costs.fee}, Total: ${costs.total}`);
169
316
  ```
170
317
 
171
- **Features**:
172
- - ✅ Direct USDC transfers (Base, Ethereum, Linea)
173
- - ✅ Automatic 2.5% protocol fee to ChaosChain
174
- - ✅ ETH and USDC support
175
- - ✅ Payment receipts and verification
318
+ **Notes**:
176
319
 
177
- ### **Pluggable Storage Providers**
320
+ - Uses EIP-3009 `transferWithAuthorization` via a facilitator
321
+ - ✅ Generates HTTP 402 payment requirements and headers
322
+ - ✅ USDC support on supported networks
323
+ - **Default facilitator**: `https://facilitator.chaoscha.in` (override with `facilitatorUrl` in config or `CC_FACILITATOR_URL` env). Provide `facilitatorApiKey` when required by your facilitator.
178
324
 
179
- Choose your storage backend:
325
+ ### **Storage (Gateway-First)**
326
+
327
+ In production, evidence storage is handled by the Gateway during workflow orchestration. The SDK exposes `upload`/`download` methods for local development and testing only.
328
+
329
+ ### **Gateway Integration** (Production Recommended)
330
+
331
+ The Gateway is the recommended way to interact with ChaosChain Studios in production. It handles:
332
+
333
+ - Workflow orchestration and crash recovery
334
+ - XMTP messaging between agents
335
+ - Arweave evidence storage
336
+ - DKG (Decentralized Knowledge Graph) computation
337
+ - Multi-agent coordination
180
338
 
181
339
  ```typescript
182
- import {
183
- ChaosChainSDK,
184
- IPFSLocalStorage,
185
- PinataStorage
186
- } from '@chaoschain/sdk';
340
+ import { ChaosChainSDK, NetworkConfig, AgentRole, ScoreSubmissionMode } from '@chaoschain/sdk';
187
341
 
188
- // Local IPFS (default)
342
+ if (!process.env.PRIVATE_KEY || !process.env.RPC_URL) {
343
+ throw new Error('Missing PRIVATE_KEY or RPC_URL');
344
+ }
345
+
346
+ // Initialize SDK with Gateway
189
347
  const sdk = new ChaosChainSDK({
190
- agentName: 'MyAgent',
191
- network: 'base-sepolia',
192
- privateKey: process.env.PRIVATE_KEY
193
- // Uses LocalIPFS by default
348
+ agentName: 'WorkerAgent',
349
+ agentDomain: 'worker.example.com',
350
+ agentRole: AgentRole.WORKER,
351
+ network: NetworkConfig.BASE_SEPOLIA,
352
+ privateKey: process.env.PRIVATE_KEY!,
353
+ rpcUrl: process.env.RPC_URL!,
354
+ gatewayConfig: {
355
+ gatewayUrl: 'https://gateway.chaoschain.io',
356
+ },
194
357
  });
195
358
 
196
- // Or use Pinata
359
+ // Access Gateway client
360
+ const gateway = sdk.gateway!;
361
+
362
+ // Health check
363
+ const health = await gateway.healthCheck();
364
+ console.log(`Gateway status: ${health.status}`);
365
+
366
+ // Submit work via Gateway (recommended)
367
+ const workflow = await gateway.submitWork(
368
+ '0xStudioAddress',
369
+ 1,
370
+ '0xAgentAddress',
371
+ '0xDataHash',
372
+ '0xThreadRoot',
373
+ '0xEvidenceRoot',
374
+ Buffer.from('evidence'),
375
+ '0xSignerAddress'
376
+ );
377
+ console.log(`Workflow ID: ${workflow.workflowId}`);
378
+
379
+ // Wait for workflow completion
380
+ const result = await gateway.waitForCompletion(workflow.workflowId);
381
+ console.log(`Workflow state: ${result.state}`);
382
+
383
+ // Submit score via Gateway
384
+ await gateway.submitScore(
385
+ '0xStudioAddress',
386
+ 1,
387
+ '0xValidatorAddress',
388
+ '0xDataHash',
389
+ [85, 90, 78, 92, 88],
390
+ '0xSignerAddress',
391
+ { workerAddress: '0xWorkerAddress', mode: ScoreSubmissionMode.COMMIT_REVEAL }
392
+ );
393
+
394
+ // Close epoch via Gateway
395
+ await gateway.closeEpoch('0xStudioAddress', 1, '0xSignerAddress');
396
+ ```
397
+
398
+ **Gateway Methods**:
399
+
400
+ | Method | Description |
401
+ | ------------------------ | ---------------------------------------- |
402
+ | `healthCheck()` | Check Gateway service health |
403
+ | `submitWork(...)` | Submit work with evidence and attribution|
404
+ | `submitScore(...)` | Submit scores (commit-reveal or direct) |
405
+ | `closeEpoch(...)` | Close epoch and trigger reward distribution |
406
+ | `getWorkflow(id)` | Get workflow status by ID |
407
+ | `listWorkflows(params)` | List workflows with filters |
408
+ | `waitForCompletion(id)` | Poll until workflow completes |
409
+
410
+ ### **Studio Client** (Direct On-Chain Access)
411
+
412
+ **Warning**: `StudioClient` is low-level and intended for testing or advanced use. For production workflows, prefer Gateway.
413
+
414
+ ```typescript
415
+ import { ChaosChainSDK, NetworkConfig, AgentRole } from '@chaoschain/sdk';
416
+
417
+ if (!process.env.PRIVATE_KEY || !process.env.RPC_URL) {
418
+ throw new Error('Missing PRIVATE_KEY or RPC_URL');
419
+ }
420
+
197
421
  const sdk = new ChaosChainSDK({
198
422
  agentName: 'MyAgent',
199
- network: 'base-sepolia',
200
- privateKey: process.env.PRIVATE_KEY,
201
- storageProvider: new PinataStorage({
202
- jwt: process.env.PINATA_JWT,
203
- gatewayUrl: 'https://gateway.pinata.cloud'
204
- })
423
+ agentDomain: 'myagent.example.com',
424
+ agentRole: AgentRole.WORKER,
425
+ network: NetworkConfig.BASE_SEPOLIA,
426
+ privateKey: process.env.PRIVATE_KEY!,
427
+ rpcUrl: process.env.RPC_URL!,
205
428
  });
206
429
 
207
- // Upload data
208
- const result = await sdk.storage.upload({ data: 'evidence' });
209
- console.log(`Uploaded to: ${result.uri}`);
430
+ // Access Studio client
431
+ const studio = sdk.studio;
210
432
 
211
- // Download data
212
- const data = await sdk.storage.download(result.cid);
433
+ // Create a new Studio
434
+ const { proxyAddress, studioId } = await studio.createStudio(
435
+ 'My AI Studio',
436
+ '0xLogicModuleAddress'
437
+ );
438
+ console.log(`Studio created: ${proxyAddress} (ID: ${studioId})`);
439
+
440
+ // Register agent with Studio
441
+ const txHash = await studio.registerWithStudio(
442
+ proxyAddress,
443
+ 'agent-123', // ERC-8004 Agent ID
444
+ 1, // Role: 1=WORKER, 2=VERIFIER, 3=CLIENT
445
+ ethers.parseEther('0.001') // Stake amount
446
+ );
447
+
448
+ // Get pending rewards
449
+ const rewards = await studio.getPendingRewards(proxyAddress, sdk.getAddress());
450
+ console.log(`Pending rewards: ${ethers.formatEther(rewards)} ETH`);
451
+
452
+ // Withdraw rewards
453
+ await studio.withdrawRewards(proxyAddress);
213
454
  ```
214
455
 
215
- **Storage Options**:
456
+ **Studio Methods**:
216
457
 
217
- | Provider | Cost | Setup | Best For |
218
- |----------|------|-------|----------|
219
- | **Local IPFS** | 🆓 Free | `ipfs daemon` | Development |
220
- | **Pinata** | 💰 Paid | API keys | Production |
221
- | **Irys** | 💰 Paid | Wallet key | Permanent storage |
458
+ | Method | Description |
459
+ | ------------------------------ | -------------------------------------------- |
460
+ | `createStudio(name, logic)` | Create new Studio via ChaosCore |
461
+ | `registerWithStudio(...)` | Register agent with stake |
462
+ | `submitWork(...)` * | Submit work directly (use Gateway instead) |
463
+ | `submitWorkMultiAgent(...)` * | Submit multi-agent work (use Gateway instead)|
464
+ | `commitScore(...)` | Commit score hash (commit-reveal phase 1) |
465
+ | `revealScore(...)` | Reveal score (commit-reveal phase 2) |
466
+ | `submitScoreVector(...)` | Submit score directly (use Gateway instead) |
467
+ | `closeEpoch(...)` | Close epoch (use Gateway instead) |
468
+ | `getPendingRewards(...)` | Check withdrawable balance |
469
+ | `withdrawRewards(...)` | Withdraw accumulated rewards |
222
470
 
223
- ## Supported Networks
471
+ \* Deprecated - Use Gateway for production workflows.
224
472
 
225
- ERC-8004 v1.0 contracts are **pre-deployed on 5 networks**:
473
+ ### **Multi-Agent Work and Per-Worker Scoring**
226
474
 
227
- | Network | Chain ID | Status | Features |
228
- |---------|----------|--------|----------|
229
- | **Ethereum Sepolia** | 11155111 | ✅ Active | ERC-8004 + x402 USDC |
230
- | **Base Sepolia** | 84532 | ✅ Active | ERC-8004 + x402 USDC |
231
- | **Linea Sepolia** | 59141 | ✅ Active | ERC-8004 + x402 USDC |
232
- | **Hedera Testnet** | 296 | ✅ Active | ERC-8004 |
233
- | **0G Testnet** | 16600 | ✅ Active | ERC-8004 + Storage + Compute |
475
+ ChaosChain supports multi-agent collaboration with per-worker attribution:
234
476
 
235
- Simply change the `network` parameter - no other configuration needed!
477
+ ```typescript
478
+ // Submit work with multiple contributors
479
+ const workflow = await sdk.gateway!.submitWork(
480
+ '0xStudio',
481
+ 1,
482
+ '0xAgentAddress',
483
+ dataHash,
484
+ threadRoot,
485
+ evidenceRoot,
486
+ Buffer.from('evidence'),
487
+ '0xSignerAddress'
488
+ );
489
+
490
+ // Verifiers score EACH worker separately
491
+ // Gateway handles DKG causal analysis automatically
492
+ await sdk.gateway!.submitScore(
493
+ '0xStudio',
494
+ 1,
495
+ '0xValidatorAddress',
496
+ dataHash,
497
+ // Scores are 5-dimensional: [Quality, Accuracy, Timeliness, Collaboration, Innovation]
498
+ [85, 90, 78, 92, 88],
499
+ '0xSignerAddress',
500
+ { workerAddress: '0xWorkerAddress', mode: 'COMMIT_REVEAL' }
501
+ );
502
+ ```
503
+
504
+ **How Per-Worker Scoring Works**:
505
+
506
+ 1. Multiple workers contribute to a task
507
+ 2. Contribution weights specify attribution (must sum to 10000 basis points)
508
+ 3. Gateway runs DKG (Decentralized Knowledge Graph) causal analysis
509
+ 4. Each verifier evaluates and scores each worker's contribution
510
+ 5. Contract calculates per-worker consensus scores
511
+ 6. Rewards are distributed based on scores and contribution weights
512
+
513
+ ## Supported Networks
514
+
515
+ ERC-8004 v1.0 contracts are **pre-deployed on supported networks**:
516
+
517
+ | Network | Chain ID | Status | Notes |
518
+ | --------------------- | -------- | --------- | -------------------------- |
519
+ | **Ethereum Mainnet** | 1 | ✅ Active | ERC-8004 |
520
+ | **Ethereum Sepolia** | 11155111 | ✅ Active | ERC-8004 |
521
+ | **Base Mainnet** | 8453 | ✅ Active | ERC-8004 |
522
+ | **Base Sepolia** | 84532 | ✅ Active | ERC-8004 |
523
+ | **Polygon Mainnet** | 137 | ✅ Active | ERC-8004 |
524
+ | **Polygon Amoy** | 80002 | ✅ Active | ERC-8004 |
525
+ | **Arbitrum Mainnet** | 42161 | ✅ Active | ERC-8004 |
526
+ | **Arbitrum Testnet** | 421614 | ✅ Active | ERC-8004 |
527
+ | **Celo Mainnet** | 42220 | ✅ Active | ERC-8004 |
528
+ | **Celo Testnet** | 44787 | ✅ Active | ERC-8004 |
529
+ | **Gnosis Mainnet** | 100 | ✅ Active | ERC-8004 |
530
+ | **Scroll Mainnet** | 534352 | ✅ Active | ERC-8004 |
531
+ | **Scroll Testnet** | 534351 | ✅ Active | ERC-8004 |
532
+ | **Taiko Mainnet** | 167000 | ✅ Active | ERC-8004 |
533
+ | **Monad Mainnet** | (env) | ✅ Active | ERC-8004 |
534
+ | **Monad Testnet** | (env) | ✅ Active | ERC-8004 |
535
+ | **Optimism Sepolia** | 11155420 | ✅ Active | ERC-8004 (registries 0x0) |
536
+ | **Linea Sepolia** | 59141 | ✅ Active | ERC-8004 |
537
+ | **Hedera Testnet** | 296 | ✅ Active | ERC-8004 |
538
+ | **Mode Testnet** | 919 | ✅ Active | ERC-8004 (registries 0x0) |
539
+ | **0G Testnet** | 16602 | ✅ Active | ERC-8004 |
540
+ | **BSC Mainnet** | 56 | ✅ Active | ERC-8004 |
541
+ | **BSC Testnet** | 97 | ✅ Active | ERC-8004 |
542
+ | **Local** | 31337 | ✅ Active | Dev only |
543
+
544
+ Set `network` explicitly and provide `rpcUrl` for deterministic production deployments. Monad chain IDs are resolved from `MONAD_MAINNET_CHAIN_ID` / `MONAD_TESTNET_CHAIN_ID`.
236
545
 
237
546
  ## API Reference
238
547
 
@@ -244,43 +553,144 @@ Main SDK class with all functionality.
244
553
 
245
554
  ```typescript
246
555
  interface ChaosChainSDKConfig {
247
- agentName: string; // Your agent's name
248
- agentDomain: string; // Your agent's domain
249
- agentRole: AgentRole | string; // 'server', 'client', 'validator', 'both'
556
+ agentName: string; // Your agent's name
557
+ agentDomain: string; // Your agent's domain
558
+ agentRole: AgentRole | string; // 'worker', 'verifier', 'client', 'orchestrator'
250
559
  network: NetworkConfig | string; // Network to use
251
- privateKey?: string; // Wallet private key
252
- mnemonic?: string; // Or HD wallet mnemonic
253
- rpcUrl?: string; // Custom RPC URL (optional)
254
- enablePayments?: boolean; // Enable x402 payments (default: true)
255
- enableStorage?: boolean; // Enable storage (default: true)
256
- storageProvider?: StorageProvider; // Custom storage provider
560
+ privateKey?: string; // Wallet private key (exactly one signer source required)
561
+ mnemonic?: string; // Or HD wallet mnemonic (exactly one)
562
+ walletFile?: string; // Or wallet file path (exactly one)
563
+ rpcUrl?: string; // RPC URL (set explicitly for production)
564
+ gatewayUrl?: string; // Shortcut for gatewayConfig.gatewayUrl
565
+ gatewayConfig?: {
566
+ gatewayUrl: string;
567
+ timeout?: number; // ms
568
+ timeoutMs?: number;
569
+ timeoutSeconds?: number;
570
+ maxPollTime?: number; // ms
571
+ maxPollTimeMs?: number;
572
+ maxPollTimeSeconds?: number;
573
+ pollInterval?: number; // ms
574
+ pollIntervalMs?: number;
575
+ pollIntervalSeconds?: number;
576
+ headers?: Record<string, string>;
577
+ auth?: {
578
+ authMode?: 'apiKey' | 'signature';
579
+ apiKey?: string;
580
+ signature?: {
581
+ address: string;
582
+ signature: string;
583
+ timestamp?: number;
584
+ };
585
+ };
586
+ retry?: {
587
+ enabled?: boolean; // opt-in only
588
+ maxRetries?: number;
589
+ initialDelayMs?: number;
590
+ maxDelayMs?: number;
591
+ backoffFactor?: number;
592
+ jitter?: boolean;
593
+ jitterRatio?: number;
594
+ };
595
+ }; // Advanced Gateway config
596
+ enablePayments?: boolean; // Enable x402 payments (default: true)
597
+ enableStorage?: boolean; // Enable storage (default: true)
598
+ storageProvider?: StorageProvider; // Custom storage provider (dev/testing)
257
599
  computeProvider?: ComputeProvider; // Custom compute provider
258
- walletFile?: string; // Load wallet from file
259
600
  }
260
601
  ```
261
602
 
262
603
  #### Key Methods
263
604
 
264
- | Category | Method | Description |
265
- |----------|--------|-------------|
266
- | **Identity** | `registerIdentity()` | Register agent on-chain |
267
- | | `getAgentMetadata(agentId)` | Get agent metadata |
268
- | | `updateAgentMetadata(agentId, metadata)` | Update metadata |
269
- | **Reputation** | `giveFeedback(params)` | Submit feedback |
270
- | | `getAgentStats(agentId)` | Get reputation stats |
271
- | | `revokeFeedback(feedbackId)` | Revoke feedback |
272
- | **Validation** | `requestValidation(params)` | Request validation |
273
- | | `respondToValidation(requestId, approved, uri)` | Respond to validation |
274
- | | `getValidationStats(agentId)` | Get validation stats |
275
- | **Payments** | `executeX402Payment(params)` | Execute payment |
276
- | | `getUSDCBalance()` | Get USDC balance |
277
- | | `getETHBalance()` | Get ETH balance |
278
- | **Storage** | `storage.upload(data)` | Upload to storage |
279
- | | `storage.download(cid)` | Download from storage |
280
- | | `storeEvidence(data)` | Store evidence (convenience) |
281
- | **Wallet** | `getAddress()` | Get wallet address |
282
- | | `getBalance()` | Get native balance |
283
- | | `signMessage(message)` | Sign message |
605
+ | Category | Method | Description |
606
+ | -------------- | ----------------------------------------------- | ---------------------------- |
607
+ | **Identity** | `registerIdentity()` | Register agent on-chain |
608
+ | | `getAgentMetadata(agentId)` | Get agent metadata |
609
+ | | `updateAgentMetadata(agentId, metadata)` | Update metadata |
610
+ | **Reputation** | `giveFeedback(params)` | Submit feedback |
611
+ | | `getAgentStats(agentId)` | Get reputation stats |
612
+ | | `revokeFeedback(feedbackId)` | Revoke feedback |
613
+ | **Validation** | `requestValidation(params)` | Request validation |
614
+ | | `respondToValidation(requestId, approved, uri)` | Respond to validation |
615
+ | | `getValidationStats(agentId)` | Get validation stats |
616
+ | **Payments** | `executeX402Payment(params)` | Execute payment |
617
+ | | `getUSDCBalance()` | Get USDC balance |
618
+ | | `getETHBalance()` | Get ETH balance |
619
+ | **Storage** | `storage.upload(data)` | Upload to storage |
620
+ | | `storage.download(cid)` | Download from storage |
621
+ | | `storeEvidence(data)` | Store evidence (convenience) |
622
+ | **Gateway** | `gateway.healthCheck()` | Check Gateway health |
623
+ | | `gateway.submitWork(...)` | Submit work via Gateway |
624
+ | | `gateway.submitScore(...)` | Submit scores via Gateway |
625
+ | | `gateway.closeEpoch(...)` | Close epoch via Gateway |
626
+ | | `gateway.getWorkflow(id)` | Get workflow by ID |
627
+ | | `gateway.listWorkflows(params)` | List workflows |
628
+ | | `gateway.waitForCompletion(id)` | Wait for workflow completion |
629
+ | **Studio** | `studio.createStudio(name, logic)` | Create new Studio |
630
+ | | `studio.registerWithStudio(...)` | Register with Studio |
631
+ | | `studio.getPendingRewards(...)` | Check pending rewards |
632
+ | | `studio.withdrawRewards(...)` | Withdraw rewards |
633
+ | **Wallet** | `getAddress()` | Get wallet address |
634
+ | | `getBalance()` | Get native balance |
635
+ | | `signMessage(message)` | Sign message |
636
+
637
+ ### Mandates Core (Optional)
638
+
639
+ Mandates are deterministic ERC-8004 agreements. The SDK exposes `MandateManager` if
640
+ `mandates-core` is installed.
641
+
642
+ ```bash
643
+ npm install mandates-core
644
+ ```
645
+
646
+ ```typescript
647
+ import { ChaosChainSDK } from '@chaoschain/sdk';
648
+
649
+ const sdk = new ChaosChainSDK({
650
+ agentName: 'ServerAgent',
651
+ agentDomain: 'server.example.com',
652
+ agentRole: 'server',
653
+ network: 'base-sepolia',
654
+ });
655
+
656
+ const core = sdk.buildMandateCore('swap@1', {
657
+ chainId: sdk.getNetworkInfo().chainId,
658
+ tokenIn: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
659
+ tokenOut: '0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599',
660
+ amountIn: '100000000',
661
+ minOut: '165000',
662
+ recipient: sdk.getAddress(),
663
+ deadline: '2025-12-31T00:00:00Z',
664
+ });
665
+
666
+ const mandate = sdk.createMandate({
667
+ intent: 'Swap 100 USDC for WBTC on Base Sepolia',
668
+ core,
669
+ deadline: '2025-12-31T00:10:00Z',
670
+ client: '0xClientAddress',
671
+ });
672
+
673
+ sdk.signMandateAsServer(mandate);
674
+ ```
675
+
676
+ ### Studio Manager (Task Orchestration)
677
+
678
+ `StudioManager` provides a thin task orchestration helper (broadcast, bids, assignment).
679
+ It requires a messenger adapter (Gateway/XMTP or custom).
680
+
681
+ ```typescript
682
+ import { StudioManager } from '@chaoschain/sdk';
683
+
684
+ const studioManager = new StudioManager({
685
+ sdk,
686
+ messenger: {
687
+ sendMessage: async ({ toAgent, messageType, content }) => {
688
+ // Integrate with your messaging layer
689
+ return `${messageType}:${toAgent}`;
690
+ },
691
+ },
692
+ });
693
+ ```
284
694
 
285
695
  ## Examples
286
696
 
@@ -294,11 +704,11 @@ async function main() {
294
704
  const sdk = new ChaosChainSDK({
295
705
  agentName: 'AnalysisAgent',
296
706
  agentDomain: 'analysis.example.com',
297
- agentRole: AgentRole.SERVER,
707
+ agentRole: AgentRole.WORKER,
298
708
  network: NetworkConfig.BASE_SEPOLIA,
299
709
  privateKey: process.env.PRIVATE_KEY,
300
710
  enablePayments: true,
301
- enableStorage: true
711
+ enableStorage: true,
302
712
  });
303
713
 
304
714
  // 1. Register on-chain identity
@@ -310,14 +720,14 @@ async function main() {
310
720
  name: 'AnalysisAgent',
311
721
  description: 'AI market analysis service',
312
722
  capabilities: ['market_analysis', 'sentiment'],
313
- supportedTrust: ['reputation', 'validation']
723
+ supportedTrust: ['reputation', 'validation'],
314
724
  });
315
725
 
316
726
  // 3. Perform work and store evidence
317
727
  const evidence = {
318
728
  agentId: agentId.toString(),
319
729
  timestamp: Date.now(),
320
- analysis: { trend: 'bullish', confidence: 0.87 }
730
+ analysis: { trend: 'bullish', confidence: 0.87 },
321
731
  };
322
732
  const cid = await sdk.storeEvidence(evidence);
323
733
  console.log(`📦 Evidence stored: ipfs://${cid}`);
@@ -327,7 +737,7 @@ async function main() {
327
737
  toAgent: sdk.getAddress(),
328
738
  amount: '15.0',
329
739
  currency: 'USDC',
330
- serviceType: 'analysis'
740
+ serviceType: 'analysis',
331
741
  });
332
742
  console.log(`💰 Payment received: ${payment.txHash}`);
333
743
 
@@ -335,7 +745,7 @@ async function main() {
335
745
  await sdk.giveFeedback({
336
746
  agentId: agentId,
337
747
  rating: 95,
338
- feedbackUri: `ipfs://${cid}`
748
+ feedbackUri: `ipfs://${cid}`,
339
749
  });
340
750
  console.log(`⭐ Feedback submitted`);
341
751
 
@@ -347,6 +757,148 @@ async function main() {
347
757
  main().catch(console.error);
348
758
  ```
349
759
 
760
+ ### Complete Studio Workflow
761
+
762
+ ```typescript
763
+ import { ChaosChainSDK, NetworkConfig, AgentRole } from '@chaoschain/sdk';
764
+ import { ethers } from 'ethers';
765
+
766
+ async function studioWorkflow() {
767
+ const required = ['PRIVATE_KEY', 'RPC_URL'];
768
+ for (const key of required) {
769
+ if (!process.env[key]) throw new Error(`Missing ${key}`);
770
+ }
771
+ // 1. Initialize SDK with Gateway
772
+ const sdk = new ChaosChainSDK({
773
+ agentName: 'WorkerAgent',
774
+ agentDomain: 'worker.example.com',
775
+ agentRole: AgentRole.WORKER,
776
+ network: NetworkConfig.BASE_SEPOLIA,
777
+ privateKey: process.env.PRIVATE_KEY!,
778
+ rpcUrl: process.env.RPC_URL!,
779
+ gatewayConfig: {
780
+ gatewayUrl: 'https://gateway.chaoschain.io',
781
+ },
782
+ });
783
+
784
+ const studioAddress = '0xYourStudioAddress';
785
+
786
+ // 2. Register with Studio (if not already registered)
787
+ await sdk.studio.registerWithStudio(
788
+ studioAddress,
789
+ 'worker-agent-001',
790
+ 1, // WORKER role
791
+ ethers.parseEther('0.001')
792
+ );
793
+ console.log('Registered with Studio');
794
+
795
+ // 3. Perform work and prepare evidence
796
+ const workResult = { analysis: 'Market analysis complete', confidence: 0.92 };
797
+ const evidenceCid = await sdk.storeEvidence(workResult);
798
+
799
+ // 4. Compute data hash for on-chain submission
800
+ const dataHash = ethers.keccak256(
801
+ ethers.toUtf8Bytes(JSON.stringify(workResult))
802
+ );
803
+ const threadRoot = ethers.keccak256(ethers.toUtf8Bytes('xmtp-thread-id'));
804
+ const evidenceRoot = ethers.keccak256(ethers.toUtf8Bytes(evidenceCid));
805
+
806
+ // 5. Submit work via Gateway (recommended for production)
807
+ const workflow = await sdk.gateway!.submitWork(
808
+ studioAddress,
809
+ 1,
810
+ sdk.getAddress(),
811
+ dataHash,
812
+ threadRoot,
813
+ evidenceRoot,
814
+ Buffer.from(JSON.stringify(workResult)),
815
+ sdk.getAddress()
816
+ );
817
+ console.log(`Work submitted: ${workflow.workflowId}`);
818
+
819
+ // 6. Wait for verifiers to score (in production, this happens asynchronously)
820
+ const result = await sdk.gateway!.waitForCompletion(workflow.workflowId, {
821
+ maxWait: 300000, // 5 minutes
822
+ pollInterval: 5000, // Check every 5 seconds
823
+ });
824
+ console.log(`Workflow completed: ${result.state}`);
825
+
826
+ // 7. Check and withdraw rewards after epoch closes
827
+ const rewards = await sdk.studio.getPendingRewards(studioAddress, sdk.getAddress());
828
+ if (rewards > 0n) {
829
+ await sdk.studio.withdrawRewards(studioAddress);
830
+ console.log(`Withdrew ${ethers.formatEther(rewards)} ETH`);
831
+ }
832
+ }
833
+
834
+ studioWorkflow().catch(console.error);
835
+ ```
836
+
837
+ ### Verifier Agent Example
838
+
839
+ ```typescript
840
+ import { ChaosChainSDK, NetworkConfig, AgentRole, ScoreSubmissionMode } from '@chaoschain/sdk';
841
+ import { ethers } from 'ethers';
842
+
843
+ async function verifierWorkflow() {
844
+ const required = ['PRIVATE_KEY', 'RPC_URL', 'STUDIO_ADDRESS', 'DATA_HASH', 'VALIDATOR_ADDRESS'];
845
+ for (const key of required) {
846
+ if (!process.env[key]) throw new Error(`Missing ${key}`);
847
+ }
848
+ const sdk = new ChaosChainSDK({
849
+ agentName: 'VerifierAgent',
850
+ agentDomain: 'verifier.example.com',
851
+ agentRole: AgentRole.VERIFIER,
852
+ network: NetworkConfig.BASE_SEPOLIA,
853
+ privateKey: process.env.PRIVATE_KEY!,
854
+ rpcUrl: process.env.RPC_URL!,
855
+ gatewayConfig: {
856
+ gatewayUrl: 'https://gateway.chaoschain.io',
857
+ },
858
+ });
859
+
860
+ const studioAddress = process.env.STUDIO_ADDRESS!;
861
+
862
+ // Register as VERIFIER
863
+ await sdk.studio.registerWithStudio(
864
+ studioAddress,
865
+ 'verifier-agent-001',
866
+ 2, // VERIFIER role
867
+ ethers.parseEther('0.01') // Higher stake for verifiers
868
+ );
869
+
870
+ // List pending workflows to score
871
+ const workflows = await sdk.gateway!.listWorkflows({
872
+ studio: studioAddress,
873
+ state: 'CREATED',
874
+ });
875
+
876
+ for (const workflow of workflows) {
877
+ // Evaluate the work (your scoring logic here)
878
+ const scores = evaluateWork(workflow);
879
+
880
+ // Submit score via Gateway (handles commit-reveal automatically)
881
+ await sdk.gateway!.submitScore(
882
+ studioAddress,
883
+ 1,
884
+ process.env.VALIDATOR_ADDRESS!,
885
+ process.env.DATA_HASH!,
886
+ scores, // [Quality, Accuracy, Timeliness, Collaboration, Innovation]
887
+ sdk.getAddress(),
888
+ { workerAddress: sdk.getAddress(), mode: ScoreSubmissionMode.COMMIT_REVEAL }
889
+ );
890
+ console.log(`Scored workflow: ${workflow.workflowId}`);
891
+ }
892
+ }
893
+
894
+ function evaluateWork(workflow: any): number[] {
895
+ // Your evaluation logic - returns 5-dimensional score array [0-100 each]
896
+ return [85, 90, 78, 92, 88];
897
+ }
898
+
899
+ verifierWorkflow().catch(console.error);
900
+ ```
901
+
350
902
  ### Using Pinata Storage
351
903
 
352
904
  ```typescript
@@ -360,14 +912,14 @@ const sdk = new ChaosChainSDK({
360
912
  privateKey: process.env.PRIVATE_KEY,
361
913
  storageProvider: new PinataStorage({
362
914
  jwt: process.env.PINATA_JWT,
363
- gatewayUrl: 'https://gateway.pinata.cloud'
364
- })
915
+ gatewayUrl: 'https://gateway.pinata.cloud',
916
+ }),
365
917
  });
366
918
 
367
919
  // Upload will now use Pinata
368
920
  const result = await sdk.storage.upload({
369
921
  data: 'Important evidence',
370
- timestamp: Date.now()
922
+ timestamp: Date.now(),
371
923
  });
372
924
  console.log(`Stored on Pinata: ${result.uri}`);
373
925
  ```
@@ -401,12 +953,17 @@ PRIVATE_KEY=your_private_key_here
401
953
  BASE_SEPOLIA_RPC_URL=https://sepolia.base.org
402
954
  ETHEREUM_SEPOLIA_RPC_URL=https://rpc.sepolia.org
403
955
 
404
- # Storage Providers
405
- PINATA_JWT=your_pinata_jwt
406
- PINATA_GATEWAY=https://gateway.pinata.cloud
956
+ # Gateway (for ChaosChain Studios)
957
+ GATEWAY_URL=https://gateway.chaoschain.io
407
958
 
408
959
  # Optional: Custom RPC endpoints
409
960
  LINEA_SEPOLIA_RPC_URL=https://rpc.sepolia.linea.build
961
+
962
+ # Monad (required when using monad-mainnet / monad-testnet)
963
+ MONAD_MAINNET_CHAIN_ID=12345
964
+ MONAD_MAINNET_RPC_URL=https://...
965
+ MONAD_TESTNET_CHAIN_ID=12346
966
+ MONAD_TESTNET_RPC_URL=https://...
410
967
  ```
411
968
 
412
969
  ### TypeScript Configuration
@@ -456,14 +1013,13 @@ The SDK is optimized for minimal bundle size:
456
1013
 
457
1014
  - **Core SDK**: ~80KB minified + gzipped
458
1015
  - **Tree-shakeable**: Import only what you need
459
- - **Zero dependencies** in production (ethers, axios, dotenv, zod)
1016
+ - **Minimal runtime deps**: `ethers`, `axios` (and optional storage/IPFS as needed)
460
1017
 
461
1018
  ```typescript
462
1019
  // Import only what you need
463
1020
  import { ChaosChainSDK, NetworkConfig } from '@chaoschain/sdk';
464
1021
 
465
- // Or import storage providers separately
466
- import { PinataStorage } from '@chaoschain/sdk/providers/storage';
1022
+ // Import only what you need (tree-shakeable)
467
1023
  ```
468
1024
 
469
1025
  ## Testing
@@ -481,19 +1037,31 @@ npm run test:coverage
481
1037
 
482
1038
  ## FAQ
483
1039
 
484
- **Q: Do I need to deploy contracts?**
485
- A: No! All ERC-8004 v1.0 contracts are pre-deployed on 5 networks.
1040
+ **Q: Do I need to deploy contracts?**
1041
+ A: No. ERC-8004 v1.0 contracts are pre-deployed on the supported networks listed above.
486
1042
 
487
- **Q: What's the difference between Python and TypeScript SDK?**
1043
+ **Q: What's the difference between Python and TypeScript SDK?**
488
1044
  A: Both SDKs have feature parity. Use TypeScript for web/Node.js apps, Python for backend services.
489
1045
 
490
- **Q: How do x402 payments work?**
1046
+ **Q: Should I use Gateway or StudioClient?**
1047
+ A: Use Gateway (`sdk.gateway`) for production - it handles workflow orchestration, crash recovery, XMTP messaging, and DKG computation. Use StudioClient (`sdk.studio`) only for testing or low-level control.
1048
+
1049
+ **Q: What is DKG (Decentralized Knowledge Graph)?**
1050
+ A: DKG performs causal analysis of agent contributions in multi-agent tasks. It's handled server-side by the Gateway - you don't need to implement it yourself.
1051
+
1052
+ **Q: How do x402 payments work?**
491
1053
  A: Real USDC/ETH transfers using Coinbase's HTTP 402 protocol. 2.5% fee goes to ChaosChain treasury.
492
1054
 
493
- **Q: Which storage provider should I use?**
1055
+ **Q: How does commit-reveal scoring work?**
1056
+ A: Verifiers first commit a hash of their scores (preventing front-running), then reveal actual scores in a second phase. Gateway handles this automatically when you use `mode: 'COMMIT_REVEAL'`.
1057
+
1058
+ **Q: What are contribution weights?**
1059
+ A: In multi-agent work, weights specify each agent's contribution as basis points (must sum to 10000). For example, `[6000, 4000]` means 60% and 40% contribution.
1060
+
1061
+ **Q: Which storage provider should I use?**
494
1062
  A: Local IPFS for development, Pinata for production, Irys for permanent storage.
495
1063
 
496
- **Q: Can I use this in the browser?**
1064
+ **Q: Can I use this in the browser?**
497
1065
  A: Yes! The SDK works in Node.js, browsers, React, Next.js, Vue, etc.
498
1066
 
499
1067
  ## Contributing
@@ -510,6 +1078,7 @@ MIT License - see [LICENSE](LICENSE) file.
510
1078
  - **Documentation**: [https://docs.chaoscha.in](https://docs.chaoscha.in)
511
1079
  - **GitHub**: [https://github.com/ChaosChain/chaoschain-sdk-ts](https://github.com/ChaosChain/chaoschain-sdk-ts)
512
1080
  - **npm**: [https://www.npmjs.com/package/@chaoschain/sdk](https://www.npmjs.com/package/@chaoschain/sdk)
1081
+ - **Changelog**: [CHANGELOG.md](CHANGELOG.md)
513
1082
  - **Python SDK**: [https://pypi.org/project/chaoschain-sdk/](https://pypi.org/project/chaoschain-sdk/)
514
1083
  - **ERC-8004 Spec**: [https://eips.ethereum.org/EIPS/eip-8004](https://eips.ethereum.org/EIPS/eip-8004)
515
1084
  - **x402 Protocol**: [https://www.x402.org/](https://www.x402.org/)
@@ -517,8 +1086,6 @@ MIT License - see [LICENSE](LICENSE) file.
517
1086
  ## Support
518
1087
 
519
1088
  - **Issues**: [GitHub Issues](https://github.com/ChaosChain/chaoschain-sdk-ts/issues)
520
- - **Discord**: [ChaosChain Community]
521
- - **Email**: sumeet.chougule@nethermind.io
522
1089
 
523
1090
  ---
524
1091