OpenAPI specificationAuthentication
API Reference
Constructor
new ValironSDK(config?: ValironConfig)| Option | Type | Default | Description |
|---|---|---|---|
apiKey | string | — | Operator API key for authenticated operations |
endpoint | string | production | Valiron API base URL (override for self-hosted or dev) |
chain | SupportedChain | server default | Default blockchain network |
timeout | number | 5000 | Request timeout (ms) |
debug | boolean | false | Enable debug logging |
telemetry | TelemetryConfig | enabled | Telemetry settings (see Telemetry) |
checkAgent(agentId, options?)
Quick routing check — returns just the route decision string.
const route = await valiron.checkAgent('25459');
// route: 'prod' | 'prod_throttled' | 'sandbox' | 'sandbox_only'
// With chain override
const monadRoute = await valiron.checkAgent('8348', { chain: 'monad' });getAgentProfile(agentId, options?)
Full trust profile combining on-chain identity, reputation, behavioral data, and routing.
const profile = await valiron.getAgentProfile('25459');
// Response includes:
// profile.identity — on-chain identity (wallet, name, endpoints)
// profile.onchainReputation — ERC-8004 feedback (count, averageScore)
// profile.localReputation — behavioral score, tier, riskLevel
// profile.routing — finalRoute, decision, reasons, signalsgetWalletProfile(wallet, options?)
Reverse-lookup a wallet address to get its trust profile.
const profile = await valiron.getWalletProfile('0x52ce...');
console.log(profile.routing.finalRoute);
// With chain override
const monadProfile = await valiron.getWalletProfile('0xABC...', { chain: 'monad' });getWalletRisk(wallet, options?)
Return a Free wallet-history assessment with score, risk, confidence, reasons, hard flags, normalized features, and cache timestamps. Requires an operator API key.
const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY });
const assessment = await valiron.getWalletRisk('0x52ce...', { chain: 'base' });
if (!assessment.available) {
console.log(assessment.error);
}resolveWallet(wallet, options?)
Lightweight wallet → agentId resolution without fetching the full trust profile. Useful when you only need to know which agent owns a wallet — e.g. after extracting a wallet from an x402 payment header.
Returns the associated agent ID when available, or null when no supported registration is found.
const resolution = await valiron.resolveWallet('0x52ce...');
console.log(resolution.agentId); // '25459' or null
console.log(resolution.source); // 'redis' | 'subgraph' | 'cache' (in-memory) | 'none'
console.log(resolution.agentName); // 'MyAgent' (from subgraph, if available)
console.log(resolution.chainId); // 1 (from subgraph, if available)
// Then fetch the full profile if needed
if (resolution.agentId) {
const profile = await valiron.getAgentProfile(resolution.agentId);
}| Field | Type | Description |
|---|---|---|
wallet | string | The queried wallet address |
agentId | string | null | Resolved ERC-8004 agent ID, or null if not found |
source | ResolutionSource | "redis" | "subgraph" | "cache" | "none" |
chainId | number | null | Chain ID from the subgraph (if available) |
agentName | string | null | Agent name from the subgraph (if available) |
timestamp | string | ISO timestamp of the resolution |
triggerSandboxTest(agentId, options?)
Run real sandbox tests against an agent and compute a Valiron score.
const result = await valiron.triggerSandboxTest('25459');
console.log(result.valironScore); // 95
console.log(result.tier); // 'AAA'
console.log(result.riskLevel); // 'GREEN'
console.log(result.mode); // 'endpoint-probe' | 'sandbox-relay'
console.log(result.testSummary); // opaque metrics objecttriggerKeyAgentSandbox(agentAddress)
Run sandbox tests against a key-based (Web2) agent. Uses sandbox_relay mode (no endpoint probing needed).
const result = await valiron.triggerKeyAgentSandbox('0x1234...abcd');
console.log(result.tier); // 'A'
console.log(result.riskLevel); // 'GREEN'
console.log(result.valironScore); // 85totalFeedback === 0 trigger triggerSandboxTest(), and key agents with no score trigger triggerKeyAgentSandbox(). The agent receives a 403 with { error: "Agent pending evaluation", retryAfterMs: 30000 }.gate(agentId, options?)
Trust gate — single call combining on-chain reputation + sandbox tests. Designed to sit in front of payment protocols (x402 etc.). The hosted endpoint requires an operator key and a fresh registry-owner signature over the actual request. Configure signRequest in the SDK; prior agent sessions do not authorize it. Local middleware uses your verifyRequest callback.
const result = await valiron.gate('25459');
console.log(result.allow); // true
console.log(result.score); // 95
console.log(result.tier); // 'AAA'
console.log(result.riskLevel); // 'GREEN'
console.log(result.sandboxRan); // true (first call) / false (cached)
// Custom threshold
const result2 = await valiron.gate('8348', {
minScore: 85, // require A tier or above
trustSignals: ['8004', 'sandbox'],
ttlMs: 3600_000, // re-test every hour
chain: 'monad', // chain override
});
if (result2.allow) {
// proceed to payment
} else {
console.log(result2.reasons); // ['Score 42 below threshold 85']
}| Option | Type | Default | Description |
|---|---|---|---|
minScore | number | 65 | Minimum score to allow (0–100) |
trustSignals | Array<'8004' | 'sandbox' | 'world' | 'self' | 'icebreaker' | 'wallet'> | auto | Optional selected scoring signals. Free includes 8004, sandbox, world, self, and wallet. Only icebreaker (Social Graph) requires Pro. |
ttlMs | number | 86400000 | Cache TTL for sandbox results (ms) |
chain | SupportedChain | constructor default | Blockchain network override |
checkAgent() returns a route decision based on existing data. gate() actively runs sandbox tests (if stale/missing), computes a combined score, and returns a binary allow/deny — ideal for protecting payment endpoints.Provisional scores: If result.provisional === true, the score is from a fast micro-sandbox. A full deep test is running in the background and will update the cached score automatically. Provisional or synthetic results do not permit production access. The request remains denied until a real completed evaluation establishes the decision.
getAgentSnapshot(agentId, options?)
Get the latest behavioral snapshot hash for an agent. Returns an opaque hash of the most recent behavioral evaluation — designed for hash-chain commitment systems that need to commit behavioral state on-chain without accessing raw metrics.
const snapshot = await valiron.getAgentSnapshot('25459');
console.log(snapshot.snapshotHash); // '0x3a7f...' (opaque hash)
console.log(snapshot.previousHash); // '0x0' (genesis) or '0x8b2c...'The snapshotHash is computed internally by Valiron from behavioral metrics. It is opaque — you cannot reverse it to raw metrics. Each hash references the previousHash, forming a chain. First evaluation gets "0x0".
Webhooks
Register a webhook to receive evaluation_complete events whenever Valiron evaluates an agent. The payload matches the getAgentSnapshot() response. Included with Free; operator API key required.
curl -X POST https://valiron-edge-proxy.onrender.com/operator/webhooks/register \
-H "Authorization: Bearer $VALIRON_API_KEY" \
-H "Content-Type: application/json" \
-d '{"event": "evaluation_complete", "url": "https://your-endpoint.com/hooks/valiron", "agentIds": [42, 43]}'The agentIds filter is optional — omit it to receive events for your own evaluations on the selected chain. Duplicate registrations (same event + URL + agentIds) are deduplicated automatically.
| Payload Field | Type | Description |
|---|---|---|
event | string | "evaluation_complete" |
agentId | string | The evaluated agent's ID |
snapshotHash | string | Opaque SHA-256 hash of the evaluation |
previousHash | string | Previous hash in the chain ("0x0" for first) |
interactionCount | number | Total interactions in the evaluation window |
timestamp | string | ISO 8601 timestamp |
proxy(agentId, request, options?)
Proxy an API call through Valiron's trust gateway. The agent sends a request to Valiron, Valiron evaluates trust inline, and either forwards to your real API or blocks with 403. The agent never touches your API directly. Included with Free; operator API key required.
const result = await valiron.proxy('25459', {
target: 'https://api.example.com/data',
method: 'GET',
headers: { 'Authorization': 'Bearer ...' },
minScore: 65, // minimum trust score (default: 65)
});
// result._valiron — gate evaluation (allow, score, tier, riskLevel)
// result._apiStatus — HTTP status from your real API
// result.response — your API's response body
if (result._valiron.allow) {
console.log(result.response); // Real API data
}| ProxyRequest Field | Type | Description |
|---|---|---|
target | string | Your real API endpoint URL (must be HTTPS, public IP) |
method | string | HTTP method (default: GET) |
headers | Record<string, string> | Headers to forward to target API |
body | unknown | Request body for POST/PUT/PATCH |
minScore | number | Minimum trust score to allow (default: 65) |
Key-Based Agents (Web2)
Not every agent has an ERC-8004 identity. Local, Web2, and non-ERC-8004 agents use a persistent Ethereum-style keypair for identity without needing an on-chain registration. Identity is verified via EIP-191 challenge-response.
| Agent type | Header | Lookup path |
|---|---|---|
| ERC-8004 / Solana | x-agent-id | /operator/agent/:agentId |
| Local / Web2 / non-ERC-8004 | x-agent-address | /operator/key/:agentAddress |
my-agent to /operator/agent/:agentId. That path is for registry-backed on-chain agents. Local agents should generate or reuse a persistent keypair, complete auth.md, and use their verified x-agent-address.// 1. Get a challenge nonce
const { challenge, expiresAt } = await valiron.getKeyAgentChallenge('0x1234...abcd');
// 2. Agent signs the challenge with its private key
const signature = await account.signMessage({ message: challenge });
// 3. Verify — returns the agent's trust profile
const profile = await valiron.verifyKeyAgent({
challenge,
signature,
agentAddress: '0x1234...abcd',
});
console.log(profile.verified); // true
console.log(profile.score); // null until behavioral evaluation
console.log(profile.tier); // null until behavioral evaluation
console.log(profile.icebreaker); // null in this summary response
// 4. Subsequent lookups (no challenge needed)
const profile2 = await valiron.getKeyAgentProfile('0x1234...abcd');
// 5. Pro operator: private Icebreaker owner context
const { icebreaker } = await valiron.getKeyAgentIcebreaker('0x1234...abcd');Middleware auto-detection: All middleware (createValironGate, etc.) automatically checks x-agent-id first (on-chain), then falls back to x-agent-address (key-based). Both claims require a configured verifyRequest callback that checks a fresh signature and rejects replays before every decision, including cache hits.
Auto-sandbox for key agents: New key agents (verified but not yet scored) are automatically sandbox-evaluated on their first gated request. Use triggerKeyAgentSandbox() or POST /operator/trigger-sandbox-key/{address} to trigger manually.
Provider-Backed Identity
POST /operator/identity/verify is the provider-independent foundation for ANS, DNS, DID, API-key, and future identity adapters. It verifies a signed timestamp, nonce, and SHA-256 request digest, prevents replay, reads reputation against a stable provider identity, and returns an allow, limit, challenge, or block policy action.
import { ValironSDK, createValironIdentityGate } from "@valiron/sdk";
const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY });
app.use(express.json({
verify: (req, _res, bytes) => { req.rawBody = Buffer.from(bytes); },
}));
app.post("/quote", createValironIdentityGate({
audience: "https://api.example.com", origin: "https://api.example.com",
sdk: valiron,
policy: {
anonymous: "challenge",
claimed: "block",
verified: "allow",
minReputationScore: 65,
belowMinimumScore: "limit",
},
}), handler);x-valiron-identity-* proof headers. Dedicated Express, Fastify, Next.js, and generic gates bind a configured audience/origin, HTTP method, full URL and exact request digest, call Valiron, and enforce the returned policy action. Valiron hosts the ANS credentials and trusted CA bundle; customer applications do not configure them. A verified provider identity remains pseudonymous and returns humanIdentified: false.See the provider-backed identity guide for the canonical signing payload, response fields, policy schema, replay behavior, and ANS adapter status.
World ID SDK Methods
Programmatic enrollment needs operator authentication and a fresh owner proof from signRequest. Status lookup requires an operator key. See World ID in Trust Model for background.
// Verify a World ID proof (from IDKit)
const result = await valiron.verifyWorldId('25459', {
proof: '0x...',
merkle_root: '0x...',
nullifier_hash: '0x...',
verification_level: 'orb',
idkit_result: idkitResult, // complete, unmodified production IDKit result
});
console.log(result.worldId.verified); // true
// Check verification status
const status = await valiron.getWorldIdStatus('25459');
console.log(status.worldId.verificationLevel); // 'orb'
// Enriched profile (World ID + Icebreaker combined)
const profile = await valiron.getWorldIdProfile('25459');
console.log(profile.humanTrust.hasHumanLink); // true
console.log(profile.humanTrust.hasBackground); // true
console.log(profile.icebreaker?.verifiedHandles);
// [{ source: 'github', handle: 'alice' }, { source: 'x', handle: '@alice' }]Self SDK Methods
Self session creation requires operator authentication and a fresh registry-owner request proof from signRequest; only owner-authorized sessions can establish a link. Status/profile reads require operator credentials. See Self in Trust Model for background.
// Create a Self Enterprise verification session
const session = await valiron.createSelfSession('25459', {
selfAgentId: 'self-agent-...',
successUrl: 'https://valiron.co/verified',
failureUrl: 'https://valiron.co/failed',
});
console.log(session.self.verificationUrl);
// Check Self status
const status = await valiron.getSelfStatus('25459');
console.log(status.self.verified);
// Full Self eligible-human / Agent ID profile
const profile = await valiron.getSelfProfile('25459');
console.log(profile.humanTrust.hasHumanLink);dispose()
Flush pending telemetry and release resources. Call this in long-running servers (Express, Fastify) on graceful shutdown. Optional for short-lived scripts — the SDK flushes automatically on process exit.
const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY });
try {
const profile = await valiron.getAgentProfile('25459');
} finally {
await valiron.dispose();
}
// Or on server shutdown
process.on('SIGTERM', async () => {
await operator.dispose();
process.exit(0);
});Response Types
All types are exported from @valiron/sdk and can be imported directly for type-safe code.
import type {
AgentProfile, WalletProfile, GateResult, SandboxResult,
AgentSnapshotSummary, WalletResolution, WalletRiskSnapshot, KeyAgentProfile,
WorldIdStatus, WorldIdAgentProfile, ProxyResponse,
RouteDecision, MoodysRating, RiskLevel, SupportedChain,
ValironError,
} from '@valiron/sdk';GateResult
| Field | Type | Description |
|---|---|---|
allow | boolean | Whether the agent is allowed through |
score | number | Combined Valiron trust score (0–100) |
tier | MoodysRating | AAA through C |
riskLevel | RiskLevel | "GREEN" | "YELLOW" | "RED" |
route | RouteDecision | prod / prod_throttled / sandbox / sandbox_only |
agentId | string | The evaluated agent's ID |
wallet | string | Agent's wallet address |
chain | ChainContext | Network, registry addresses used |
sandboxRan | boolean | Whether sandbox tests ran this call (false = cached) |
cached | boolean | Whether cached results were used |
provisional | boolean? | If true, score is from a fast micro-sandbox; a full deep test is running in the background |
AgentProfile
| Field | Type | Description |
|---|---|---|
agentId | string | ERC-8004 agent ID |
identity | AgentIdentity | On-chain identity (wallet, name, endpoints, trust models) |
onchainReputation | OnchainReputation | Feedback count, average score, entries, and Solana ATOM data |
localReputation | LocalReputation | null | Behavioral score, tier, riskLevel, graduated status |
routing | RoutingExplanation | finalRoute, decision text, reasons array, signals breakdown |
chain | ChainContext | Network, RPC URL, registry contract addresses |
worldId | WorldIdStatus? | World ID verification status (if checked) |
timestamp | string | ISO 8601 timestamp |
KeyAgentProfile
| Field | Type | Description |
|---|---|---|
agentAddress | string | Ethereum address (keccak256 of secp256k1 pubkey) |
verified | boolean | Identity verified via challenge-response |
score | number | null | Behavioral score (0–100) |
tier | MoodysRating | null | AAA through C |
riskLevel | RiskLevel | null | GREEN / YELLOW / RED |
route | RouteDecision | null | Route decision |
icebreaker | IcebreakerOwnership | null | Icebreaker attestation context |
reasons | string[] | Human-readable trust explanation |
Request Headers
| Header | Purpose | Notes |
|---|---|---|
X-Agent-Id | On-chain agent ID (ERC-8004 / Solana) | Checked first by all middleware |
X-Agent-Address | Key-based agent Ethereum address | Fallback when no X-Agent-Id |
X-Chain | Blockchain network override | Alternative to ?chain= query param |
Authorization | Operator API key | Bearer val_op_xxxx |
All Exports
Everything available from @valiron/sdk:
// Classes
export { ValironSDK, ValironClient, ValironError };
// Middleware
export { createValironGate, valironFastifyPlugin, createValironNextMiddleware, valironGateCheck };
// Utilities
export { isValidAddress, generateChallenge };
// All TypeScript types (AgentProfile, GateResult, etc.)
export type { ... }; // See full list in types.tsTelemetry
The SDK collects opt-out usage telemetry to improve reliability. Events include SDK version, runtime, environment, method names, chain labels, latency, HTTP status/error buckets, route decisions, and coarse score/reputation buckets. Raw agent IDs, wallet addresses, API keys, and exact scores are not sent in SDK telemetry.
SDK reports are anonymous client reports and may be sampled. Signal counts describe reported selections; they do not count successful verifications. Environment defaults to recognized NODE_ENV values, otherwise unknown. Telemetry observer failures do not affect API calls.
// Disable telemetry entirely
const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY,
telemetry: { enabled: false },
});
// Reduce volume with sampling
const valiron2 = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY,
telemetry: { sampleRate: 0.1 }, // only 10% of events
});
// Custom event handler (e.g. forward to your own analytics)
const valiron3 = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY,
telemetry: {
onEvent: (event) => myAnalytics.track(event),
},
});| Option | Type | Default | Description |
|---|---|---|---|
enabled | boolean | true | Enable/disable telemetry |
sampleRate | number | 1.0 | Sampling rate (0.0–1.0) |
appId | string | — | Application identifier for grouping |
env | "prod" | "staging" | "dev" | "test" | "unknown" | NODE_ENV or unknown | Environment label; set explicitly for browser applications |
onEvent | (event) => void | — | Custom event callback |
Error Handling
All SDK methods throw typed ValironError instances with a code field for programmatic handling.
import { ValironError } from '@valiron/sdk';
try {
const profile = await valiron.getAgentProfile('123');
} catch (error) {
if (error instanceof ValironError) {
console.error(error.details?.action, error.details?.requestId);
switch (error.code) {
case 'TIMEOUT_ERROR': // Request timed out
case 'NETWORK_ERROR': // Could not reach API
case 'MISSING_AGENT_IDENTITY':
case 'TRUST_GATE_DENIED':
case 'API_ERROR': // Non-2xx response without a server error code
}
}
}| Error Code | Meaning |
|---|---|
TIMEOUT_ERROR | Request exceeded the configured timeout (default 5000ms) |
NETWORK_ERROR | Could not reach the Valiron API (DNS, connection refused, etc.) |
MISSING_AGENT_IDENTITY | A trust-gated endpoint needs an agent identity header |
TRUST_GATE_DENIED | Agent did not satisfy the endpoint's trust policy; inspect the returned result |
API_ERROR | Server returned a non-2xx response without a specific code — check error.statusCode and error.details |
Common HTTP status codes from the Valiron API:
| Status | Cause |
|---|---|
400 | Invalid agentId format or missing required fields |
401 | Missing agent identity header (middleware) or invalid operator API key |
403 | Agent blocked (score below threshold) or feature requires Pro plan |
404 | Agent not found on the specified chain |
429 | Sandbox daily limit exceeded (free plan) |
503 | Trust gate unavailable — request denied (fail-closed) |