Skip to main content
Version: 0.1.0

Agent SDK

Type-safe TypeScript client for the BaseCred Agent API.

The @basecred/agent-sdk package wraps the Agent API into a typed client with built-in error handling, registration polling, and ZK proof support.

Installation

npm install @basecred/agent-sdk

Quick Start

import { BasecredAgent } from "@basecred/agent-sdk";

const agent = new BasecredAgent({ apiKey: "bc_your_api_key" });
const result = await agent.checkOwner();

console.log(result.summary);
// "Your reputation is strong across all contexts."

Registration Flow

New agents must register and be verified by their owner before the API key becomes active.

1. Register

import { BasecredAgent } from "@basecred/agent-sdk";

const registration = await BasecredAgent.register({
agentName: "my_agent",
contactHandle: "@owner_tg",
ownerAddress: "0x1234...abcd",
webhookUrl: "https://example.com/webhook", // optional
});

// SAVE THIS — it will not be shown again
console.log(registration.apiKey);

// Send this URL to the owner
console.log(registration.claimUrl);

The returned Registration object contains:

PropertyTypeDescription
apiKeystringAPI key (save immediately, shown only once)
claimIdstringUnique claim identifier
claimUrlstringURL the owner visits to verify
verificationCodestringCode the owner includes in their tweet

2. Poll for Verification

Use the async generator to watch for status changes:

for await (const status of registration.poll()) {
console.log(status.status); // "pending_claim" → "verified"
if (status.status === "verified") break;
}

Or use the convenience method that resolves when verified:

const verified = await registration.waitUntilVerified();

Poll Options

OptionTypeDefaultDescription
intervalMsnumber5000Milliseconds between polls
maxAttemptsnumber720Max polls (~1 hour at 5s)
signalAbortSignalCancel polling

3. Use the API Key

Once verified, create a client and start checking reputation:

const agent = new BasecredAgent({ apiKey: registration.apiKey });
const result = await agent.checkOwner();

API Methods

Authenticated (requires API key)

MethodReturnsDescription
checkOwner()ReputationResultCheck owner reputation across all contexts with ZK proofs and on-chain submission. Can take up to 90s.

Public (no auth, uses instance config)

MethodReturnsDescription
getContexts()ContextInfo[]List all available decision contexts
getPolicies()PolicyInfo[]List all policies with context and policy hash
getFeed(limit?)FeedEntry[]Get the global activity feed
getStats()ProtocolStatsGet aggregated protocol statistics

Static (no API key required)

MethodReturnsDescription
BasecredAgent.register(input, options?)RegistrationRegister a new agent
BasecredAgent.checkRegistration(claimId, options?)RegistrationStatusCheck status of an existing registration

Configuration

const agent = new BasecredAgent({
apiKey: "bc_your_api_key", // Required
baseUrl: "https://www.zkbasecred.xyz", // Optional (default)
timeoutMs: 120_000, // Optional (default: 120s)
fetch: customFetch, // Optional (default: global fetch)
});

Error Handling

All API errors are mapped to typed error classes extending BasecredError:

import {
BasecredAgent,
AuthError,
RateLimitError,
ValidationError,
NotFoundError,
ServiceUnavailableError,
ServerError,
NetworkError,
} from "@basecred/agent-sdk";

try {
const result = await agent.checkOwner();
} catch (error) {
if (error instanceof AuthError) {
// 401 — invalid or missing API key
} else if (error instanceof RateLimitError) {
// 429 — back off for error.retryAfter seconds
console.log(`Retry after ${error.retryAfter}s`);
} else if (error instanceof ServiceUnavailableError) {
// 503 — ZK circuit files not available
} else if (error instanceof NetworkError) {
// DNS failure, timeout, etc.
}
}

Error Classes

ClassHTTP StatusDescription
BasecredErrorBase class. All errors have status, code, message.
AuthError401Invalid or missing API key
RateLimitError429Rate limit exceeded. Has retryAfter (seconds).
ValidationError400Bad request parameters
NotFoundError404Resource not found
ServiceUnavailableError503Service temporarily unavailable
ServerError5xxUnexpected server error
NetworkError0Network failure (DNS, timeout, etc.)

Key Types

TypeDescription
BasecredAgentConfigConstructor config (apiKey, baseUrl, timeoutMs, fetch)
PublicRequestOptionsOptions for static methods (baseUrl, timeoutMs, fetch)
RegisterAgentInputInput for register() (agentName, contactHandle, ownerAddress, webhookUrl?)
RegistrationReturned by register(). Has apiKey, claimId, poll(), waitUntilVerified().
RegistrationStatusPoll result (status, agentName, verificationCode?, expiresAt?)
RegistrationStatusValue"pending_claim" | "verified" | "expired" | "revoked"
ReputationResultFull check result (ownerAddress, agentName, summary, signals, results)
ContextResultPer-context decision (decision, confidence, constraints, proof?, onChain?)
NormalizedSignalsReputation signals (trust, socialTrust, builder, creator, recencyDays, spamRisk)
FeedEntryActivity feed item (agentName, ownerAddress, context, txHash?, timestamp)
PolicyInfoPolicy details (context, policyHash, normalizationVersion)
ProtocolStatsAggregated stats (totalDecisions, uniqueAgents, decisionsByOutcome, etc.)
PollOptionsPolling config (intervalMs, maxAttempts, signal)

Further Reading