cronos-agent-wallet 1.2.6 → 1.2.9

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
@@ -49,32 +49,45 @@ npm install @cronos-merchant/sdk ethers
49
49
  ## Quick Start
50
50
 
51
51
  ```typescript
52
- import { AgentClient, AgentError } from "@cronos-merchant/sdk";
52
+ import { AgentClient, AgentAdmin, AgentError } from "@cronos-merchant/sdk";
53
53
 
54
- // 1. Initialize
55
- const agent = new AgentClient({
56
- privateKey: process.env.AGENT_KEY,
57
- rpcUrl: "https://evm-t3.cronos.org", // Cronos Testnet
54
+ // Configuration
55
+ const CONFIG = {
56
+ key: process.env.AGENT_KEY,
57
+ rpc: "https://evm-t3.cronos.org",
58
58
  chainId: 338,
59
- usdcAddress: "0xc01..." // Your payment token
60
- });
59
+ usdc: "0xc01...",
60
+ limits: { daily: 10, perTx: 1 }
61
+ };
61
62
 
62
63
  async function main() {
63
64
  try {
64
- // 2. Fetch paid resources (just like axios/fetch)
65
- const response = await agent.fetch<{ answer: string }>("http://localhost:3000/premium", {
65
+ // 1. [Setup] Seal Policy On-Chain (Run once or on change)
66
+ await AgentAdmin.setPolicy({ privateKey: CONFIG.key }, {
67
+ dailyLimit: CONFIG.limits.daily,
68
+ maxPerTransaction: CONFIG.limits.perTx
69
+ });
70
+
71
+ // 2. [Runtime] Initialize Agent
72
+ const agent = new AgentClient({
73
+ privateKey: CONFIG.key,
74
+ rpcUrl: CONFIG.rpc,
75
+ chainId: CONFIG.chainId,
76
+ usdcAddress: CONFIG.usdc,
77
+ dailyLimit: CONFIG.limits.daily, // Must match setPolicy
78
+ maxPerTransaction: CONFIG.limits.perTx // Must match setPolicy
79
+ });
80
+
81
+ // 3. [Usage] Fetch paid resources
82
+ const response = await agent.fetch("http://localhost:3000/premium", {
66
83
  method: "POST",
67
84
  body: { prompt: "Hello World" }
68
85
  });
69
86
 
70
- console.log("Success:", response.answer);
87
+ console.log("Success:", response);
71
88
 
72
89
  } catch (err: any) {
73
- // 3. Handle Errors
74
- if (err instanceof AgentError) {
75
- console.error(`Status: ${err.status}`); // 402, 500
76
- console.error(`Code: ${err.code}`); // POLICY_REJECTED, NETWORK_ERROR
77
- }
90
+ if (err instanceof AgentError) console.error(`Error ${err.code}: ${err.message}`);
78
91
  }
79
92
  }
80
93
  ```
@@ -89,7 +102,8 @@ async function main() {
89
102
  | `rpcUrl` | `string` | Yes | RPC Endpoint (e.g., Cronos Testnet). |
90
103
  | `chainId` | `number` | Yes | Chain ID (e.g., 338). Sent to backend for negotiation. |
91
104
  | `usdcAddress` | `string` | Yes | ERC20 Token Address used for payment. |
92
- | `dailyLimit` | `number` | No | Max USDC allowed to spend per 24h. Default: 1.0 |
105
+ | `dailyLimit` | `number` | No | Max USDC allowed to spend per 24h. Default: 1.0. |
106
+ | `maxPerTransaction` | `number` | No | Max USDC allowed per single transaction. Default: 0.5. |
93
107
  | `strictPolicy` | `boolean` | No | If `true`, Agent crashes if local config hash != on-chain hash. Default: `true`. |
94
108
  | `anchors` | `object` | No | On-chain registry addresses. Auto-filled for Cronos Testnet. |
95
109
  | `analyticsUrl` | `string` | No | URL for centralized logging of payment decisions (e.g. `https://api.myapp.com/analytics`). |
@@ -97,24 +111,42 @@ async function main() {
97
111
  | `trustedFacilitators` | `string[]` | No | List of Gateway URLs to trust (e.g., localhost). |
98
112
 
99
113
  ## 🛡️ Security Workflow (Strict Mode)
100
-
101
- When `strictPolicy` is `true` (default), you must register your configuration hash on-chain whenever you change limits.
102
-
103
- 1. **Define Limits**: Set `dailyLimit` in your code.
104
- 2. **Seal Policy**: Use the Admin helper to write the hash to the chain.
105
-
114
+
115
+ When `strictPolicy` is `true` (default), the Agent **verifies on-chain authority** before starting. This ensures that no one (including a compromised local server) can tamper with spending limits.
116
+
117
+ **Step 1. Define Limits in Code**
118
+ You must set your desired limits in your `AgentClient` (or environment variables).
119
+
120
+ ```typescript
121
+ const agent = new AgentClient({
122
+ ...
123
+ dailyLimit: 10,
124
+ maxPerTransaction: 1, // Optional, defaults to 0.5
125
+ ...
126
+ });
127
+ ```
128
+
129
+ **Step 2. Seal Policy On-Chain**
130
+ Use the `AgentAdmin` tool to write these exact limits to the blockchain. This generates a cryptographic hash.
131
+
106
132
  ```typescript
107
133
  import { AgentAdmin } from "@cronos-merchant/sdk";
108
134
 
135
+ // Run this ONCE (or whenever you change limits)
109
136
  await AgentAdmin.setPolicy({
110
- privateKey: process.env.AGENT_KEY
137
+ privateKey: process.env.ADMIN_KEY
111
138
  }, {
112
- dailyLimit: 0.5,
113
- maxPerTransaction: 0.5
139
+ dailyLimit: 10, // MUST MATCH AgentClient config
140
+ maxPerTransaction: 1 // MUST MATCH AgentClient config
114
141
  });
115
142
  ```
116
-
117
- 3. **Run Agent**: The Agent checks `Local Limit == On-Chain Limit` before spending.
143
+
144
+ **Step 3. Run Agent**
145
+ When the Agent starts:
146
+ 1. Calculates hash of local `dailyLimit` + `maxPerTransaction`.
147
+ 2. Fetches the hash from the On-Chain Registry.
148
+ 3. **Matches?** -> Runs.
149
+ 4. **Mismatch?** -> Crashes (FAIL-SAFE).
118
150
 
119
151
  ## API Reference
120
152
 
@@ -192,12 +192,15 @@ class AgentWallet {
192
192
  const localHash = hashPolicy(this.config);
193
193
  // Note: We check if on-chain hash is set (non-zero) before enforcing
194
194
  if (onChain.policyHash !== ethers_1.ethers.ZeroHash && onChain.policyHash !== localHash) {
195
- const msg = `Policy Hash Mismatch! Local: ${localHash}, Chain: ${onChain.policyHash}`;
195
+ const msg = `[SECURITY] Policy Mismatch! Your local config (dailyLimit/maxPerTx) differs from the on-chain policy. \n` +
196
+ ` -> Local Hash: ${localHash}\n` +
197
+ ` -> Chain Hash: ${onChain.policyHash}\n` +
198
+ ` -> Tip: Ensure your 'AgentClient' config matches what you deployed via 'set_policy'.`;
196
199
  if (this.config?.strictPolicy) {
197
200
  throw new Error(msg);
198
201
  }
199
202
  else {
200
- console.warn(`[AgentWallet] WARN: ${msg}. Running in PERMISSIVE mode.`);
203
+ console.warn(`[AgentWallet] WARN: ${msg}\n -> Running in PERMISSIVE mode.`);
201
204
  }
202
205
  }
203
206
  else {
@@ -205,7 +208,12 @@ class AgentWallet {
205
208
  }
206
209
  }
207
210
  catch (error) {
208
- console.error("[AgentWallet] Anchor check failed:", error.message);
211
+ // Only log here if we are NOT throwing (i.e. unexpected errors), or if permissive.
212
+ // If strict, the caller (constructor) will catch and log/exit, so we avoid double logs.
213
+ if (!this.config?.strictPolicy) {
214
+ console.error("[AgentWallet] Anchor check failed:", error.message);
215
+ }
216
+ // Propagate if strict
209
217
  if (this.config?.strictPolicy)
210
218
  throw error;
211
219
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cronos-agent-wallet",
3
- "version": "1.2.6",
3
+ "version": "1.2.9",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "files": [