@valiron/sdk 1.1.1 → 1.2.1

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/types.d.ts CHANGED
@@ -9,7 +9,8 @@ export type SupportedChain = "ethereum" | "monad" | "arbitrum" | "base" | "avala
9
9
  export type RouteDecision = "prod" | "prod_throttled" | "sandbox" | "sandbox_only";
10
10
  export type RiskLevel = "GREEN" | "YELLOW" | "RED";
11
11
  export type MoodysRating = "AAA" | "AA" | "A" | "BAA" | "BA" | "B" | "CAA" | "CA" | "C";
12
- export type TrustSignal = "8004" | "sandbox" | "world" | "icebreaker" | "self";
12
+ export type TrustSignal = "8004" | "sandbox" | "world" | "icebreaker" | "self" | "wallet";
13
+ export type WalletRiskLevel = "LOW" | "MEDIUM" | "HIGH" | "CRITICAL";
13
14
  export interface AgentIdentity {
14
15
  agentId: string;
15
16
  wallet: string;
@@ -123,6 +124,36 @@ export interface WalletProfile {
123
124
  resolutionSource?: "redis" | "subgraph" | "cache" | "none";
124
125
  timestamp: string;
125
126
  }
127
+ export interface WalletHistoryFeatures {
128
+ transactionCount: number;
129
+ activeDays: number;
130
+ walletAgeDays?: number;
131
+ uniqueCounterparties?: number;
132
+ failedTransactionRate?: number;
133
+ rapidPassThroughRate?: number;
134
+ activitySpikeRatio?: number;
135
+ flaggedCounterpartyCount?: number;
136
+ maliciousReportCount?: number;
137
+ sanctioned?: boolean;
138
+ historyTruncated?: boolean;
139
+ }
140
+ export interface WalletRiskSnapshot {
141
+ available: boolean;
142
+ wallet: string;
143
+ network: SupportedChain;
144
+ provider: "alchemy" | "helius" | "none";
145
+ score: number;
146
+ rawScore: number;
147
+ risk: number;
148
+ confidence: number;
149
+ riskLevel: WalletRiskLevel;
150
+ reasons: string[];
151
+ hardFlags: string[];
152
+ features: WalletHistoryFeatures;
153
+ observedAt: string;
154
+ expiresAt: string;
155
+ error?: string;
156
+ }
126
157
  /**
127
158
  * Response from `GET /operator/resolve-wallet/:wallet`
128
159
  *
@@ -193,7 +224,7 @@ export interface GateOptions {
193
224
  minScore?: number;
194
225
  /** TTL in ms for cached sandbox results. Stale results trigger re-testing (default: 86400000 = 24 h). */
195
226
  ttlMs?: number;
196
- /** Customer-selected scoring signals. Free plans support 8004+sandbox; Pro adds world+self+icebreaker. */
227
+ /** Customer-selected scoring signals. Free plans support 8004+sandbox; Pro adds world+self+icebreaker+wallet. */
197
228
  trustSignals?: TrustSignal[];
198
229
  /** Override the blockchain network for this call. */
199
230
  chain?: SupportedChain;
@@ -218,6 +249,8 @@ export interface GateResult {
218
249
  cached: boolean;
219
250
  /** Whether the score is from a micro-sandbox (fast, limited coverage). When true, a full deep test is running in the background and will update the cached score. */
220
251
  provisional?: boolean;
252
+ /** Wallet intelligence result when the wallet signal was requested. */
253
+ walletRisk?: WalletRiskSnapshot;
221
254
  }
222
255
  /**
223
256
  * Options for the proxy gateway request.
@@ -529,8 +562,26 @@ export interface ValironConfig {
529
562
  */
530
563
  telemetry?: TelemetryConfig;
531
564
  }
565
+ /** Structured diagnostics attached to SDK failures for programmatic recovery. */
566
+ export interface ValironErrorDetails {
567
+ /** HTTP method used for the failed request, when applicable. */
568
+ method?: "GET" | "POST";
569
+ /** Valiron API path that failed. */
570
+ path?: string;
571
+ /** Server request ID, when the deployment supplies one. Include this in support requests. */
572
+ requestId?: string;
573
+ /** Safe server-provided explanation beyond the top-level message. */
574
+ details?: unknown;
575
+ /** Suggested next step supplied by Valiron. */
576
+ action?: string;
577
+ /** Documentation or setup URL relevant to the failure. */
578
+ docsUrl?: string;
579
+ /** Delay before retrying, when the operation is retryable. */
580
+ retryAfterMs?: number;
581
+ }
532
582
  export declare class ValironError extends Error {
533
583
  code: string;
534
584
  statusCode?: number | undefined;
535
- constructor(message: string, code: string, statusCode?: number | undefined);
585
+ details?: ValironErrorDetails | undefined;
586
+ constructor(message: string, code: string, statusCode?: number | undefined, details?: ValironErrorDetails | undefined);
536
587
  }
package/dist/types.js CHANGED
@@ -7,12 +7,12 @@
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.ValironError = void 0;
10
- // ─── Errors ─────────────────────────────────────────────────────────────────
11
10
  class ValironError extends Error {
12
- constructor(message, code, statusCode) {
11
+ constructor(message, code, statusCode, details) {
13
12
  super(message);
14
13
  this.code = code;
15
14
  this.statusCode = statusCode;
15
+ this.details = details;
16
16
  this.name = "ValironError";
17
17
  }
18
18
  }
@@ -4,7 +4,7 @@ Base URL: `https://valiron-edge-proxy.onrender.com`
4
4
 
5
5
  Endpoints are organized into three groups:
6
6
 
7
- - **Trust evaluation** (`/operator/agent/*`, `/operator/gate/*`, etc.) — No authentication required. Used by the SDK to evaluate agents.
7
+ - **Trust evaluation** (`/operator/agent/*`, `/operator/gate/*`, etc.) — Basic evaluation is public. Pro trust signals and wallet intelligence require `Authorization: Bearer val_op_...`.
8
8
  - **Dashboard** (`/operator/register`, `/operator/login`, `/operator/endpoints`, etc.) — JWT-authenticated. Used by the Operator Dashboard. See [DASHBOARD.md](./DASHBOARD.md) for the UI guide.
9
9
  - **Agent-ready wrappers** (`/wrap/:operatorId/*`) — Public agent-facing URLs created from Dashboard endpoint configs. These can enforce x402/MPP payment, optional trust checks, rate limits, and upstream forwarding.
10
10
 
@@ -83,6 +83,61 @@ Same structure as `GET /operator/agent/:agentId`.
83
83
 
84
84
  ---
85
85
 
86
+ ## GET /operator/wallet-risk/:wallet (Pro)
87
+
88
+ Return an explainable wallet-history assessment. Requires a Pro or Enterprise operator API key in `Authorization: Bearer val_op_...`.
89
+
90
+ ### Parameters
91
+
92
+ | Parameter | Location | Type | Required | Description |
93
+ |-----------|----------|------|----------|-------------|
94
+ | `wallet` | path | string | yes | EVM address or Solana public key |
95
+ | `chain` | query | string | no | `ethereum`, `base`, `arbitrum`, `optimism`, `polygon`, or `solana` |
96
+
97
+ ### Response — 200 OK
98
+
99
+ ```json
100
+ {
101
+ "available": true,
102
+ "wallet": "0x52ce...",
103
+ "network": "base",
104
+ "provider": "alchemy",
105
+ "score": 78,
106
+ "rawScore": 85,
107
+ "risk": 22,
108
+ "confidence": 0.81,
109
+ "riskLevel": "LOW",
110
+ "reasons": [
111
+ "Wallet has at least one year of history",
112
+ "Score is based on a bounded transaction sample"
113
+ ],
114
+ "hardFlags": [],
115
+ "features": {
116
+ "transactionCount": 146,
117
+ "activeDays": 41,
118
+ "walletAgeDays": 620,
119
+ "uniqueCounterparties": 77,
120
+ "historyTruncated": true
121
+ },
122
+ "observedAt": "2026-07-20T12:00:00.000Z",
123
+ "expiresAt": "2026-07-20T18:00:00.000Z"
124
+ }
125
+ ```
126
+
127
+ `score` is trust-oriented: higher is better. `risk` is `100 - score`. `confidence` dampens sparse assessments toward neutral. `historyTruncated: true` means the score uses a bounded sample rather than complete transaction history.
128
+
129
+ Provider failures return HTTP 200 with `available: false`, `provider: "none"`, and an `error` explaining why the signal was unavailable. Gate/profile endpoints exclude unavailable wallet intelligence from composite scoring.
130
+
131
+ ### Error Responses
132
+
133
+ | Status | Meaning |
134
+ |--------|---------|
135
+ | 400 | Invalid EVM or Solana wallet address |
136
+ | 403 | Missing operator key or plan does not include enriched profiles |
137
+ | 500 | Unexpected wallet-risk route failure |
138
+
139
+ ---
140
+
86
141
  ## GET /operator/resolve-wallet/:wallet
87
142
 
88
143
  Lightweight wallet → agentId resolution. Returns just the agent ID and how it was resolved, without the full trust profile.
@@ -159,12 +214,16 @@ Trust gate — combined on-chain reputation + sandbox check. Returns an allow/de
159
214
 
160
215
  ```json
161
216
  {
217
+ "minScore": 65,
218
+ "trustSignals": ["8004", "sandbox", "wallet"],
162
219
  "ttlMs": 86400000
163
220
  }
164
221
  ```
165
222
 
166
223
  | Field | Type | Default | Description |
167
224
  |-------|------|---------|-------------|
225
+ | `minScore` | number | 65 | Minimum composite trust score required to allow |
226
+ | `trustSignals` | string[] | automatic | Selected signals. `wallet`, `world`, `self`, and `icebreaker` require Pro |
168
227
  | `ttlMs` | number | 86400000 | Cache TTL in milliseconds (default 24 hours) |
169
228
 
170
229
  ### Response — 200 OK
@@ -183,7 +242,15 @@ Trust gate — combined on-chain reputation + sandbox check. Returns an allow/de
183
242
  "chainId": 1
184
243
  },
185
244
  "sandboxRan": false,
186
- "cached": true
245
+ "cached": true,
246
+ "walletRisk": {
247
+ "available": true,
248
+ "score": 78,
249
+ "risk": 22,
250
+ "riskLevel": "LOW",
251
+ "confidence": 0.81,
252
+ "hardFlags": []
253
+ }
187
254
  }
188
255
  ```
189
256
 
@@ -193,6 +260,8 @@ Trust gate — combined on-chain reputation + sandbox check. Returns an allow/de
193
260
  2. If the agent does not meet the threshold → `allow: false`
194
261
  3. Cached sandbox results are reused within the `ttlMs` window
195
262
  4. If no cached result exists, sandbox tests run automatically
263
+ 5. If `wallet` is selected and available, its confidence-damped score is included in the composite result
264
+ 6. Unavailable wallet history is excluded; any populated wallet hard flag forces `sandbox_only`
196
265
 
197
266
  ---
198
267
 
package/docs/CHAINS.md CHANGED
@@ -89,6 +89,30 @@ Solana support is powered by [QuantuLabs 8004-solana](https://8004.qnt.sh/) —
89
89
  | `SOLANA_CLUSTER` | `mainnet-beta` | Solana cluster (`mainnet-beta` or `devnet`) |
90
90
  | `SOLANA_RPC_URL` | Public RPC | Custom Solana RPC endpoint for production use |
91
91
 
92
+ ## Wallet Intelligence Coverage
93
+
94
+ Wallet intelligence is available on a smaller network subset than identity and ERC-8004 reputation:
95
+
96
+ | Network | SDK Value | History Provider |
97
+ |---------|-----------|------------------|
98
+ | Ethereum Mainnet | `ethereum` | Alchemy |
99
+ | Base Mainnet | `base` | Alchemy |
100
+ | Arbitrum Mainnet | `arbitrum` | Alchemy |
101
+ | Optimism Mainnet | `optimism` | Alchemy |
102
+ | Polygon Mainnet | `polygon` | Alchemy |
103
+ | Solana Mainnet | `solana` | Helius |
104
+
105
+ For other supported chains, identity and reputation continue to work, but a requested wallet assessment returns `available: false` and is excluded from composite scoring.
106
+
107
+ | Environment Variable | Default | Description |
108
+ |---------------------|---------|-------------|
109
+ | `ALCHEMY_API_KEY` | — | Enables EVM wallet history on the five supported mainnets |
110
+ | `HELIUS_API_KEY` | — | Enables Solana mainnet wallet history |
111
+ | `WALLET_HISTORY_CACHE_TTL_SECONDS` | `21600` | Available-assessment cache duration in seconds |
112
+ | `WALLET_HISTORY_TIMEOUT_MS` | `4000` | Per-provider request timeout in milliseconds |
113
+
114
+ Wallet history is a bounded sample. See [TRUST-MODEL.md](./TRUST-MODEL.md#wallet-intelligence) for scoring behavior and limitations.
115
+
92
116
  ## Specifying a Chain
93
117
 
94
118
  ### SDK
@@ -0,0 +1,213 @@
1
+ # End-to-End Valiron Middleware Integration
2
+
3
+ This guide helps API teams integrate Valiron middleware from the first incoming
4
+ agent request through the downstream action they want to take. Start with the
5
+ agent identity, choose the trust signals that match your policy, then use the
6
+ gate result to protect an endpoint, vary access, attach pricing context, or
7
+ record the decision.
8
+
9
+ ```text
10
+ Incoming request
11
+ -> identify the agent
12
+ -> evaluate selected trust signals
13
+ -> receive an allow/deny decision, score, tier, and route
14
+ -> apply your API policy
15
+ -> serve, limit, sandbox, price, or deny
16
+ ```
17
+
18
+ ## Before you start
19
+
20
+ 1. Create an operator account in the [Dashboard](./DASHBOARD.md).
21
+ 2. Copy an operator API key (`val_op_...`) if you will use Pro trust signals,
22
+ operator usage logging, or hosted products.
23
+ 3. Install the SDK:
24
+
25
+ ```bash
26
+ npm install @valiron/sdk
27
+ ```
28
+
29
+ 4. Choose the identity format your agent callers will send.
30
+
31
+ ## 1. Identify every agent
32
+
33
+ Valiron middleware supports both identity paths automatically. Send one of the
34
+ following headers on the request to your API:
35
+
36
+ | Agent type | Header | Value | Setup |
37
+ | --- | --- | --- | --- |
38
+ | ERC-8004 EVM agent | `x-agent-id` | ERC-8004 token ID | Agent is registered on-chain |
39
+ | Solana agent | `x-agent-id` | Metaplex Core asset pubkey or supported indexed ID | Use `chain: "solana"` |
40
+ | Local, Web2, or non-ERC-8004 agent | `x-agent-address` | Persistent Ethereum-style address | Complete [key-based challenge-response](https://www.valiron.co/auth.md) first |
41
+
42
+ Do not send a local agent name to `x-agent-id`. Key-based agents must prove
43
+ ownership of their persistent address before they can pass an identity-aware
44
+ policy.
45
+
46
+ > **Hosted wrapper note:** Valiron-hosted API Scaffolding currently requires
47
+ > `x-agent-id` when its trust check is enabled. Use the SDK middleware in your
48
+ > own backend for a policy that accepts either identity path.
49
+
50
+ ## 2. Choose trust signals
51
+
52
+ Pass `trustSignals` to the middleware configuration. Start with the default
53
+ baseline, then add signals only when they are meaningful for the action you are
54
+ protecting.
55
+
56
+ | Signal | What it contributes | Availability |
57
+ | --- | --- | --- |
58
+ | `8004` | Registry-backed on-chain identity and reputation | All plans |
59
+ | `sandbox` | Behavioral evaluation and route readiness | All plans |
60
+ | `world` | World ID proof-of-personhood linkage | Pro |
61
+ | `self` | Self eligible-human verification | Pro |
62
+ | `icebreaker` | Human-to-agent attestation | Pro |
63
+ | `wallet` | Explainable wallet-history risk, confidence, and hard flags | Pro |
64
+
65
+ For example, a high-value endpoint might require on-chain reputation,
66
+ behavioral evidence, and wallet intelligence:
67
+
68
+ ```typescript
69
+ import { ValironSDK, createValironGate } from "@valiron/sdk";
70
+
71
+ const valiron = new ValironSDK({
72
+ apiKey: process.env.VALIRON_API_KEY,
73
+ chain: "base",
74
+ });
75
+
76
+ const trustGate = createValironGate({
77
+ sdk: valiron,
78
+ trustSignals: ["8004", "sandbox", "wallet"],
79
+ minScore: 80,
80
+ });
81
+ ```
82
+
83
+ If a wallet-history provider is unavailable or a network is unsupported, its
84
+ result is neutral and excluded from the composite score rather than treated as
85
+ malicious. See [Trust Model](./TRUST-MODEL.md) for the complete signal model.
86
+
87
+ ## 3. Choose the downstream behavior
88
+
89
+ The middleware attaches a normalized result to the request after a successful
90
+ check. It includes `allow`, `score`, `tier`, `riskLevel`, `route`, and the
91
+ resolved `agentId`, regardless of which supported identity header the agent
92
+ used.
93
+
94
+ Choose the behavior that fits the endpoint:
95
+
96
+ | Goal | Use the decision for |
97
+ | --- | --- |
98
+ | Trust gate | Allow trusted agents and return a denial before your handler runs |
99
+ | Graduated access | Serve full access for `prod`, apply limits for `prod_throttled`, and use test data for sandbox routes |
100
+ | Trust-aware pricing | Read the result in your handler and apply your own price or entitlement policy |
101
+ | Monetized endpoint logging | Use `ValironOperator.paywall()` to gate access, attach a configured per-call price, and record usage |
102
+ | Agent profile lookup | Retrieve a profile when your product needs to display or review trust evidence |
103
+ | Predictive risk | Use dashboard/API forecasts as an additional operational signal; do not replace the runtime gate with a forecast |
104
+ | Audit and operations | Capture the result in your logs or use dashboard call logs and evaluation history |
105
+
106
+ Valiron does not itself settle a payment or choose a dynamic price table. It
107
+ provides the verified trust context that your payment and application policy
108
+ can use.
109
+
110
+ ## 4. Put the gate in front of your handler
111
+
112
+ Here is a complete Express example that supports both agent identity paths and
113
+ uses the route decision for graduated access:
114
+
115
+ ```typescript
116
+ import express from "express";
117
+ import { ValironSDK, createValironGate } from "@valiron/sdk";
118
+
119
+ const app = express();
120
+ const valiron = new ValironSDK({
121
+ apiKey: process.env.VALIRON_API_KEY,
122
+ chain: "base",
123
+ });
124
+
125
+ app.use("/api/research", createValironGate({
126
+ sdk: valiron,
127
+ trustSignals: ["8004", "sandbox", "wallet"],
128
+ minScore: 65,
129
+ }));
130
+
131
+ app.get("/api/research", (req, res) => {
132
+ const trust = (req as typeof req & { valiron: {
133
+ route: "prod" | "prod_throttled" | "sandbox" | "sandbox_only";
134
+ score: number;
135
+ tier: string;
136
+ } }).valiron;
137
+
138
+ if (trust.route === "prod_throttled") {
139
+ res.set("X-Rate-Limit-Policy", "reduced");
140
+ }
141
+
142
+ if (trust.route === "sandbox") {
143
+ return res.json({ mode: "sandbox", results: [] });
144
+ }
145
+
146
+ return res.json({
147
+ mode: "production",
148
+ trust: { score: trust.score, tier: trust.tier },
149
+ results: [/* your production response */],
150
+ });
151
+ });
152
+
153
+ app.listen(3000);
154
+ ```
155
+
156
+ The middleware checks `x-agent-id` first, then `x-agent-address`. If there is
157
+ no supported identity, the agent is denied. If an agent is pending its first
158
+ behavioral evaluation, it receives a retryable denial while sandbox evaluation
159
+ runs.
160
+
161
+ ## 5. Add a pricing or payment policy
162
+
163
+ For a server-side endpoint with a fixed price and usage logging, use the
164
+ operator SDK. It gates the route, makes the decision available as
165
+ `req.valiron`, and records the configured price only for successful allowed
166
+ calls.
167
+
168
+ ```typescript
169
+ import { ValironOperator } from "@valiron/sdk";
170
+
171
+ const operator = new ValironOperator({
172
+ apiKey: process.env.VALIRON_API_KEY!,
173
+ chain: "base",
174
+ });
175
+
176
+ app.use("/api/premium", operator.paywall({
177
+ pricePerCall: 0.05,
178
+ minTrustScore: 65,
179
+ trustSignals: ["8004", "sandbox", "wallet"],
180
+ }));
181
+ ```
182
+
183
+ If your payment provider supports multiple prices, select the price in your
184
+ handler from `req.valiron.tier`, `score`, or `route`. Keep payment settlement
185
+ in that provider; use Valiron first to decide whether the caller is eligible
186
+ to reach it.
187
+
188
+ ## 6. Test the complete request path
189
+
190
+ Test each case before production:
191
+
192
+ 1. A registered agent using `x-agent-id`.
193
+ 2. A verified key-based agent using `x-agent-address`.
194
+ 3. A request without either identity header.
195
+ 4. An agent below your `minScore`.
196
+ 5. A new agent pending sandbox evaluation.
197
+ 6. A production-eligible agent on every protected route.
198
+ 7. A paid or priced request, verifying that trust denial happens before your
199
+ payment or application handler.
200
+
201
+ Use the [Dashboard Playground](./DASHBOARD.md#api-playground) to inspect
202
+ decisions and the Dashboard's call logs to review outcome, latency, price, and
203
+ trust context after launch.
204
+
205
+ ## Next steps
206
+
207
+ - [Quickstart](./QUICKSTART.md) — protect a first endpoint quickly
208
+ - [SDK Reference](./SDK-REFERENCE.md#middleware) — Express, Fastify, Next.js,
209
+ and generic middleware APIs
210
+ - [Identity](./IDENTITY.md) — registry and key-based identity details
211
+ - [Trust Model](./TRUST-MODEL.md) — signals, tiers, and routes
212
+ - [API Scaffolding](./AGENT-READY-APIS.md) — hosted x402/MPP wrappers for an
213
+ existing API
package/docs/ERRORS.md CHANGED
@@ -2,6 +2,44 @@
2
2
 
3
3
  Common error scenarios, status codes, and guidance on how to handle them.
4
4
 
5
+ ## Read an error before retrying
6
+
7
+ Every SDK failure is a `ValironError`. Its stable `code` is for program logic; its `message` is safe to show in developer logs; and `details` provides the recovery information that was available from the API.
8
+
9
+ ```typescript
10
+ import { ValironError } from "@valiron/sdk";
11
+
12
+ try {
13
+ await valiron.getAgentProfile("99999");
14
+ } catch (error) {
15
+ if (error instanceof ValironError) {
16
+ console.error({
17
+ code: error.code,
18
+ status: error.statusCode,
19
+ message: error.message,
20
+ nextStep: error.details?.action,
21
+ requestId: error.details?.requestId,
22
+ docs: error.details?.docsUrl,
23
+ retryAfterMs: error.details?.retryAfterMs,
24
+ serverDetails: error.details?.details,
25
+ });
26
+ }
27
+ }
28
+ ```
29
+
30
+ HTTP errors from SDK calls and trust-gate responses use these fields where applicable:
31
+
32
+ | Field | Purpose |
33
+ |--------|---------|
34
+ | `code` | Stable, machine-readable category such as `MISSING_AGENT_IDENTITY` or `TRUST_GATE_DENIED` |
35
+ | `message` | Human-readable explanation of what happened |
36
+ | `action` / `details.action` | Concrete next debugging or recovery step |
37
+ | `docsUrl` / `details.docsUrl` | Relevant documentation section |
38
+ | `requestId` / `details.requestId` | Include with a timestamp in a support request |
39
+ | `retryAfterMs` | Minimum delay before retrying, when retrying is appropriate |
40
+
41
+ Treat `code` as the contract; wording may be refined over time.
42
+
5
43
  ## HTTP Status Codes
6
44
 
7
45
  | Status | Meaning | Action |
@@ -28,12 +66,11 @@ const valiron = new ValironSDK();
28
66
  try {
29
67
  const profile = await valiron.getAgentProfile("99999");
30
68
  } catch (error) {
31
- if (error.status === 404) {
69
+ if (error instanceof ValironError && error.statusCode === 404) {
32
70
  // Agent not registered — register via ERC-8004 first
33
- } else if (error.status === 429) {
71
+ } else if (error instanceof ValironError && error.statusCode === 429) {
34
72
  // Rate limited — wait and retry
35
- const retryAfter = error.headers?.["retry-after"];
36
- await sleep(parseInt(retryAfter || "5") * 1000);
73
+ await sleep(error.details?.retryAfterMs ?? 5_000);
37
74
  } else {
38
75
  // Unexpected error — log and retry with backoff
39
76
  console.error(error.message);
@@ -52,10 +89,11 @@ async function withRetry<T>(fn: () => Promise<T>, maxRetries = 3): Promise<T> {
52
89
  return await fn();
53
90
  } catch (error) {
54
91
  // Never retry auth errors
55
- if (error.status === 401 || error.status === 403) throw error;
92
+ const status = error instanceof ValironError ? error.statusCode : undefined;
93
+ if (status === 401 || status === 403) throw error;
56
94
 
57
95
  // Never retry client errors (except 429)
58
- if (error.status >= 400 && error.status < 500 && error.status !== 429) throw error;
96
+ if (status && status >= 400 && status < 500 && status !== 429) throw error;
59
97
 
60
98
  if (attempt === maxRetries) throw error;
61
99
 
@@ -108,6 +146,31 @@ If the agent is registered on Monad but you query Ethereum (the default), it wil
108
146
  const valiron = new ValironSDK({ chain: "monad" });
109
147
  ```
110
148
 
149
+ ### Wallet intelligence unavailable
150
+
151
+ `getWalletRisk()` may return HTTP 200 with `available: false`. This is a graceful degradation response, not an SDK transport error. Inspect `error` for the exact reason:
152
+
153
+ - `ALCHEMY_API_KEY is not configured` for supported EVM mainnets
154
+ - `HELIUS_API_KEY is not configured` for Solana
155
+ - `Wallet history is not configured for <network>` when the selected chain is outside the supported history subset
156
+ - `Wallet history lookup timed out` or a provider HTTP/RPC error
157
+
158
+ Unavailable wallet intelligence is excluded from profile and gate composite scoring. Retry provider failures according to your policy; do not reinterpret an unavailable assessment as malicious activity.
159
+
160
+ ### Wallet intelligence requires Pro
161
+
162
+ Direct wallet-risk requests and policies containing `trustSignals: ["wallet"]` require a valid Pro or Enterprise operator key. A Free or unauthenticated request returns:
163
+
164
+ ```json
165
+ {
166
+ "error": "upgrade_required",
167
+ "feature": "enriched_profiles",
168
+ "message": "World ID, Self, Icebreaker, and wallet intelligence signals require a Pro plan. Free plans can use ERC-8004 and sandbox signals."
169
+ }
170
+ ```
171
+
172
+ Invalid EVM or Solana wallet formats return HTTP 400 before any provider request is made.
173
+
111
174
  ---
112
175
 
113
176
  ## Solana-Specific Errors
@@ -152,11 +215,14 @@ SOLANA_RPC_URL=https://your-private-rpc.example.com
152
215
 
153
216
  All Valiron middleware (Express, Fastify, Next.js, generic) returns consistent error responses:
154
217
 
155
- | Status | When | Body |
218
+ | Status | Code | When | What to do |
156
219
  |--------|------|------|
157
- | 401 | No agent ID found in request | `{ error: "No agent identity provided" }` |
158
- | 403 | Agent denied by trust gate | `{ error: "Access denied", tier, riskLevel, route }` |
159
- | 503 | Valiron service unavailable | `{ error: "Trust evaluation unavailable" }` |
220
+ | 401 | `MISSING_AGENT_IDENTITY` | No identity header | Send one supported identity header: `x-agent-id` or `x-agent-address` |
221
+ | 403 | `TRUST_GATE_DENIED` | Agent did not meet the configured policy | Inspect `score`, `tier`, `route`, and `reasons`; do not blindly retry |
222
+ | 403 | `AGENT_EVALUATION_PENDING` | New identity is sandbox-evaluating | Keep the same identity and retry after `retryAfterMs` |
223
+ | 503 | `TRUST_GATE_UNAVAILABLE` | Trust evaluation could not complete | Fail closed; retry shortly and inspect the logged `cause` |
224
+
225
+ Each response includes `message`, `action`, and `docsUrl`; denials retain the trust result fields so an application can make a deliberate fallback decision.
160
226
 
161
227
  > **Fail-closed:** When the Valiron service is unreachable, middleware returns 503 — it never fails open and never allows unverified agents through.
162
228
 
@@ -169,6 +235,16 @@ All Valiron middleware (Express, Fastify, Next.js, generic) returns consistent e
169
235
  | 403 | SSRF blocked | The `targetUrl` resolves to a private IP, localhost, or metadata endpoint |
170
236
  | 503 | Origin server unreachable | Your upstream API base URL is down or timed out |
171
237
 
238
+ ## Hosted Wrapper Errors
239
+
240
+ | Status | Code | When | Action |
241
+ |--------|------|------|--------|
242
+ | 400 | `MISSING_AGENT_IDENTITY` | A trust-enabled hosted wrapper did not receive `x-agent-id` | Hosted wrappers currently require `x-agent-id`; use SDK middleware for key/address identity support |
243
+ | 404 | `WRAPPER_NOT_FOUND` | Operator ID, path, method, or endpoint activation does not match | Verify all four values in the dashboard |
244
+ | 413 | `WRAPPER_BODY_TOO_LARGE` | Body exceeds the wrapper limit | Send a smaller request or use an external input reference |
245
+ | 429 | `WRAPPER_RATE_LIMITED` | Endpoint rate limit reached | Honor `retryAfter` and use exponential backoff |
246
+ | 502 / 504 | `WRAPPER_UPSTREAM_REQUEST_FAILED` / `WRAPPER_UPSTREAM_TIMEOUT` | The target API failed or was too slow | Check upstream URL/auth; include `requestId` and timestamp when escalating |
247
+
172
248
  ## Key-Based Agent Errors
173
249
 
174
250
  | Status | When | Action |
package/docs/IDENTITY.md CHANGED
@@ -10,6 +10,12 @@ Valiron supports two identity paths:
10
10
 
11
11
  Use `/operator/agent/:agentId` only for registry-backed on-chain agents. Local and Web2 agents should generate or reuse a persistent keypair, prove ownership through Valiron's challenge-response flow, and then use their `x-agent-address` for trust checks.
12
12
 
13
+ ## Wallet as a Trust Input
14
+
15
+ When a Pro policy selects `trustSignals: ["wallet"]`, Valiron evaluates the wallet associated with the chosen identity path. ERC-8004 and Solana agents use the wallet resolved from their registry identity; key-based agents use their verified persistent agent address. Wallet intelligence does not establish identity by itself—it is an additional economic-history signal applied after Valiron has a wallet address.
16
+
17
+ Use `getWalletProfile()` to resolve a wallet to an agent profile. Use `getWalletRisk()` when you need only the explainable wallet-history assessment. See [TRUST-MODEL.md](./TRUST-MODEL.md#wallet-intelligence) for supported networks and limitations.
18
+
13
19
  ## ERC-8004 Identity
14
20
 
15
21
  For EVM on-chain agents, Valiron uses the ERC-8004 standard for AI agent identity. Each agent is represented by an ERC-721 token in the Identity Registry.
@@ -96,6 +96,20 @@ app.use("/api/paid", createValironGate({ sdk: valiron }));
96
96
 
97
97
  This checks `x-agent-id` first for on-chain agents, then falls back to `x-agent-address` for key-based agents. It returns 403 for untrusted agents, is safe with Express 4 (async errors are handled), and includes a 30-second client-side cache for x402 compatibility.
98
98
 
99
+ Pro operators can include wallet history in an endpoint policy:
100
+
101
+ ```typescript
102
+ const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY });
103
+
104
+ app.use("/api/high-trust", createValironGate({
105
+ sdk: valiron,
106
+ trustSignals: ["8004", "sandbox", "wallet"],
107
+ minScore: 80,
108
+ }));
109
+ ```
110
+
111
+ The `wallet` signal supports Ethereum, Base, Arbitrum, Optimism, Polygon, and Solana. If wallet history is unavailable, Valiron excludes it from the composite score instead of penalizing the agent.
112
+
99
113
  Or use `getAgentProfile()` directly for on-chain custom logic:
100
114
 
101
115
  ```typescript
@@ -230,11 +244,13 @@ process.on("SIGTERM", async () => {
230
244
 
231
245
  ## What's next?
232
246
 
247
+ - **[End-to-End Middleware Integration](./E2E-MIDDLEWARE-INTEGRATION.md)** — Choose identity, trust signals, and a downstream policy for a production integration
233
248
  - **[Proxy Gateway](./SDK-REFERENCE.md#proxy-gateway-pro)** — Forward requests through Valiron's edge proxy (Pro)
234
249
  - **[API Scaffolding](./AGENT-READY-APIS.md)** — Create hosted x402/MPP wrappers for existing APIs
235
250
  - **[Key-Based Agents](./SDK-REFERENCE.md#key-based-agents)** — Support Web2 agents without on-chain identity
236
251
  - **[World ID](./SDK-REFERENCE.md#world-id-methods)** — Verify agent-human linkage
237
252
  - **[Self](./SDK-REFERENCE.md#self-methods)** — Create Self Enterprise sessions and verify eligible-human linkage
253
+ - **[Wallet Intelligence](./TRUST-MODEL.md#wallet-intelligence)** — Add explainable wallet-history risk to Pro endpoint policies
238
254
  - **[Fastify / Next.js / Hono middleware](./SDK-REFERENCE.md#middleware)** — Framework-specific middleware
239
255
  - **[Plans & Limits](./SDK-REFERENCE.md#plans--limits)** — Free vs Pro feature comparison
240
256