-
Notifications
You must be signed in to change notification settings - Fork 0
Agent SDK Documentation
- Introduction
- Project Structure
- Core Components
- Architecture Overview
- Detailed Component Analysis
- Dependency Analysis
- Performance Considerations
- Troubleshooting Guide
- Conclusion
- Appendices
This document provides comprehensive documentation for the Countersig Network TypeScript SDK, enabling developers to integrate AI agents with the Countersig protocol. It covers SDK architecture, installation, configuration, core classes (CountersigAgent, CountersigVerifier), authentication flows, DID document building, cryptographic operations, on-chain interactions, and practical integration examples for AI frameworks (LangChain, AutoGen, CrewAI). It also includes troubleshooting guidance and best practices for production deployments.
The SDK is organized as a modular TypeScript package with clear separation of concerns:
- Core exports and re-exports in the index module
- Agent-side cryptography and challenge issuance
- Verifier-side on-chain lookups and DID document building
- Challenge generation, signing, verification, and parsing
- DID parsing/formatting and hashing
- Cryptographic helpers for keys and encodings
- Type definitions for contracts, identities, and verification artifacts
- ABI definitions for on-chain contracts
- Package metadata and build configuration
graph TB
subgraph "SDK Core"
IDX["index.ts"]
AG["agent.ts"]
VR["verifier.ts"]
CH["challenge.ts"]
DD["did.ts"]
KY["keys.ts"]
TP["types.ts"]
AB["abis.ts"]
end
subgraph "Build & Config"
PJ["package.json"]
TC["tsconfig.json"]
end
IDX --> AG
IDX --> VR
IDX --> CH
IDX --> DD
IDX --> KY
IDX --> TP
IDX --> AB
AG --> KY
AG --> DD
AG --> CH
VR --> DD
VR --> CH
VR --> KY
VR --> AB
VR --> TP
CH --> KY
KY --> PJ
TP --> PJ
Diagram sources
- index.ts:1-36
- agent.ts:1-80
- verifier.ts:1-160
- challenge.ts:1-78
- did.ts:1-29
- keys.ts:1-91
- types.ts:1-66
- abis.ts:1-25
- package.json:1-34
- tsconfig.json:1-19
Section sources
- index.ts:1-36
- package.json:1-34
- tsconfig.json:1-19
This section documents the primary SDK classes and utilities, their responsibilities, and how they fit together.
- CountersigAgent
- Purpose: Manages Ed25519 keypair, exposes DID and didHash, issues challenges, and signs challenge payloads.
- Key capabilities:
- Static factory for generating a new agent with a fresh Ed25519 seed
- Deterministic DID computation from agent address and chainId
- Challenge issuance with configurable TTL
- Ed25519 signature generation for challenge payloads
- CountersigVerifier
- Purpose: Interacts with on-chain contracts to resolve agent identity, reputation, and stake; builds W3C-compliant DID documents; verifies signatures.
- Key capabilities:
- Resolve identity by DID
- Check agent status and activity
- Retrieve reputation metrics and thresholds
- Stake queries and minimum stake checks
- Verify challenge signatures using on-chain public key
- Build DID Document with Ed25519VerificationKey2020
- Utility modules
- Challenge: Challenge generation, signing, verification, parsing, expiration checks
- DID: Parsing, formatting, and didHash computation
- Keys: Base58 encode/decode, hex conversions, Ed25519 keypair derivation, multibase encoding
- Types: Strongly typed interfaces for contracts, identities, challenges, verification config, and DID documents
- ABIs: Typed ABI definitions for Identity, Reputation, and Staking contracts
Section sources
- agent.ts:7-79
- verifier.ts:15-133
- challenge.ts:11-77
- did.ts:8-28
- keys.ts:75-90
- types.ts:1-66
- abis.ts:1-25
The SDK implements a layered architecture:
- Off-chain agent layer: Generates Ed25519 keys, creates challenges, signs payloads, and resolves DIDs
- DID resolver layer: Provides DID parsing and didHash computation
- On-chain verification layer: Uses Ethers.js providers to query Identity, Reputation, and Staking contracts
- Oracle network (conceptual): Supplies reputation updates off-chain (not part of the SDK)
graph TB
subgraph "Off-Chain"
A["Agent A<br/>CountersigAgent"]
B["Agent B<br/>CountersigAgent"]
V["Verifier<br/>CountersigVerifier"]
end
subgraph "DID Layer"
D["DID Utils<br/>parseDid, formatDid, computeDidHash"]
end
subgraph "On-Chain"
ID["Identity Contract"]
REP["Reputation Contract"]
ST["Staking Contract"]
end
A --> |"issueChallenge"| B
B --> |"verifySignature"| V
V --> |"getIdentity, isActive, getReputation, getStake"| ID
V --> |"getReputation, meetsThreshold"| REP
V --> |"getStake, hasMinimumStake, minimumStake"| ST
A --> |"DID/DID Hash"| D
B --> |"DID/DID Hash"| D
Diagram sources
- agent.ts:70-78
- verifier.ts:50-107
- did.ts:8-28
- abis.ts:1-25
CountersigAgent encapsulates agent identity and challenge-handling logic. It manages Ed25519 keypair derivation, DID computation, challenge issuance, and signature generation.
classDiagram
class CountersigAgent {
-keyPair
-_agentAddress
-_chainId
-_challengeTtl
+constructor(options)
+static generate(options)
+agentAddress
+did
+didHash
+publicKeyBytes32
+issueChallenge(peerDid, ttlSeconds)
+signChallenge(payload)
}
Diagram sources
- agent.ts:7-79
Key methods and parameters:
- Constructor options:
- privateKey: Ed25519 seed (string or Uint8Array)
- agentAddress: Ethereum address of the agent
- chainId: Numeric chain identifier
- challengeTtlSeconds: Optional TTL for issued challenges (default 300 seconds)
- Static factory:
- generate(options): Creates a new agent with a random seed and returns both agent and the seed for secure storage
- Properties:
- agentAddress: Lowercased agent address
- did: Deterministic DID string
- didHash: On-chain didHash derived from agent address and chainId
- publicKeyBytes32: 32-byte hex public key for on-chain registration
- Methods:
- issueChallenge(peerDid, ttlSeconds?): Issues a challenge payload with a random nonce and timestamp; TTL overrides default if provided
- signChallenge(payload): Signs the challenge payload with the agent’s Ed25519 secret key and returns a base58-encoded signature
Return values:
- did: String in format did:countersig:{chainId}:{agentAddress}
- didHash: 32-byte hex string
- publicKeyBytes32: 0x-prefixed 64-character hex string
- issueChallenge: Challenge object with payload, nonce, timestamp, expiresAt
- signChallenge: Base58-encoded signature string
Security and correctness:
- Deterministic keypair derivation from seed ensures reproducible public key
- Random nonce generation per challenge prevents replay attacks
- Default TTL of 300 seconds balances usability and security
Section sources
- agent.ts:13-49
- agent.ts:51-78
- challenge.ts:11-16
- keys.ts:62-73
- did.ts:14-28
CountersigVerifier provides on-chain lookups and verification utilities. It interacts with Identity, Reputation, and Staking contracts and constructs W3C-compliant DID documents.
classDiagram
class CountersigVerifier {
-provider
-addresses
-_chainId
+constructor(config)
+getIdentity(did)
+isActive(did)
+getReputation(did)
+meetsThreshold(did, threshold)
+getStake(did)
+hasMinimumStake(did)
+verifySignature(did, challengePayload, signatureBase58)
+buildDidDocument(did)
}
Diagram sources
- verifier.ts:15-133
Key methods and parameters:
- Constructor config:
- rpcUrl: JSON-RPC endpoint
- addresses: Contract addresses for identity, reputation, staking
- chainId: Optional override for chainId resolution
- Methods:
- getIdentity(did): Returns operator, agentAddress, ed25519PubKey, status, registeredAt
- isActive(did): Boolean check for active status
- getReputation(did): Returns structured reputation metrics and total score
- meetsThreshold(did, threshold): Checks if total reputation meets threshold
- getStake(did): Returns stake amount
- hasMinimumStake(did): Checks if stake meets minimum requirement
- verifySignature(did, challengePayload, signatureBase58): Resolves on-chain public key and verifies Ed25519 signature
- buildDidDocument(did): Builds a W3C DID Document with Ed25519VerificationKey2020
Return values:
- getIdentity: AgentIdentity object
- getReputation: ReputationData object
- meetsThreshold: boolean
- verifySignature: boolean
- buildDidDocument: DidDocument object compliant with W3C standards
On-chain interaction patterns:
- Uses Ethers.js JsonRpcProvider to query contracts
- Computes didHash from DID components for on-chain lookups
- Converts bytes32 public key to Uint8Array for verification
Section sources
- verifier.ts:20-43
- verifier.ts:50-107
- verifier.ts:109-132
- types.ts:13-30
- types.ts:51-65
These modules provide cryptographic primitives and utilities for challenge-response protocols and DID handling.
flowchart TD
Start(["Challenge Generation"]) --> Gen["Generate random nonce<br/>and timestamp"]
Gen --> Payload["Build payload:<br/>COUNTERSIG-VERIFY:{proverDid}:{nonce}:{timestamp}"]
Payload --> Expires["Compute expiresAt = timestamp + ttlSeconds"]
Expires --> Return(["Return Challenge"])
subgraph "Signing"
S1["Encode payload to bytes"] --> S2["Sign with Ed25519 secret key"]
S2 --> S3["Base58 encode signature"]
S3 --> S4["Return base58 signature"]
end
subgraph "Verification"
V1["Encode payload to bytes"] --> V2["Decode base58 signature"]
V2 --> V3["Verify against Ed25519 public key"]
V3 --> V4["Return boolean"]
end
Diagram sources
- challenge.ts:11-35
- keys.ts:75-90
Key utilities:
- Challenge generation and parsing
- Ed25519 signing and verification
- Base58 encoding/decoding
- Hex and bytes conversion
- Ed25519 keypair derivation from seed
- DID parsing, formatting, and didHash computation
- Multibase encoding for W3C compliance
Section sources
- challenge.ts:11-77
- did.ts:8-28
- keys.ts:7-90
The agent-to-agent authentication flow leverages Ed25519 challenge-response and on-chain identity verification.
sequenceDiagram
participant A as "Agent A<br/>CountersigAgent"
participant B as "Agent B<br/>CountersigAgent"
participant V as "Verifier<br/>CountersigVerifier"
participant ID as "Identity Contract"
A->>B : "Issue challenge with payload"
B->>A : "Challenge payload"
A->>A : "Sign payload with Ed25519"
A->>B : "{ did, signature }"
B->>V : "verifySignature(did, payload, signature)"
V->>ID : "getIdentity(didHash)"
ID-->>V : "AgentIdentity { ed25519PubKey, status }"
V->>V : "Verify Ed25519 signature"
V-->>B : "Boolean result"
Diagram sources
- agent.ts:70-78
- verifier.ts:101-107
- challenge.ts:19-35
The verifier can construct a W3C-compliant DID Document for an agent’s DID, embedding the Ed25519 public key.
flowchart TD
D1["Get Identity from chain"] --> D2["Extract operator and ed25519PubKey"]
D2 --> D3["Convert bytes32 pubKey to Uint8Array"]
D3 --> D4["Compute publicKeyMultibase (z-prefix)"]
D4 --> D5["Assemble DidDocument with context, id, controller, verificationMethod, authentication, assertionMethod"]
D5 --> D6["Return DidDocument"]
Diagram sources
- verifier.ts:109-132
- keys.ts:87-90
The SDK depends on:
- Ethers.js for on-chain interactions
- TweetNaCl for Ed25519 cryptography
- TypeScript compiler and Vitest for testing
graph TB
AG["CountersigAgent"] --> KY["keys.ts"]
AG --> DD["did.ts"]
AG --> CH["challenge.ts"]
VR["CountersigVerifier"] --> DD
VR --> CH
VR --> KY
VR --> AB["abis.ts"]
VR --> TP["types.ts"]
CH --> KY
KY --> PJ["package.json"]
TP --> PJ
Diagram sources
- agent.ts:1-5
- verifier.ts:1-6
- challenge.ts:1-4
- keys.ts:1
- abis.ts:1-25
- types.ts:1-66
- package.json:13-21
Section sources
- package.json:13-21
- Challenge TTL: Set appropriate TTL to balance security and latency; default 300 seconds is suitable for most scenarios.
- Asynchronous on-chain calls: Use Promise.all for concurrent reputation and total score retrieval to reduce latency.
- Deterministic DID hashing: Precompute didHash to avoid repeated computations.
- Base58 encoding: Efficiently encodes signatures; ensure minimal allocations when handling large volumes.
- Provider caching: Reuse a single JsonRpcProvider instance across verifier instances to reduce overhead.
Common issues and resolutions:
- Invalid DID format: Ensure DID follows did:countersig:{chainId}:{agentAddress}. Validation throws errors for malformed inputs.
- Signature verification fails:
- Confirm the payload matches exactly what was signed (no trailing whitespace or modifications)
- Verify the correct public key is used (resolved from on-chain identity)
- Check that the signature is base58-encoded and 64 bytes decoded
- Challenge expired: Increase TTL or regenerate challenge if the timestamp exceeds allowed age
- On-chain lookup failures:
- Verify RPC URL and contract addresses
- Confirm chainId alignment with the DID and provider
- Ensure the agent is registered and has a non-zero registeredAt timestamp
- Integration test environment:
- Provide COUNTERSIG_RPC_URL, COUNTERSIG_IDENTITY_ADDRESS, COUNTERSIG_REPUTATION_ADDRESS, COUNTERSIG_STAKING_ADDRESS, COUNTERSIG_OPERATOR_PRIVATE_KEY to run integration tests against a live network
Section sources
- did.test.ts:27-31
- challenge.test.ts:45-47
- challenge.test.ts:87-95
- integration.test.ts:30-36
- integration.test.ts:60-66
The Countersig Network TypeScript SDK provides a robust foundation for integrating AI agents with on-chain identity, reputation, and A2A authentication. By leveraging Ed25519 challenge-response and W3C-compliant DID documents, agents can establish verifiable trust across decentralized networks. The included utilities and examples facilitate secure key management, efficient on-chain interactions, and seamless integration with popular AI frameworks.
- Install the SDK package using npm.
- Configure TypeScript compiler settings and ensure proper module resolution.
- Provide environment variables for agent private key, agent address, chainId, and RPC endpoints.
Section sources
- README.md:268-270
- package.json:8-12
- tsconfig.json:2-15
- CountersigAgent constructor:
- privateKey: Ed25519 seed (32 bytes)
- agentAddress: Ethereum address of the agent
- chainId: Numeric chain identifier
- challengeTtlSeconds: Optional TTL override for issued challenges
- Verifier constructor:
- rpcUrl: JSON-RPC endpoint
- addresses: Identity, Reputation, Staking contract addresses
- chainId: Optional override for chainId resolution
Section sources
- agent.ts:13-23
- verifier.ts:20-24
- types.ts:45-49
- LangChain, AutoGen, CrewAI integrations demonstrate middleware patterns, authenticated tool calls, and reputation-gated execution.
- TypeScript/Node.js examples show challenge-response handling and audit ingestion.
Section sources
- ai-frameworks.md:171-269
- Operator registration: registerAgent helper submits on-chain registration with bytes32 public key and parses the emitted didHash.
- Identity resolution: getIdentity retrieves operator, agentAddress, ed25519PubKey, status, and registeredAt.
- Reputation checks: getReputation and meetsThreshold enable trust decisions.
- Stake queries: getStake and hasMinimumStake support compliance and risk controls.
Section sources
- verifier.ts:136-159
- verifier.ts:50-107
- abis.ts:1-25
- Secure seed storage: Never expose or log Ed25519 seeds; store as environment variables or secure vaults.
- ChainId consistency: Ensure chainId aligns with the target network and DID components.
- Gas optimization: Batch on-chain calls where possible; use cached provider instances.
- Audit trail: Include agent_did in every audit ingestion call for forensic traceability.
- Threshold tuning: Adjust meetsThreshold values according to risk tolerance and operational policies.
Section sources
- README.md:361-389
Start Here
Core Concepts
Smart Contracts
Oracle System
Agent SDK
Integration Guides
Economic Model
Deployment & Ops
Advanced Topics