Official TypeScript SDK for Valiron - Trust Layer for Agentic Economy
npm install @valiron/sdkOfficial TypeScript SDK for Valiron - Trust Infrastructure for AI Agent Systems
Valiron verifies AI agent trustworthiness using on-chain reputation (ERC-8004) and behavioral analysis. This SDK provides routing decisions based on agent trust scores, enabling you to protect infrastructure while maintaining service availability for verified agents.
``bash`
npm install @valiron/sdkor
yarn add @valiron/sdkor
pnpm add @valiron/sdk
1. Initialize the SDK:
`typescript
import { ValironSDK } from '@valiron/sdk';
// Simple initialization (uses default production endpoint)
const valiron = new ValironSDK();
// Or with custom configuration
const valiron = new ValironSDK({
endpoint: 'https://valiron-edge-proxy.onrender.com', // default
timeout: 5000, // optional
debug: false // optional
});
`
> Note: API key authentication is not yet enforced. The apiKey field is
> reserved for future use when authentication is implemented.
2. Check agent trust before processing requests:
`typescript
const decision = await valiron.checkAgent('417');
if (decision.route === 'prod') {
return handleRequest();
} else {
return denyRequest();
}
`
The SDK returns one of four routing decisions:
- prod - Full access (trust tiers: AAA to BAA)
- prod_throttled - Rate-limited access (trust tiers: BA to B)
- sandbox - Agent under evaluation (temporary state)
- sandbox_only - Access denied (trust tiers: CAA to C)
Valiron evaluates agents using:
1. On-chain Reputation - ERC-8004 feedback submitted by other organizations
2. Behavioral Analysis - Sandbox evaluation of rate-limit compliance, error rates, and request patterns
3. Credit Rating - Moody's-style scoring system (AAA to C tiers)
``
Request → SDK.checkAgent() → Valiron API → Route Decision → Application
The SDK queries Valiron's trust infrastructure, which evaluates on-chain reputation and behavioral metrics to return a routing decision. Your application implements access control based on this decision.
`typescript`
new ValironSDK(config: ValironConfig)
Config Options:
| Option | Type | Required | Default | Description |
|--------|------|----------|---------|-------------|
| apiKey | string | No | - | API key (reserved for future use) |endpoint
| | string | No | https://valiron-edge-proxy.onrender.com | API endpoint URL |timeout
| | number | No | 5000 | Request timeout (ms) |debug
| | boolean | No | false | Enable debug logging |
#### checkAgent(agentId: string): Promise
Check routing decision for an ERC-8004 agent.
Returns:
`typescript`
{
route: 'prod' | 'prod_throttled' | 'sandbox' | 'sandbox_only',
reason: string,
explanation: string,
onChainData?: {
feedbackCount: number,
averageScore: number,
agentId: string
},
localReputation?: {
score: number,
tier: MoodysRating,
riskLevel: 'GREEN' | 'YELLOW' | 'RED',
graduated: boolean
}
}
Example:
`typescript`
const decision = await valiron.checkAgent('417');
console.log(decision.route); // 'prod'
console.log(decision.localReputation?.tier); // 'AAA'
---
#### checkWallet(wallet: string): Promise
Check routing decision for a wallet address (legacy method).
Example:
`typescript`
const decision = await valiron.checkWallet('0x742d35Cc...');
---
#### getAgentProfile(agentId: string): Promise
Get complete trust profile for an agent.
Returns:
`typescript`
{
agentId: string,
identity: {
wallet: string,
name: string,
description: string,
image: string,
endpoints: string[]
},
onchainReputation: {
count: number,
averageScore: number,
feedbackEntries: FeedbackEntry[]
},
localReputation: {
score: number,
tier: MoodysRating,
riskLevel: 'GREEN' | 'YELLOW' | 'RED',
metrics: BehavioralMetrics
},
routing: {
finalRoute: RouteDecision,
decision: string,
reasons: string[]
}
}
Example:
`typescriptScore: ${profile.localReputation.score}/100
const profile = await valiron.getAgentProfile('417');
console.log();Tier: ${profile.localReputation.tier}
console.log();On-chain feedback: ${profile.onchainReputation.count} entries
console.log();`
---
#### submitFeedback(params: SubmitFeedbackParams): Promise<{ success: boolean; txHash?: string }>
Submit feedback about an agent's behavior. Valiron handles IPFS storage and on-chain submission automatically.
Parameters:
`typescript`
{
agentId: string,
score: number, // 0-100
outcome: 'success' | 'failure',
metadata?: { // Custom metadata
[key: string]: any
}
}
Example:
`typescript`
await valiron.submitFeedback({
agentId: '417',
score: 95,
outcome: 'success',
metadata: {
taskType: 'data_processing',
duration: 2340,
recordsProcessed: 10000
}
});
---
#### triggerSandboxTest(params: SandboxTestParams): Promise<{ success: boolean; message: string }>
Manually trigger sandbox testing for an agent.
Example:
`typescript`
await valiron.triggerSandboxTest({
agentId: '417',
behaviorType: 'good'
});
---
`typescript
import { ValironSDK } from '@valiron/sdk';
import express from 'express';
const app = express();
const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY! });
async function valironMiddleware(req, res, next) {
const agentId = req.headers['x-agent-id'];
const decision = await valiron.checkAgent(agentId);
if (decision.route === 'prod' || decision.route === 'prod_throttled') {
return next();
}
return res.status(403).json({
error: 'Access denied',
reason: decision.reason
});
}
app.use('/api/protected/*', valironMiddleware);
`
`typescript
// middleware.ts
import { NextRequest, NextResponse } from 'next/server';
import { ValironSDK } from '@valiron/sdk';
const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY! });
export async function middleware(request: NextRequest) {
const agentId = request.headers.get('x-agent-id');
const decision = await valiron.checkAgent(agentId!);
if (decision.route === 'prod' || decision.route === 'prod_throttled') {
return NextResponse.next();
}
return NextResponse.json(
{ error: 'Access denied' },
{ status: 403 }
);
}
export const config = {
matcher: '/api/protected/:path*'
};
`
`typescript
import { ValironSDK } from '@valiron/sdk';
const valiron = new ValironSDK({ apiKey: 'vln_xxx' });
async function handleRequest(agentId: string) {
const decision = await valiron.checkAgent(agentId);
switch (decision.route) {
case 'prod':
return processRequest({ rateLimit: null });
case 'prod_throttled':
return processRequest({ rateLimit: '100/hour' });
case 'sandbox':
return { error: 'Agent under evaluation', retryAfter: 30 };
case 'sandbox_only':
return { error: 'Access denied', reason: decision.reason };
}
}
`
Valiron integrates with x402 payment-gated APIs (e.g., Orthogonal). Verify trust before processing payments to prevent malicious agents from accessing paid endpoints.
#### Server-Side: Validate Trust + Payment
`typescript
import { ValironSDK } from '@valiron/sdk';
import { privateKeyToAccount } from 'viem/accounts';
import { getAddress } from 'viem';
import { exact } from 'x402/schemes'; // Real x402 package
const valiron = new ValironSDK();
async function trustThenPayment(req, res, next) {
const agentId = req.headers['x-agent-id'];
const paymentHeader = req.headers['x-payment'];
// Step 1: Verify trust before payment
const { route, localReputation } = await valiron.checkAgent(agentId);
if (route === 'sandbox_only') {
return res.status(403).json({
error: 'Agent banned',
reason: 'Failed behavioral trust requirements'
});
}
if (route === 'sandbox') {
return res.status(403).json({
error: 'Agent under evaluation',
retryAfter: 30
});
}
// Step 2: Verify payment (trusted agents only)
if (!paymentHeader) {
// Dynamic pricing based on trust tier
const pricing = {
'AAA': 5, 'AA': 5, 'A': 8, 'BAA': 10,
'BA': 25, 'B': 50, 'CAA': 100, 'CA': 100, 'C': 100
};
return res.status(402).json({
error: 'Payment Required',
accepts: [{
scheme: 'exact',
network: 'base',
maxAmountRequired: pricing[localReputation?.tier || 'B'],
asset: '0x...',
payTo: '0x...',
// ... x402 payment requirements
}]
});
}
// Verify payment (use x402 library)
const valid = await exact.evm.verifyPayment(paymentHeader);
if (!valid) {
return res.status(402).json({ error: 'Invalid payment' });
}
// Step 3: Apply trust-based rate limits
req.rateLimit = route === 'prod' ? 1000 : 100; // requests/hour
next();
}
app.get('/api/premium/weather', trustThenPayment, handler);
`
#### Client-Side: Make Trusted Payments
`typescript
import { ValironSDK } from '@valiron/sdk';
import { exact } from 'x402/schemes';
import { privateKeyToAccount } from 'viem/accounts';
const valiron = new ValironSDK();
const account = privateKeyToAccount(process.env.PRIVATE_KEY);
async function fetchPaidAPI(agentId: string, url: string) {
// Optional: Verify own trust status
const { route } = await valiron.checkAgent(agentId);
if (route === 'sandbox_only') {
throw new Error('Agent access denied');
}
// Get payment requirements
const res = await fetch(url);
const { accepts } = await res.json();
// Create x402 payment header
const paymentHeader = await exact.evm.createPaymentHeader(
account,
1,
accepts[0]
);
// Retry with payment
const data = await fetch(url, {
headers: { 'X-PAYMENT': paymentHeader }
}).then(r => r.json());
return data;
}
`
Trust + Payment Benefits:
- Reject untrusted agents before payment verification
- Implement dynamic pricing based on trust tier
- Reduce transaction overhead by filtering banned agents
- Mitigate DDoS attacks from paid malicious requests
Compatible with:
- Orthogonal x402 API marketplace
- Any HTTP 402 Payment Required API
See examples/x402-integration.ts for complete implementation.
The SDK is fully typed. Import types as needed:
`typescript`
import {
ValironSDK,
RouteDecision,
MoodysRating,
AgentProfile,
RoutingResponse,
ValironError
} from '@valiron/sdk';
| Tier | Score Range | Risk | Access Level |
|------|-------------|------|--------------|
| AAA | 98-110 | Prime | Full production |
| AA | 92-97 | High grade | Full production |
| A | 85-91 | Upper medium | Full production |
| BAA | 75-84 | Medium | Full production (monitored) |
| BA | 65-74 | Speculative | Throttled |
| B | 50-64 | Highly speculative | Throttled |
| CAA | 35-49 | Substantial risk | Sandbox only |
| CA | 20-34 | Extremely speculative | Sandbox only |
| C | 0-19 | Default risk | Sandbox only |
`typescript
import { ValironError } from '@valiron/sdk';
try {
const decision = await valiron.checkAgent('123');
} catch (error) {
if (error instanceof ValironError) {
console.error('Code:', error.code);
console.error('Message:', error.message);
console.error('Status:', error.statusCode);
switch (error.code) {
case 'TIMEOUT_ERROR':
// Handle timeout
break;
case 'NETWORK_ERROR':
// Handle network issues
break;
case 'API_ERROR':
// Handle API errors
break;
}
}
}
``
- Email: founders@valiron.io
MIT © Valiron