Developer Documentation

ClearShield API

Incorporate real-time, peer-to-peer threat verification into your application, wallet, or autonomous agent. Query any address to retrieve verified incident histories.

01

Quick Start (60s)

Configure authorization headers and issue a GET query using one of our verified starter examples.

terminal
# Check a suspicious contract address using the GET endpoint
curl "https://api.clearshield.network/api/v1/check?address=0xbc8ad786e6de38c4c79893fb25db56f9a0de5b94" \
  -H "x-api-key: cs_live_7f8a9b0c1d2e3f4a5b6c7d8e9f"

# Request full individual report summaries
curl "https://api.clearshield.network/api/v1/check?address=0xbc8ad786e6de38c4c79893fb25db56f9a0de5b94&includeReports=true" \
  -H "Authorization: Bearer cs_live_7f8a9b0c1d2e3f4a5b6c7d8e9f"

Ethers.js (v6) Signer Middleware Wrapper

Intercept outbound transactions to block requests targeting addresses flagged as high or critical risk before the wallet triggers signing.

ethersSigner.ts
import { Signer, TransactionRequest } from "ethers";

// A wrapper class to validate target addresses before transaction signing
export class ClearShieldSigner extends Signer {
  constructor(
    private readonly baseSigner: Signer,
    private readonly apiKey: string
  ) {
    super(baseSigner.provider);
  }

  async sendTransaction(tx: TransactionRequest) {
    const toAddress = await tx.to;
    if (toAddress) {
      const response = await fetch(
        `https://api.clearshield.network/api/v1/check?address=${encodeURIComponent(toAddress)}`,
        { headers: { "x-api-key": this.apiKey } }
      );
      
      if (response.ok) {
        const result = await response.json();
        if (result.isFlagged && ["critical", "high"].includes(result.riskLevel)) {
          throw new Error(
            `[Security Alert] Transaction blocked. Target address ${toAddress} is flagged as ${result.riskLevel.toUpperCase()}. Verdict: ${result.verdict}`
          );
        }
      }
    }
    return this.baseSigner.sendTransaction(tx);
  }

  // Delegate required abstract methods
  getAddress() { return this.baseSigner.getAddress(); }
  signMessage(message: string | Uint8Array) { return this.baseSigner.signMessage(message); }
  signTransaction(tx: TransactionRequest) { return this.baseSigner.signTransaction(tx); }
  connect(provider: any) { return new ClearShieldSigner(this.baseSigner.connect(provider), this.apiKey); }
}
02

API Endpoints

GET https://api.clearshield.network/api/v1/checkPOST https://api.clearshield.network/api/v1/check

The endpoint validates addresses identically using query parameters (GET) or JSON parameters (POST).

POST with Structured JSON Body

terminal
curl -X POST "https://api.clearshield.network/api/v1/check" \
  -H "Content-Type: application/json" \
  -H "x-api-key: cs_live_7f8a9b0c1d2e3f4a5b6c7d8e9f" \
  -d '{
    "address": "0xbc8ad786e6de38c4c79893fb25db56f9a0de5b94",
    "includeReports": true
  }'
03

Request Parameters

ParameterTypeRequiredDescription
addressstringRequired42-character hexadecimal Ethereum address (e.g. 0xbc8ad786e6de38c4c79893fb25db56f9a0de5b94)
includeReportsbooleanOptionalSet to true to append detailed list of reported incidents
04

Response Schema

response.json
{
  "address": "0xbc8ad786e6de38c4c79893fb25db56f9a0de5b94",
  "isFlagged": true,
  "riskLevel": "high",
  "confidence": "high",
  "reportCount": 8,
  "confirmationCount": 14,
  "maxSeverity": 9,
  "dominantThreatType": "approval_drainer",
  "totalAmountLostUSD": 142050,
  "verdict": "This address is flagged as an active ERC-20 approval drainer. Multiple wallets have confirmed total losses of $142,050 USD. The contract requests unlimited token approvals under the guise of a staking transaction and siphons funds immediately. Do not interact."
}
FieldTypeDescription
addressstringThe queried EVM address in lowercase hex representation
isFlaggedbooleanEvaluates to true if riskLevel is critical, high, or medium. Prompt blocks or confirmations accordingly
riskLevelstringRisk status classification: critical | high | medium | low | unknown
confidencestringDegree of trust behind verdict: high | medium | low
reportCountnumberTotal community reports submitted against this address on Braga testnet
confirmationCountnumberTotal cryptographic signatures corroborating the submitted reports
maxSeveritynumberThe highest single severity score (1-10) among verified reports
dominantThreatTypestring?Most recurring threat category reported for this entity
totalAmountLostUSDnumber?Aggregate value of tokens and assets reported lost
verdictstringAn AI-summarized plain-English analysis explaining the assessment context
reportsarray?Detailed list of individual reported incidents. Only populated when includeReports=true

Response with includeReports=true

response_with_reports.json
{
  "address": "0xbc8ad786e6de38c4c79893fb25db56f9a0de5b94",
  "isFlagged": true,
  "riskLevel": "high",
  "confidence": "high",
  "reportCount": 8,
  "confirmationCount": 14,
  "maxSeverity": 9,
  "dominantThreatType": "approval_drainer",
  "totalAmountLostUSD": 142050,
  "verdict": "This address is flagged as an active ERC-20 approval drainer...",
  "reports": [
    {
      "entityKey": "0x4e5b2e3f8a0e1c2d3b4a5f6e7d8c9b0a1f2e3d4c",
      "threatType": "approval_drainer",
      "severityScore": 9,
      "confirmationCount": 6,
      "amountLostUSD": 85000,
      "reportedAt": 1716422400000,
      "aiSummary": "Contract poses as a decentralized yield aggregator. On calling deposit(), it attempts to execute setApprovalForAll on key token assets.",
      "creator": "0xf20aa4aad7642eeeb91398d04926ee4a2490b19b",
      "owner": "0xf20aa4aad7642eeeb91398d04926ee4a2490b19b"
    },
    {
      "entityKey": "0x8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f6a7b",
      "threatType": "phishing_contract",
      "severityScore": 8,
      "confirmationCount": 8,
      "amountLostUSD": 57050,
      "reportedAt": 1716508800000,
      "aiSummary": "Phishing interface impersonating popular NFT mint page. Prompts user to sign a drain transaction.",
      "creator": "0xe0a205a8fde84a56a6fd7b0ea765109b867efcb9",
      "owner": "0xe0a205a8fde84a56a6fd7b0ea765109b867efcb9"
    }
  ]
}
05

Error Handling

The API returns standard HTTP status codes. Every client must handle client input issues (4xx) and temporary network or backend failures (5xx) cleanly.

error_400.json
{
  "status": "error",
  "code": "INVALID_ADDRESS",
  "message": "The provided address '0x1234' is not a valid EVM address. Address must be a 42-character hexadecimal string starting with '0x'."
}
06

Supported Chains

ClearShield is currently active on EVM compatible networks. Address queries must pass 42-character hexadecimal format validations.

NetworkChain IDStatus
Ethereum Mainnet1Active
Polygon PoS137Active
Arbitrum One42161Active
Optimism Mainnet10Active
Base8453Active
BNB Chain56Active

Non-EVM Networks (Solana, Bitcoin, Cosmos, etc.)

Non-EVM addresses are **not supported**. Sending non-EVM strings to the endpoint will result in an HTTP 400 validation error (`INVALID_ADDRESS`).

07

How Risk Scoring Works

ClearShield aggregates decentralized threat reports to evaluate trust levels. Our backend synthesizes risk profiles using five key parameters:

Severity Scoring

Each report specifies a severity weight (1–10). Level 9–10 corresponds to severe threat classes (e.g. direct private key extraction, immediate wallet drainers), while Level 1–3 represents spam transactions.

Confidence Calculation

Values (low, medium, high) reflect community backing. Metrics scale dynamically based on reporter reputation score, total independent reporting accounts, and signature confirms.

Cryptographic Confirmations

Peer wallets confirm existing threats by signing cryptographic EIP-712 messages on-chain. Each signature boosts confirmation counts and reinforces confidence.

Temporal Report Decay

Unconfirmed reports decay linearly over a 90-day window to prevent permanent blacklists of compromised contracts. High-confidence confirmed records decay only via formal dispute processes.

Anti-Spam & Sybil Protections

Submission requires a threshold of Braga utility tokens or validated DID credentials. Reports from linked accounts (sybil patterns) are automatically grouped to prevent attack weights.

08

False Positives & Limitations

Integrators must account for the following design constraints when deploying the security client in production environments:

Unknown ≠ Safe

An 'unknown' result simply means the target address has no recorded incident reports on-chain. Zero-day exploit contracts or freshly deployed drainers will return 'unknown'. This must not be treated as a positive validation.

Community Reporting Lag

Incidents rely on user alerts and block-explorer triggers. There can be a minor time delay between a new attack wave launching and reports registering on the Braga data layer.

Heuristic Risk Signal

ClearShield provides threat intelligence signals. We strongly recommend combining this endpoint with transaction simulation tools (e.g. Tenderly), static code checks, and domain registry verifications.

09

Operational Guidance

Latency & Timeouts

Average p50 latency is ~85ms, p99 is ~250ms. For wallet interactions (pre-sign checks), set a client timeout limit of 300ms–500ms. In case of timeout, fail open with a user warning.

Caching Guidelines & TTL

Cache 'critical' and 'high' results for 1 hour to optimize performance. Cache 'unknown' and 'low' reports for 5–15 minutes to guarantee fast capture of newly reported attack vectors.

Retry Policies

Do not retry 4xx responses (except 429). For 5xx errors or 429 rate limits, apply an exponential backoff policy: delay = min(100 * 2^attempt, 5000) + random_jitter_ms.

API Versioning

All requests target standard '/api/v1/' paths. Backward-compatible changes (e.g., adding optional fields to responses) will occur without path updates. Breaking changes will increment to '/api/v2/'.

10

Agent Integration

Autonomous AI agents executing transactions independently must implement safety guardrails. ClearShield should act as an inline transaction filter.

Agent Guardrail Instructions (System Prompt Snippet)

agent_rules.txt
Before initiating any transaction, approval, or message signature targeting address {ADDRESS}:
1. Call GET https://api.clearshield.network/api/v1/check?address={ADDRESS}
2. Parse response and strictly apply security policies:
   - If isFlagged is TRUE and riskLevel in ["critical", "high"] -> Immediately block execution, output: "Security Abort: Target address {ADDRESS} is flagged as a confirmed threat."
   - If isFlagged is TRUE and riskLevel is "medium" -> Warn user, request explicit verification, proceed only if approved.
   - If isFlagged is FALSE -> Allowed.
3. Fail safe policy: if the request times out or yields a 5xx error, alert the user and prompt for manual review before signing.

Example Guardrail Logic (TypeScript)

agentSafety.ts
import { checkAddress } from "./clearshield";

interface TransactionResult {
  success: boolean;
  reason?: string;
  txHash?: string;
}

export async function executeAgentTransaction(
  targetAddress: string,
  apiKey: string
): Promise<TransactionResult> {
  try {
    // Standard fail-safe: set a strict timeout of 500ms
    const checkPromise = checkAddress(targetAddress, apiKey);
    const timeoutPromise = new Promise<never>((_, reject) => 
      setTimeout(() => reject(new Error("Timeout")), 500)
    );

    const checkResult = await Promise.race([checkPromise, timeoutPromise]);

    if (checkResult.isFlagged && ["critical", "high"].includes(checkResult.riskLevel)) {
      return {
        success: false,
        reason: `[Security Abort] Address ${targetAddress} is flagged as ${checkResult.riskLevel.toUpperCase()}. Verdict: ${checkResult.verdict}`
      };
    }
    
    // Proceed with safe transaction
    return { success: true, txHash: "0x..." };
  } catch (error) {
    // Fail closed or open based on agent policy. Recommended: Fail closed or request manual fallback.
    console.error("ClearShield security check failed:", error);
    return { success: false, reason: "Security service error. Transaction aborted to prevent unsafe state." };
  }
}
11

Real-world Wallet & Client UI Integration

Integrating ClearShield into wallets or client applications requires careful UX design to balance security alerts and seamless interactions.

Pre-Transaction Checking

Query the endpoint as soon as a user enters a destination address or connects to an external dApp, rather than waiting for the signature confirmation screen.

Token Approval Protection

Explicitly query the approved spender address on ERC-20 `approve` and `setApprovalForAll` calls to safeguard user tokens from malicious drainers.

UI Warning Tiers

Use red block screens for critical/high levels, requiring user passphrase confirmation. For medium/low, display subtle dismissible yellow banner alerts.

12

Threat Categories

ClearShield reports index threats under seven unique classifications. Query responses contain the dominantThreatType matching these tags:

Approval Drainerapproval_drainer

Contracts that request broad ERC-20 approvals to siphon tokens at a later time.

Phishing Contractphishing_contract

Malicious contracts mimicking legitimate protocols to capture assets or sign claims.

Rug Pullrug_pull

Token contracts or staking pools where deployers hold backdoors to extract accumulated liquidity.

Honeypothoneypot

Token contracts designed to prevent transfers or selling, locking user capitals permanently.

Wallet Drainerwallet_drainer

Addresses deployed exclusively to execute malicious multi-asset draining signatures.

Fake Tokenfake_token

Impersonator ERC-20 contracts mimicking major assets (e.g. fake USDC, USDT, WETH).

Otherother

Anomalous patterns that violate protocol security but do not fit specific standard classes.

13

Risk Severity Tiers

🔴
critical

Multiple confirmed reports, severity score 9–10, validated asset loss. Integrators must block transactions automatically.

🟠
high

Multiple reports or severity 6–8, confirmed by separate accounts. Require strong user override warning before interaction.

🟡
medium

1–3 reports, moderate severity 4–6, limited confirmation. Advise caution; notify user of potential risks.

🟢
low

Single report of low severity 1–3, unconfirmed. Informational alert only; interaction remains unlocked.

⚪
unknown

No reports found in the community registry. NOTE: This does not mean verified safe; it is simply unreported.

14

Authentication

API keys authenticate client integrations. Pass keys via one of two supported header formats:

authentication
# Option 1: x-api-key header
curl "https://api.clearshield.network/api/v1/check?address=0xbc8ad786e6de38c4c79893fb25db56f9a0de5b94" \
  -H "x-api-key: cs_live_7f8a9b0c1d2e3f4a5b6c7d8e9f"

# Option 2: Authorization Bearer header
curl "https://api.clearshield.network/api/v1/check?address=0xbc8ad786e6de38c4c79893fb25db56f9a0de5b94" \
  -H "Authorization: Bearer cs_live_7f8a9b0c1d2e3f4a5b6c7d8e9f"

Server-side Environment Configuration

.env.local
# API Key configuration (comma-separated list for validation)
CLEARSHIELD_API_KEYS=cs_live_7f8a9b0c1d2e3f4a5b6c7d8e9f,cs_live_1a2b3c4d5e6f7g8h9i0j

# Rate limiting windows and thresholds
RATE_LIMIT_WINDOW_MS=60000
RATE_LIMIT_MAX_ANONYMOUS=10
RATE_LIMIT_MAX_API_KEY=120
15

Rate Limits

Anonymous Tier

10 / MIN

Rate-limited by client IP address. Recommended only for development testing.

Standard API Key Tier

120 / MIN

Pass via validation headers. Contact support to request enterprise tier increases.

Rate Limit Headers

X-RateLimit-LimitMax requests allowed in the current rate limit window
X-RateLimit-RemainingRequests remaining in the current rate limit window
X-RateLimit-ResetUnix timestamp (seconds) indicating when the current window resets
X-RateLimit-TierAssigned tier: anonymous | api_key
Retry-AfterSeconds to wait (returned only on HTTP 429 response)
16

Cryptographic Backend

ClearShield threat data is permanently recorded on the **Arkiv Braga testnet** data layer. Each threat incident and corroboration is cryptographically signed by the reporter, ensuring open audit trails.

Project Identifier

CLEARSHIELD_V1

Supported Entities

threat_report, threat_confirmation

Default Retention TTL

90 days (for unconfirmed records)

Validation Network

Arkiv Braga Testnet

Ready to integrate?