Skip to documentation

Jump to a guide

Crawler ProtectionOverview · See and simulate crawler traffic, then enforce it at your edge and protect website and database capacity.Agent AccessOverview · Decide which AI agents can use your API, before they cost you money.Traffic insightsCrawler Protection · Connect request logs and see which bots reach your website, without changing any traffic.Edge rulesCrawler Protection · Test edge rules on your recent traffic, then enforce them at Cloudflare or AWS WAF.Self-hosted quickstartCrawler Protection · Run the gateway or SDK in your own infrastructure and roll it out safely.Gateway & SDK integrationCrawler Protection · Describe your routes, measure a baseline and wrap expensive work.Runtime policy & capacityCrawler Protection · Choose which crawlers the self-hosted runtime allows, set shared budgets and keep room for customers.Self-hosted controlsCrawler Protection · Change crawler access, budgets, decision logs and alerts for a running runtime.Runtime analyticsCrawler Protection · Report runtime telemetry and read what the self-hosted runtime decided.Troubleshooting & recoveryCrawler Protection · Handle limits, outages, held capacity and recovery.Bot verificationCrawler Protection · How crawler claims are checked against provider evidence and signatures.Plans & usageCrawler Protection · What each plan includes, monthly allowances and additional requests.ConceptsAgent Access · Decisions, the sandbox, supported chains and plan limits.Trust signalsAgent Access · The checks behind each decision, and how to choose them for each route.MiddlewareAgent Access · Gate routes in Express, Fastify, Next.js and other frameworks.SDK referenceAgent Access · Every SDK method, response type, telemetry option and error.InstallationAgent Access · Agent identity, access policies, and SDK integration.Identity and trustAgent Access · Agent identity, access policies, and SDK integration.API referenceAgent Access · Agent identity, access policies, and SDK integration.Errors and retriesAgent Access · Agent identity, access policies, and SDK integration.
Docs/Agent Access/SDK reference
Browse documentation

Agent Access

SDK reference

Every SDK method, response type, telemetry option and error.

OpenAPI specificationAuthentication

API Reference

Constructor

new ValironSDK(config?: ValironConfig)
OptionTypeDefaultDescription
apiKeystring—Operator API key for authenticated operations
endpointstringproductionValiron API base URL (override for self-hosted or dev)
chainSupportedChainserver defaultDefault blockchain network
timeoutnumber5000Request timeout (ms)
debugbooleanfalseEnable debug logging
telemetryTelemetryConfigenabledTelemetry 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, signals

getWalletProfile(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);
}
FieldTypeDescription
walletstringThe queried wallet address
agentIdstring | nullResolved ERC-8004 agent ID, or null if not found
sourceResolutionSource"redis" | "subgraph" | "cache" | "none"
chainIdnumber | nullChain ID from the subgraph (if available)
agentNamestring | nullAgent name from the subgraph (if available)
timestampstringISO 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 object

triggerKeyAgentSandbox(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); // 85
Auto-sandbox: Middleware automatically triggers sandbox evaluation for new agents. On-chain agents with totalFeedback === 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']
}
OptionTypeDefaultDescription
minScorenumber65Minimum score to allow (0–100)
trustSignalsArray<'8004' | 'sandbox' | 'world' | 'self' | 'icebreaker' | 'wallet'>autoOptional selected scoring signals. Free includes 8004, sandbox, world, self, and wallet. Only icebreaker (Social Graph) requires Pro.
ttlMsnumber86400000Cache TTL for sandbox results (ms)
chainSupportedChainconstructor defaultBlockchain network override
gate() vs checkAgent(): 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 FieldTypeDescription
eventstring"evaluation_complete"
agentIdstringThe evaluated agent's ID
snapshotHashstringOpaque SHA-256 hash of the evaluation
previousHashstringPrevious hash in the chain ("0x0" for first)
interactionCountnumberTotal interactions in the evaluation window
timestampstringISO 8601 timestamp
Limitations: Max 1,000 registrations. Delivery is fire-and-forget with a 10-second timeout — no retries on failure. Payloads are not signed; verify the source IP or use a secret URL path if you need sender authentication.

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 FieldTypeDescription
targetstringYour real API endpoint URL (must be HTTPS, public IP)
methodstringHTTP method (default: GET)
headersRecord<string, string>Headers to forward to target API
bodyunknownRequest body for POST/PUT/PATCH
minScorenumberMinimum trust score to allow (default: 65)
SSRF protection: The proxy blocks requests to private IP ranges (10.x, 172.16-31.x, 192.168.x, 127.x), localhost, and cloud metadata endpoints (169.254.169.254). Only public HTTPS targets are allowed.

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 typeHeaderLookup path
ERC-8004 / Solanax-agent-id/operator/agent/:agentId
Local / Web2 / non-ERC-8004x-agent-address/operator/key/:agentAddress
Important: Do not send a local agent name such as 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);
Provider proof v2: Agents send signed 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

FieldTypeDescription
allowbooleanWhether the agent is allowed through
scorenumberCombined Valiron trust score (0–100)
tierMoodysRatingAAA through C
riskLevelRiskLevel"GREEN" | "YELLOW" | "RED"
routeRouteDecisionprod / prod_throttled / sandbox / sandbox_only
agentIdstringThe evaluated agent's ID
walletstringAgent's wallet address
chainChainContextNetwork, registry addresses used
sandboxRanbooleanWhether sandbox tests ran this call (false = cached)
cachedbooleanWhether cached results were used
provisionalboolean?If true, score is from a fast micro-sandbox; a full deep test is running in the background

AgentProfile

FieldTypeDescription
agentIdstringERC-8004 agent ID
identityAgentIdentityOn-chain identity (wallet, name, endpoints, trust models)
onchainReputationOnchainReputationFeedback count, average score, entries, and Solana ATOM data
localReputationLocalReputation | nullBehavioral score, tier, riskLevel, graduated status
routingRoutingExplanationfinalRoute, decision text, reasons array, signals breakdown
chainChainContextNetwork, RPC URL, registry contract addresses
worldIdWorldIdStatus?World ID verification status (if checked)
timestampstringISO 8601 timestamp

KeyAgentProfile

FieldTypeDescription
agentAddressstringEthereum address (keccak256 of secp256k1 pubkey)
verifiedbooleanIdentity verified via challenge-response
scorenumber | nullBehavioral score (0–100)
tierMoodysRating | nullAAA through C
riskLevelRiskLevel | nullGREEN / YELLOW / RED
routeRouteDecision | nullRoute decision
icebreakerIcebreakerOwnership | nullIcebreaker attestation context
reasonsstring[]Human-readable trust explanation

Request Headers

HeaderPurposeNotes
X-Agent-IdOn-chain agent ID (ERC-8004 / Solana)Checked first by all middleware
X-Agent-AddressKey-based agent Ethereum addressFallback when no X-Agent-Id
X-ChainBlockchain network overrideAlternative to ?chain= query param
AuthorizationOperator API keyBearer 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.ts

Telemetry

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),
  },
});
OptionTypeDefaultDescription
enabledbooleantrueEnable/disable telemetry
sampleRatenumber1.0Sampling rate (0.0–1.0)
appIdstring—Application identifier for grouping
env"prod" | "staging" | "dev" | "test" | "unknown"NODE_ENV or unknownEnvironment 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 CodeMeaning
TIMEOUT_ERRORRequest exceeded the configured timeout (default 5000ms)
NETWORK_ERRORCould not reach the Valiron API (DNS, connection refused, etc.)
MISSING_AGENT_IDENTITYA trust-gated endpoint needs an agent identity header
TRUST_GATE_DENIEDAgent did not satisfy the endpoint's trust policy; inspect the returned result
API_ERRORServer returned a non-2xx response without a specific code — check error.statusCode and error.details

Common HTTP status codes from the Valiron API:

StatusCause
400Invalid agentId format or missing required fields
401Missing agent identity header (middleware) or invalid operator API key
403Agent blocked (score below threshold) or feature requires Pro plan
404Agent not found on the specified chain
429Sandbox daily limit exceeded (free plan)
503Trust gate unavailable — request denied (fail-closed)