Skip to content

Developer Resources

dev-mondoshawan edited this page Jul 1, 2026 · 1 revision

Developer Resources

**Referenced Files in This Document** - [README.md](file://README.md) - [foundry.toml](file://foundry.toml) - [CountersigIdentity.sol](file://src/CountersigIdentity.sol) - [CountersigReputation.sol](file://src/CountersigReputation.sol) - [CountersigStaking.sol](file://src/CountersigStaking.sol) - [index.ts](file://packages/sdk/src/index.ts) - [types.ts](file://packages/sdk/src/types.ts) - [agent.ts](file://packages/sdk/src/agent.ts) - [verifier.ts](file://packages/sdk/src/verifier.ts) - [quickstart.md](file://docs/quickstart.md) - [ecosystem.md](file://docs/ecosystem.md) - [agent.test.ts](file://packages/sdk/test/agent.test.ts) - [challenge.test.ts](file://packages/sdk/test/challenge.test.ts) - [integration.test.ts](file://packages/sdk/test/integration.test.ts) - [package.json](file://packages/sdk/package.json)

Table of Contents

  1. Introduction
  2. Project Structure
  3. Core Components
  4. Architecture Overview
  5. Detailed Component Analysis
  6. API Reference
  7. Development Environment Setup
  8. Testing Framework
  9. Contribution Guidelines
  10. Code Examples and Integration Templates
  11. Best Practices
  12. Community and Support
  13. Troubleshooting Guide
  14. Conclusion

Introduction

This document is a comprehensive developer resource for contributors and integrators working with the Countersig Network. It covers the protocol’s architecture, on-chain contracts, the TypeScript SDK, API references, development setup, testing, contribution guidelines, integration patterns, and best practices. It also outlines debugging approaches and community resources to help you build secure, verifiable, and auditable AI agent systems anchored on-chain.

Project Structure

The repository is organized into:

  • Solidity contracts under src/
  • TypeScript SDK under packages/sdk/
  • Foundry configuration for EVM development
  • Documentation under docs/
  • Oracle reference implementation under oracle/
graph TB
subgraph "Contracts (Solidity)"
A["CountersigIdentity.sol"]
B["CountersigReputation.sol"]
C["CountersigStaking.sol"]
end
subgraph "SDK (TypeScript)"
D["packages/sdk/src/index.ts"]
E["packages/sdk/src/agent.ts"]
F["packages/sdk/src/verifier.ts"]
G["packages/sdk/src/types.ts"]
end
subgraph "Tooling"
H["foundry.toml"]
I["docs/quickstart.md"]
J["docs/ecosystem.md"]
end
A --- D
B --- D
C --- D
D --- E
D --- F
D --- G
H --- A
H --- B
H --- C
I --- D
J --- A
J --- B
J --- C
Loading

Diagram sources

  • CountersigIdentity.sol
  • CountersigReputation.sol
  • CountersigStaking.sol
  • index.ts
  • agent.ts
  • verifier.ts
  • types.ts
  • foundry.toml
  • quickstart.md
  • ecosystem.md

Section sources

  • README.md
  • foundry.toml

Core Components

  • CountersigIdentity: On-chain DID anchoring, public key storage, agent status lifecycle, and didHash computation.
  • CountersigReputation: Oracle-written 6-factor reputation store with threshold checks.
  • CountersigStaking: CSIG staking, slashing lifecycle, and distribution mechanics.
  • TypeScript SDK: Agent creation/signing, verifier utilities, DID/DID hash helpers, and on-chain registration.

Key relationships:

  • CountersigStaking depends on CountersigIdentity and CountersigReputation for state transitions and score zeroing.
  • CountersigReputation is updated by oracles; CountersigIdentity validates status transitions.
  • The SDK provides agent-side cryptography and on-chain verification utilities.

Section sources

  • CountersigIdentity.sol
  • CountersigReputation.sol
  • CountersigStaking.sol
  • index.ts

Architecture Overview

The protocol consists of three on-chain layers reinforced by off-chain services:

  • Identity: Deterministic DID anchoring and status control.
  • Reputation: Verified score store with threshold gating.
  • Staking: Permissioned slash initiation and execution with a challenge window.
  • Oracle: Off-chain aggregation and on-chain score updates.
  • CounterAudit: Forensically enriched audit trails with frozen-in-time reputation.
graph TB
subgraph "Off-chain"
OA["Agent Nodes<br/>Ed25519 PKI"]
OR["Oracle Network<br/>24h Epoch Aggregation"]
CA["CounterAudit<br/>Tamper-Evident Seals"]
end
subgraph "On-chain"
ID["CountersigIdentity<br/>DID anchoring · pubkey · status"]
REP["CountersigReputation<br/>6-factor store · thresholds"]
ST["CountersigStaking<br/>CSIG bonds · slash lifecycle"]
end
OA --> |"Challenge-response"| OA
OA --> |"Resolve DID"| ID
OR --> |"updateReputation()"| REP
ST --> |"updateStatus(Slashed)"| ID
ST --> |"zeroReputation()"| REP
CA --> |"Read identity + score"| ID
CA --> |"Read identity + score"| REP
Loading

Diagram sources

  • README.md
  • CountersigIdentity.sol
  • CountersigReputation.sol
  • CountersigStaking.sol

Detailed Component Analysis

CountersigIdentity

Responsibilities:

  • Register agents with deterministic didHash derivation.
  • Store operator address, agent Ethereum address, and Ed25519 public key.
  • Manage AgentStatus (Active, Suspended, Slashed) with role-gated transitions.
  • Rotate public keys for compromised key recovery (except Slashed).

Key functions and behaviors:

  • registerAgent: Validates inputs, computes didHash, stores identity, emits AgentRegistered.
  • updateStatus: Operator toggles Active/Suspended; STAKING_CORE_ROLE sets Slashed.
  • rotatePublicKey: Operator rotates key; Slashed agents cannot rotate.
  • computeDidHash: Pure view to derive didHash deterministically.
flowchart TD
Start(["registerAgent"]) --> CheckInputs["Validate agentAddress ≠ 0<br/>ed25519PubKey ≠ 0"]
CheckInputs --> ComputeHash["Compute didHash"]
ComputeHash --> Exists{"Already registered?"}
Exists --> |Yes| Revert["Revert AlreadyRegistered"]
Exists --> |No| Store["Store AgentIdentity<br/>operator, agentAddress, pubKey, status=Active"]
Store --> Emit["Emit AgentRegistered"]
Emit --> End(["Return didHash"])
Loading

Diagram sources

  • CountersigIdentity.sol

Section sources

  • CountersigIdentity.sol

CountersigReputation

Responsibilities:

  • Store 6-factor reputation data per didHash.
  • Enforce factor caps at write time.
  • Provide getTotalScore and meetsThreshold for on-chain consumers.

Key functions and behaviors:

  • updateReputation: Only callable by ORACLE_ROLE; validates per-factor caps and emits ReputationUpdated.
  • zeroReputation: Callable by STAKING_CORE_ROLE; resets scores while preserving lastUpdated.
  • getTotalScore/meetsThreshold: View helpers to compute and compare totals.
flowchart TD
Start(["updateReputation"]) --> Validate["Validate each factor ≤ cap"]
Validate --> Write["Write ReputationData<br/>with lastUpdated"]
Write --> Emit["Emit ReputationUpdated(didHash, total, timestamp)"]
Emit --> End(["Done"])
Loading

Diagram sources

  • CountersigReputation.sol

Section sources

  • CountersigReputation.sol

CountersigStaking

Responsibilities:

  • Manage CSIG bond deposits and withdrawals.
  • Enforce slashing lifecycle with a challenge window.
  • Distribute slashed tokens and trigger identity/status changes.

Key functions and behaviors:

  • depositStake: Requires active identity and operator authorization.
  • withdrawStake: Enforces minimum stake and no pending slash.
  • initiateSlash: Suspends agent and creates a Pending slash proposal.
  • disputeSlash: Operator cancels proposal during challenge window.
  • executeSlash: Permissionless execution burns 50%, pays 25% to victim and reporter; marks agent Slashed and zeros reputation.
sequenceDiagram
participant CM as "Committee Member"
participant ST as "CountersigStaking"
participant ID as "CountersigIdentity"
participant REP as "CountersigReputation"
CM->>ST : initiateSlash(didHash, victim, evidenceHash)
ST->>ID : updateStatus(didHash, Suspended)
Note over ST : Challenge window starts
opt Operator disputes within window
ST->>ID : updateStatus(didHash, Active)
end
opt Window passes undisputed
ST->>ST : executeSlash(didHash)
ST->>ID : updateStatus(didHash, Slashed)
ST->>REP : zeroReputation(didHash)
ST-->>0xdead : Burn 50%
ST-->>victim : Pay 25%
ST-->>reporter : Pay 25%
end
Loading

Diagram sources

  • CountersigStaking.sol
  • CountersigIdentity.sol
  • CountersigReputation.sol

Section sources

  • CountersigStaking.sol

TypeScript SDK

The SDK provides:

  • CountersigAgent: Ed25519 keypair generation, challenge issuance, and signature signing.
  • CountersigVerifier: On-chain lookups, signature verification, DID document building, and threshold checks.
  • Utility functions: DID/DID hash helpers, key conversions, challenge parsing and expiration.
classDiagram
class CountersigAgent {
+constructor(options)
+static generate(options)
+agentAddress string
+did string
+didHash string
+publicKeyBytes32 string
+issueChallenge(peerDid, ttl?) Challenge
+signChallenge(payload) string
}
class CountersigVerifier {
+constructor(config)
+getIdentity(did) Promise~AgentIdentity~
+isActive(did) Promise~boolean~
+getReputation(did) Promise~ReputationData~
+meetsThreshold(did, threshold) Promise~boolean~
+getStake(did) Promise~bigint~
+hasMinimumStake(did) Promise~boolean~
+verifySignature(did, payload, signature) Promise~boolean~
+buildDidDocument(did) Promise~DidDocument~
}
class registerAgent {
+(signer, agentAddress, ed25519PubKey, identityAddress) Promise~{didHash, txHash}~
}
CountersigAgent --> CountersigVerifier : "consumes types"
CountersigVerifier --> CountersigAgent : "verifies signatures"
registerAgent --> CountersigAgent : "uses publicKeyBytes32"
Loading

Diagram sources

  • agent.ts
  • verifier.ts
  • types.ts
  • index.ts

Section sources

  • agent.ts
  • verifier.ts
  • types.ts
  • index.ts

API Reference

Solidity Contracts

CountersigIdentity

  • registerAgent(agentAddress, ed25519PubKey) → bytes32 didHash

    • Parameters: agentAddress (non-zero), ed25519PubKey (bytes32)
    • Returns: didHash
    • Emits: AgentRegistered
    • Errors: ZeroAgentAddress, ZeroPubKey, AlreadyRegistered
  • updateStatus(didHash, newStatus)

    • Parameters: didHash, AgentStatus (Active, Suspended, Slashed)
    • Role gating: STAKING_CORE_ROLE can set Slashed; others require operator
    • Emits: AgentStatusUpdated
    • Errors: NotRegistered, NotOperator, SlashedAgentImmutable
  • rotatePublicKey(didHash, newEd25519PubKey)

    • Parameters: didHash, newEd25519PubKey (non-zero)
    • Role: operator
    • Emits: PublicKeyRotated
    • Errors: NotRegistered, NotOperator, SlashedAgentImmutable, ZeroPubKey
  • computeDidHash(agentAddress) → bytes32

    • Parameters: agentAddress
    • Returns: didHash (pure view)
  • getIdentity(didHash) → AgentIdentity

  • isActive(didHash) → bool

  • getOperatorAgents(operator) → bytes32[]

Section sources

  • CountersigIdentity.sol

CountersigReputation

  • updateReputation(didHash, data)

    • Parameters: didHash, ReputationData (factor caps enforced)
    • Role: ORACLE_ROLE
    • Emits: ReputationUpdated
    • Errors: ScoreOutOfRange
  • zeroReputation(didHash)

    • Parameters: didHash
    • Role: STAKING_CORE_ROLE
    • Emits: ReputationZeroed
  • getReputation(didHash) → ReputationData

  • getTotalScore(didHash) → uint8

  • meetsThreshold(didHash, threshold) → bool

Section sources

  • CountersigReputation.sol

CountersigStaking

  • depositStake(didHash, amount)

    • Parameters: didHash, amount
    • Precondition: agent Active
    • Emits: StakeDeposited
  • withdrawStake(didHash, amount)

    • Parameters: didHash, amount
    • Constraints: no pending slash; if Active, must remain ≥ minimumStake
    • Emits: StakeWithdrawn
    • Errors: NoStake, AgentNotActive, InsufficientStake, SlashAlreadyPending
  • initiateSlash(didHash, victim, evidenceHash)

    • Role: SLASHING_COMMITTEE_ROLE
    • Side effect: immediately Suspends agent
    • Emits: SlashInitiated
  • disputeSlash(didHash)

    • Operator may cancel during challenge window
    • Emits: SlashDisputed
  • executeSlash(didHash)

    • Permissionless after challenge window
    • Distribution: 50% burn, 25% victim, 25% reporter
    • Side effects: mark Slashed, zero reputation
    • Emits: SlashExecuted
  • setMinimumStake(newMinimum)

  • setChallengePeriod(newPeriod)

  • getStake(didHash) → uint256

  • hasMinimumStake(didHash) → bool

  • getSlashProposal(didHash) → SlashProposal

Section sources

  • CountersigStaking.sol

TypeScript SDK

CountersigAgent

  • constructor({ privateKey, agentAddress, chainId, challengeTtlSeconds? })
  • static generate({ agentAddress, chainId, challengeTtlSeconds? }) → { agent, privateKey }
  • agentAddress: string
  • did: string
  • didHash: string
  • publicKeyBytes32: string
  • issueChallenge(peerDid, ttlSeconds?): Challenge
  • signChallenge(payload): string

Section sources

  • agent.ts

CountersigVerifier

  • constructor(config: { rpcUrl, addresses: ContractAddresses, chainId? })
  • getIdentity(did): Promise
  • isActive(did): Promise
  • getReputation(did): Promise
  • meetsThreshold(did, threshold): Promise
  • getStake(did): Promise
  • hasMinimumStake(did): Promise
  • verifySignature(did, challengePayload, signatureBase58): Promise
  • buildDidDocument(did): Promise

Section sources

  • verifier.ts

Utility Functions (exports)

  • generateChallenge, signChallenge, verifyChallenge, parseChallengePayload, isChallengeExpired
  • computeDidHash, formatDid, parseDid
  • base58Encode, base58Decode, hexToBytes, bytesToHex, seedToKeyPair, pubKeyToBytes32, bytes32ToPubKey, pubKeyToMultibase

Section sources

  • index.ts

Development Environment Setup

  • Prerequisites: Foundry, Node.js 18+, an Ethereum wallet with Sepolia ETH, $CSIG testnet tokens.
  • Install dependencies and build:
    • forge install
    • forge build
    • forge test
  • Run fuzz tests at higher intensity:
    • FOUNDRY_PROFILE=ci forge test
  • SDK development:
    • Build: npm run build
    • Test: npm test
    • Type check: npm run typecheck

Environment variables for integration tests:

  • COUNTERSIG_RPC_URL
  • COUNTERSIG_IDENTITY_ADDRESS
  • COUNTERSIG_REPUTATION_ADDRESS
  • COUNTERSIG_STAKING_ADDRESS
  • COUNTERSIG_OPERATOR_PRIVATE_KEY

Section sources

  • README.md
  • foundry.toml
  • package.json
  • quickstart.md

Testing Framework

  • Foundry tests for Solidity contracts (standard forge test).
  • SDK tests:
    • Unit tests for agent and challenge utilities.
    • Integration tests that require live Sepolia deployment and skip automatically if environment variables are missing.
  • Vitest is configured for SDK tests.

Recommended local testing workflow:

  • Run unit tests: npm test
  • Run integration tests with environment variables set for Sepolia deployment.

Section sources

  • agent.test.ts
  • challenge.test.ts
  • integration.test.ts
  • package.json

Contribution Guidelines

  • Fork and branch from the repository.
  • Follow existing code style and patterns (TypeScript and Solidity).
  • Add or update unit tests for new features or bug fixes.
  • Keep pull requests focused and include a clear description of the change and rationale.
  • For SDK contributions, ensure type definitions and exports are updated in index.ts.
  • For Solidity changes, include appropriate tests and consider upgradeability implications (UUPS proxies).
  • Use conventional commit messages and reference relevant issues.

[No sources needed since this section provides general guidance]

Code Examples and Integration Templates

On-chain Registration (Operator)

  • Steps: approve staking contract for CSIG, then call registerAgent with agent address and Ed25519 public key.
  • See the Quickstart guide for a full end-to-end example.

Section sources

  • quickstart.md

Agent-to-Agent Authentication

  • Agent A generates a challenge targeting Agent B’s DID.
  • Agent A signs the payload with its Ed25519 key.
  • Agent B resolves A’s public key from chain and verifies the signature via the verifier.
sequenceDiagram
participant A as "Agent A"
participant B as "Agent B"
participant V as "CountersigVerifier"
A->>B : issueChallenge(peerDid)
B->>A : challenge payload
A->>A : signChallenge(payload)
A-->>B : {did, signature}
B->>V : verifySignature(did, payload, signature)
V-->>B : boolean
Loading

Diagram sources

  • agent.ts
  • verifier.ts

Section sources

  • README.md

DID Document Resolution

  • Build a W3C-compliant DID Document with Ed25519VerificationKey2020 for onboarding and verification.

Section sources

  • verifier.ts

Best Practices

  • Secure key management: Never hardcode private keys; use environment variables and secure keystores.
  • Validate inputs: Use SDK helpers to compute didHash and DID; verify signatures before trusting peer claims.
  • Gate on-chain operations: Use meetsThreshold for access control in downstream contracts.
  • Monitor reputation: Track score changes and status transitions to inform trust decisions.
  • Upgradeability: Respect UUPS upgrade roles and timelock governance.

[No sources needed since this section provides general guidance]

Community and Support

  • Explore the ecosystem overview and integration guides for broader context.
  • Use the official documentation links for quickstart, AI framework integrations, reputation model, and tokenomics.
  • Engage with the team and community through the project’s communication channels as indicated in the repository.

Section sources

  • ecosystem.md
  • README.md

Troubleshooting Guide

Common issues and resolutions:

  • Signature verification fails:
    • Ensure the DID matches the prover’s DID in the payload.
    • Confirm the public key fetched from chain corresponds to the agent’s registered Ed25519 key.
    • Verify the challenge is not expired.
  • Registration errors:
    • ZeroAgentAddress or ZeroPubKey indicate invalid inputs.
    • AlreadyRegistered suggests the agent is already anchored.
  • Staking operations:
    • InsufficientStake occurs if withdrawal drops below minimum while Active.
    • SlashAlreadyPending prevents withdrawals during a pending slash.
  • Integration tests:
    • Missing environment variables cause automatic skipping; set all required variables to enable live tests.

Section sources

  • CountersigIdentity.sol
  • CountersigReputation.sol
  • CountersigStaking.sol
  • integration.test.ts

Conclusion

Countersig provides a robust, on-chain identity and reputation layer for AI agents, reinforced by staking and auditability. The TypeScript SDK simplifies agent creation, authentication, and verification, while the Solidity contracts offer a secure, upgradeable foundation. Use the provided APIs, examples, and best practices to integrate verifiable agent identities into your systems and contribute to the growing ecosystem.

Clone this wiki locally