# Get Agent Count
Source: https://docs.credprotocol.com/api-reference/agents/agent-count
GET /api/v2/agents/count
Get the total number of agents registered in the ERC-8004 Identity Registry
## Overview
Returns the total number of AI agents minted in the [ERC-8004](https://eips.ethereum.org/EIPS/eip-8004) Identity Registry on Base. This is useful for understanding the size of the registry and for paginating through the full agent list.
This is a free endpoint (0 Cred Units). It reads directly from the on-chain Identity Registry contract on Base.
## Authentication
| Method | Header | Cost |
| - | - | - |
| API Token | `Authorization: Bearer YOUR_API_KEY` | 0 Cred Units |
| x402 Payment | `X-PAYMENT: ` | Free |
## Response
Total number of agents currently registered in the Identity Registry
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/agents/count" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const response = await fetch('https://api.credprotocol.com/api/v2/agents/count', {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const data = await response.json();
console.log(`Total agents: ${data.total}`);
```
```python Python theme={null}
import requests
response = requests.get(
'https://api.credprotocol.com/api/v2/agents/count',
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
data = response.json()
print(f"Total agents: {data['total']}")
```
```json 200 theme={null}
{
"total": 42
}
```
```json 502 theme={null}
{
"detail": "Failed to read from Identity Registry contract"
}
```
## Performance
* **Response Time**: Typically under 1 second
* **Data Source**: On-chain `totalSupply()` call to the Identity Registry on Base (chain 8453)
# Feedback JSON
Source: https://docs.credprotocol.com/api-reference/agents/feedback-json
GET /api/v2/agents/{agent_id}/reputation/feedback/{submission_id}
Retrieve the off-chain feedback JSON document for a submission
## Overview
Serves the [ERC-8004](https://eips.ethereum.org/EIPS/eip-8004) off-chain feedback JSON document for a completed reputation submission. This URL is stored on-chain as the `endpoint` parameter in `giveFeedback`, allowing anyone to verify the full feedback details.
This is a **public endpoint** — no authentication required. Responses are cached for 24 hours.
## Path Parameters
ERC-8004 agent ID. Must be >= 1.
Submission UUID
## Response
Returns the raw ERC-8004 feedback JSON document.
CAIP-2 Identity Registry address
Agent ID in the Identity Registry
CAIP-2 address of the feedback submitter (Cred Protocol's wallet)
ISO 8601 timestamp of when the feedback was created
Feedback value (e.g., credit score)
Decimal places for the value
Feedback metric type (e.g., `creditScore`)
Provider identifier (`credprotocol`)
URL to this feedback JSON endpoint
Cred-specific scoring context and details
## Response Headers
| Header | Description |
| - | - |
| `X-Feedback-Hash` | KECCAK-256 hash of the feedback JSON (matches on-chain `feedbackHash`) |
| `X-Feedback-URI` | IPFS URI of the feedback document |
| `Cache-Control` | `public, max-age=86400` (24 hour cache) |
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/agents/18/reputation/feedback/550e8400-e29b-41d4-a716-446655440000"
```
```javascript JavaScript theme={null}
const agentId = 18;
const submissionId = '550e8400-e29b-41d4-a716-446655440000';
const response = await fetch(
`https://api.credprotocol.com/api/v2/agents/${agentId}/reputation/feedback/${submissionId}`
);
const feedback = await response.json();
console.log(`Score: ${feedback.value} (${feedback.tag1})`);
console.log(`Hash: ${response.headers.get('X-Feedback-Hash')}`);
```
```python Python theme={null}
import requests
agent_id = 18
submission_id = '550e8400-e29b-41d4-a716-446655440000'
response = requests.get(
f'https://api.credprotocol.com/api/v2/agents/{agent_id}/reputation/feedback/{submission_id}'
)
feedback = response.json()
print(f"Score: {feedback['value']} ({feedback['tag1']})")
print(f"Hash: {response.headers.get('X-Feedback-Hash')}")
```
```json 200 theme={null}
{
"agentRegistry": "eip155:8453:0x8004A169FB4a3325136EB29fA0ceB6D2e539a432",
"agentId": 18,
"clientAddress": "eip155:8453:0x1234567890abcdef1234567890abcdef12345678",
"createdAt": "2026-02-27T15:30:00Z",
"value": 782,
"valueDecimals": 0,
"tag1": "creditScore",
"tag2": "credprotocol",
"endpoint": "https://api.credprotocol.com/api/v2/agents/18/reputation/feedback/550e8400-e29b-41d4-a716-446655440000",
"context": {
"model_version": "andromeda_1.1",
"address_scored": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"score_range": "good"
}
}
```
```json 404 theme={null}
{
"detail": "Feedback not found"
}
```
# Get Agent Info
Source: https://docs.credprotocol.com/api-reference/agents/get-agent
GET /api/v2/agents/{agent_id}
Check if an agent exists and get its owner address
## Overview
Returns whether an agent exists in the [ERC-8004](https://eips.ethereum.org/EIPS/eip-8004) Identity Registry on Base, along with its owner address. Use this to validate an agent ID before submitting reputation feedback.
This is a free endpoint (0 Cred Units). It reads directly from the on-chain Identity Registry contract on Base.
## Authentication
| Method | Header | Cost |
| - | - | - |
| API Token | `Authorization: Bearer YOUR_API_KEY` | 0 Cred Units |
| x402 Payment | `X-PAYMENT: ` | Free |
## Path Parameters
ERC-8004 agent ID (ERC-721 token ID in the Identity Registry). Must be >= 1.
## Response
The ERC-8004 agent ID
Ethereum address of the agent's owner (checksummed)
Agent registration metadata from tokenURI (null if unavailable)
Agent name from registration metadata
Agent description from registration metadata
Agent image URI from registration metadata
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/agents/1" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const agentId = 1;
const response = await fetch(`https://api.credprotocol.com/api/v2/agents/${agentId}`, {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const agent = await response.json();
console.log(`Agent ${agent.agent_id} owned by ${agent.owner}`);
```
```python Python theme={null}
import requests
agent_id = 1
response = requests.get(
f'https://api.credprotocol.com/api/v2/agents/{agent_id}',
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
agent = response.json()
print(f"Agent {agent['agent_id']} owned by {agent['owner']}")
```
```json 200 theme={null}
{
"agent_id": 1,
"owner": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
"metadata": {
"name": "Example Agent",
"description": "An example AI agent registered on-chain",
"image": "ipfs://QmExample123"
}
}
```
```json 404 theme={null}
{
"detail": "Agent 999 does not exist in the Identity Registry"
}
```
```json 422 theme={null}
{
"detail": [
{
"type": "greater_than_equal",
"loc": ["path", "agent_id"],
"msg": "Input should be greater than or equal to 1"
}
]
}
```
## Performance
* **Response Time**: Typically under 1 second
* **Data Source**: On-chain `ownerOf()` call to the Identity Registry on Base (chain 8453)
# List Agents
Source: https://docs.credprotocol.com/api-reference/agents/list-agents
GET /api/v2/agents
List registered agents with their owner addresses
## Overview
Returns a paginated list of agents from the [ERC-8004](https://eips.ethereum.org/EIPS/eip-8004) Identity Registry on Base, including each agent's owner address. Use this to discover valid agent IDs for submitting reputation feedback.
This is a free endpoint (0 Cred Units). It reads directly from the on-chain Identity Registry contract on Base.
## Authentication
| Method | Header | Cost |
| - | - | - |
| API Token | `Authorization: Bearer YOUR_API_KEY` | 0 Cred Units |
| x402 Payment | `X-PAYMENT: ` | Free |
## Query Parameters
Page number (must be >= 1)
Number of agents per page (1-100)
## Response
Array of agent objects on this page
The ERC-8004 agent ID (ERC-721 token ID)
Ethereum address of the agent's owner (checksummed)
Agent registration metadata from tokenURI (null if unavailable)
Agent name from registration metadata
Agent description from registration metadata
Agent image URI from registration metadata
Total number of agents in the Identity Registry
Current page number
Number of agents per page
Agent IDs are 1-indexed ERC-721 token IDs. Burned or nonexistent tokens are automatically skipped, so a page may return fewer agents than the limit.
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/agents?page=1&limit=10" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const response = await fetch('https://api.credprotocol.com/api/v2/agents?page=1&limit=10', {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const data = await response.json();
console.log(`Showing ${data.agents.length} of ${data.total} agents`);
data.agents.forEach(agent => {
console.log(`Agent #${agent.agent_id} — owner: ${agent.owner}`);
});
```
```python Python theme={null}
import requests
response = requests.get(
'https://api.credprotocol.com/api/v2/agents',
params={'page': 1, 'limit': 10},
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
data = response.json()
print(f"Showing {len(data['agents'])} of {data['total']} agents")
for agent in data['agents']:
print(f"Agent #{agent['agent_id']} — owner: {agent['owner']}")
```
```json 200 theme={null}
{
"agents": [
{
"agent_id": 1,
"owner": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
"metadata": {
"name": "DeFi Score Agent",
"description": "Credit scoring for DeFi protocols",
"image": "ipfs://QmExample1"
}
},
{
"agent_id": 2,
"owner": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"metadata": {
"name": "Sybil Detector",
"description": "Sybil detection and identity verification",
"image": "ipfs://QmExample2"
}
},
{
"agent_id": 3,
"owner": "0x1234567890abcdef1234567890abcdef12345678",
"metadata": null
}
],
"total": 42,
"page": 1,
"limit": 10
}
```
```json 400 theme={null}
{
"detail": "limit must be between 1 and 100"
}
```
```json 502 theme={null}
{
"detail": "Failed to read from Identity Registry contract"
}
```
## Use Cases
Browse all registered agents to find valid IDs for reputation feedback submission. Useful for building dashboards or agent directories.
Use `page` and `limit` to iterate through the full registry. The `total` field tells you how many pages exist (`total_pages = ceil(total / limit)`).
## Performance
* **Response Time**: Typically 1-3 seconds depending on page size
* **Data Source**: On-chain `ownerOf()` calls to the Identity Registry on Base (chain 8453)
* **Maximum Page Size**: 100 agents per request
# Reputation Summary
Source: https://docs.credprotocol.com/api-reference/agents/reputation-summary
GET /api/v2/agents/{agent_id}/reputation/summary
Read on-chain aggregated reputation summary for an agent
## Overview
Reads the aggregated feedback summary from the [ERC-8004](https://eips.ethereum.org/EIPS/eip-8004) Reputation Registry on Base. Returns the count and average of all Cred Protocol feedback entries for the specified agent, broken down by tag.
This is a view call (no gas cost) that reads directly from the on-chain Reputation Registry.
## Authentication
| Method | Header | Cost |
| - | - | - |
| API Token | `Authorization: Bearer YOUR_API_KEY` | 1 Cred Unit |
| x402 Payment | `X-PAYMENT: ` | \$0.01 USDC |
## Path Parameters
ERC-8004 agent ID. Must be >= 1.
## Response
The ERC-8004 agent ID
Summary per feedback tag (only includes tags with at least one entry)
Feedback metric type (e.g., `creditScore`, `sybilRisk`, `identityCount`)
Provider identifier (always `credprotocol` for Cred submissions)
Number of feedback entries for this tag
Aggregated value (sum or average depending on the contract implementation)
Decimal places for the summary value
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/agents/18/reputation/summary" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const agentId = 18;
const response = await fetch(`https://api.credprotocol.com/api/v2/agents/${agentId}/reputation/summary`, {
headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
});
const data = await response.json();
data.summaries.forEach(s => {
console.log(`${s.tag1}: ${s.summary_value} (${s.count} entries)`);
});
```
```python Python theme={null}
import requests
agent_id = 18
response = requests.get(
f'https://api.credprotocol.com/api/v2/agents/{agent_id}/reputation/summary',
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
data = response.json()
for s in data['summaries']:
print(f"{s['tag1']}: {s['summary_value']} ({s['count']} entries)")
```
```json 200 theme={null}
{
"agent_id": 18,
"summaries": [
{
"tag1": "creditScore",
"tag2": "credprotocol",
"count": 5,
"summary_value": 745.0,
"summary_value_decimals": 0
},
{
"tag1": "sybilRisk",
"tag2": "credprotocol",
"count": 5,
"summary_value": 15.0,
"summary_value_decimals": 0
},
{
"tag1": "identityCount",
"tag2": "credprotocol",
"count": 5,
"summary_value": 3.0,
"summary_value_decimals": 0
}
]
}
```
```json 404 theme={null}
{
"detail": "Agent 999 does not exist in the Identity Registry"
}
```
## Performance
* **Response Time**: Typically 1-3 seconds (multiple on-chain view calls)
* **Data Source**: On-chain `getSummary()` calls to the Reputation Registry on Base (chain 8453)
# Search Agents
Source: https://docs.credprotocol.com/api-reference/agents/search-agents
GET /api/v2/agents/search
Search agents by name or description
## Overview
Search across all registered agents in the [ERC-8004](https://eips.ethereum.org/EIPS/eip-8004) Identity Registry by name or description. Returns paginated results with agent metadata.
The search uses a pre-built Redis index that is refreshed every 30 minutes, making queries instant even across 20,000+ agents. Matching is case-insensitive substring search on the agent's name and description fields.
This is a free endpoint (0 Cred Units).
## Authentication
| Method | Header | Cost |
| - | - | - |
| API Token | `Authorization: Bearer YOUR_API_KEY` | 0 Cred Units |
| x402 Payment | `X-PAYMENT: ` | Free |
## Query Parameters
Search query (matches against agent name or description). Minimum 1 character.
Page number (must be >= 1)
Number of agents per page (1-100)
## Response
Array of matching agent objects on this page
The ERC-8004 agent ID (ERC-721 token ID)
Ethereum address of the agent's owner (checksummed)
Agent registration metadata from tokenURI (null if unavailable)
Agent name from registration metadata
Agent description from registration metadata
Agent image URI from registration metadata
Total number of agents matching the query
The search query that was used
Current page number
Number of agents per page
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/agents/search?q=cred&page=1&limit=10" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const query = 'cred';
const response = await fetch(`https://api.credprotocol.com/api/v2/agents/search?q=${query}&page=1&limit=10`, {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const data = await response.json();
console.log(`Found ${data.total_results} agents matching "${data.query}"`);
data.agents.forEach(agent => {
console.log(`Agent #${agent.agent_id} — ${agent.metadata?.name} (owner: ${agent.owner})`);
});
```
```python Python theme={null}
import requests
response = requests.get(
'https://api.credprotocol.com/api/v2/agents/search',
params={'q': 'cred', 'page': 1, 'limit': 10},
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
data = response.json()
print(f"Found {data['total_results']} agents matching \"{data['query']}\"")
for agent in data['agents']:
name = agent['metadata']['name'] if agent.get('metadata') else 'Unknown'
print(f"Agent #{agent['agent_id']} — {name} (owner: {agent['owner']})")
```
```json 200 theme={null}
{
"agents": [
{
"agent_id": 42,
"owner": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
"metadata": {
"name": "Cred Score Agent",
"description": "On-chain credit scoring for DeFi protocols",
"image": "ipfs://QmExample123"
}
},
{
"agent_id": 128,
"owner": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"metadata": {
"name": "CredCheck",
"description": "Automated credential verification",
"image": "https://example.com/agent.png"
}
}
],
"total_results": 2,
"query": "cred",
"page": 1,
"limit": 10
}
```
```json 400 theme={null}
{
"detail": "page must be >= 1"
}
```
```json 422 theme={null}
{
"detail": [
{
"type": "missing",
"loc": ["query", "q"],
"msg": "Field required"
}
]
}
```
```json 502 theme={null}
{
"detail": "Failed to search agents"
}
```
## Performance
* **Response Time**: Typically under 100ms (reads from a pre-built Redis index)
* **Index Freshness**: Updated every 30 minutes by a background task
* **Data Source**: Agent metadata from on-chain `tokenURI()` calls, cached in Redis
# Submission Status
Source: https://docs.credprotocol.com/api-reference/agents/submission-status
GET /api/v2/agents/{agent_id}/reputation/status/{submission_id}
Check the status of a reputation feedback submission
## Overview
Poll this endpoint to track the progress of an on-chain reputation submission. Returns the current status, computed scores (once available), and transaction details after confirmation.
This is a free endpoint (0 Cred Units). Poll every 5–10 seconds until the status is `confirmed` or `failed`.
## Authentication
| Method | Header | Cost |
| - | - | - |
| API Token | `Authorization: Bearer YOUR_API_KEY` | 0 Cred Units |
| x402 Payment | `X-PAYMENT: ` | Free |
## Path Parameters
ERC-8004 agent ID. Must be >= 1.
Submission UUID returned by the [submit endpoint](/api-reference/agents/submit-feedback)
## Response
UUID tracking this submission
The ERC-8004 agent ID
Current status: `pending`, `scoring`, `uploading`, `submitting`, `confirmed`, or `failed`
Computed scores (available after the `scoring` phase)
Andromeda 1.0 credit score (300–1000)
Sybil risk score (0–100)
Number of verified identity attestations
On-chain transaction details per tag (available after confirmation)
Feedback tag (e.g., `creditScore`)
Transaction hash on Base
Block number of confirmation
Gas used by the transaction
IPFS URI of the off-chain feedback JSON
Error message if status is `failed`
ISO 8601 timestamp when the submission was created
ISO 8601 timestamp when the submission was last updated
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/agents/18/reputation/status/550e8400-e29b-41d4-a716-446655440000" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const agentId = 18;
const submissionId = '550e8400-e29b-41d4-a716-446655440000';
const response = await fetch(
`https://api.credprotocol.com/api/v2/agents/${agentId}/reputation/status/${submissionId}`,
{ headers: { 'Authorization': 'Bearer YOUR_API_KEY' } }
);
const data = await response.json();
console.log(`Status: ${data.status}`);
if (data.scores) {
console.log(`Credit Score: ${data.scores.credit_score}`);
}
```
```python Python theme={null}
import requests
agent_id = 18
submission_id = '550e8400-e29b-41d4-a716-446655440000'
response = requests.get(
f'https://api.credprotocol.com/api/v2/agents/{agent_id}/reputation/status/{submission_id}',
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
data = response.json()
print(f"Status: {data['status']}")
if data.get('scores'):
print(f"Credit Score: {data['scores']['credit_score']}")
```
```json 200 theme={null}
{
"submission_id": "550e8400-e29b-41d4-a716-446655440000",
"agent_id": 18,
"status": "confirmed",
"scores": {
"credit_score": 782,
"sybil_score": 12,
"identity_count": 3
},
"transactions": [
{
"tag1": "creditScore",
"transaction_hash": "0xabc123...",
"block_number": 12345678,
"gas_used": 85000
},
{
"tag1": "sybilRisk",
"transaction_hash": "0xdef456...",
"block_number": 12345679,
"gas_used": 82000
}
],
"feedback_uri": "ipfs://QmXyz...",
"error": null,
"created_at": "2026-02-27T15:30:00Z",
"updated_at": "2026-02-27T15:30:45Z"
}
```
```json 404 theme={null}
{
"detail": "Submission not found"
}
```
# Submit Reputation Feedback
Source: https://docs.credprotocol.com/api-reference/agents/submit-feedback
POST /api/v2/agents/{agent_id}/reputation
Submit on-chain reputation feedback for an AI agent
## Overview
Computes Cred Protocol credit score, sybil risk, and identity attestations for the given agent, then submits the results as on-chain feedback to the [ERC-8004](https://eips.ethereum.org/EIPS/eip-8004) Reputation Registry on Base.
The submission happens **asynchronously** — this endpoint returns immediately with a tracking ID. Use the [status endpoint](/api-reference/agents/submission-status) to poll for completion.
This endpoint costs **10 Cred Units** per submission (covers computation + on-chain gas on Base).
## Authentication
| Method | Header | Cost |
| - | - | - |
| API Token | `Authorization: Bearer YOUR_API_KEY` | 10 Cred Units |
| x402 Payment | `X-PAYMENT: ` | \$0.10 USDC |
## Path Parameters
ERC-8004 agent ID from the Identity Registry. Must be >= 1.
## Request Body
Ethereum address to score for this agent (e.g., `0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045`)
Which feedback types to submit. Defaults to all three if omitted.
Options: `creditScore`, `sybilRisk`, `identityCount`
## Feedback Tags
| Tag | Description | Value Range |
| - | - | - |
| `creditScore` | Andromeda 1.0 credit score | 300–1000 |
| `sybilRisk` | Sybil detection risk score | 0 (human) – 100 (bot) |
| `identityCount` | Number of verified identity attestations | 0+ |
## Response
Returns HTTP **202 Accepted** with a tracking ID.
UUID tracking this submission
The ERC-8004 agent ID
Initial status (always `pending`)
Estimated time to on-chain confirmation (typically \~45 seconds)
Relative URL to poll for submission status
Feedback types being submitted
```bash cURL theme={null}
curl -X POST "https://api.credprotocol.com/api/v2/agents/18/reputation" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"}'
```
```javascript JavaScript theme={null}
const response = await fetch('https://api.credprotocol.com/api/v2/agents/18/reputation', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
address: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
})
});
const data = await response.json();
console.log(`Submission ${data.submission_id} — status: ${data.status}`);
console.log(`Poll: ${data.status_url}`);
```
```python Python theme={null}
import requests
response = requests.post(
'https://api.credprotocol.com/api/v2/agents/18/reputation',
headers={'Authorization': 'Bearer YOUR_API_KEY'},
json={'address': '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'}
)
data = response.json()
print(f"Submission {data['submission_id']} — status: {data['status']}")
print(f"Poll: {data['status_url']}")
```
```json 202 theme={null}
{
"submission_id": "550e8400-e29b-41d4-a716-446655440000",
"agent_id": 18,
"status": "pending",
"estimated_completion_seconds": 45,
"status_url": "/api/v2/agents/18/reputation/status/550e8400-e29b-41d4-a716-446655440000",
"tags": ["creditScore", "sybilRisk", "identityCount"]
}
```
```json 400 theme={null}
{
"detail": "address is required in the request body — the Ethereum address to score for this agent"
}
```
```json 404 theme={null}
{
"detail": "Agent 999 does not exist in the Identity Registry"
}
```
## Submission Lifecycle
The submission progresses through these statuses:
| Status | Description |
| - | - |
| `pending` | Submission received, queued for processing |
| `scoring` | Computing credit score, sybil risk, and identity attestations |
| `uploading` | Uploading feedback JSON to IPFS |
| `submitting` | Sending `giveFeedback` transaction to Base |
| `confirmed` | Transaction confirmed on-chain |
| `failed` | An error occurred (check the `error` field) |
## Performance
* **Response Time**: Immediate (HTTP 202)
* **End-to-End Completion**: \~45 seconds (scoring + IPFS upload + on-chain confirmation)
# Authentication
Source: https://docs.credprotocol.com/api-reference/authentication
How to authenticate with the Cred Protocol API
## Overview
The Cred Protocol API supports two authentication methods:
1. **Bearer Token Authentication** — Use an API key from your dashboard (recommended for most users)
2. **x402 Payment Authentication** — Pay per request with USDC, no account required
Most users should use Bearer token authentication. x402 payments support USDC on Base and SKALE networks. For details, see the [Authentication Guide](/guides/authentication#x402-payment-authentication).
## Getting Your API Key
Log in to your account at [app.credprotocol.com](https://app.credprotocol.com).
Go to the **Dashboard** and find the **API Keys** section.
Click **Create API Key** and give it a descriptive name (e.g., "Production", "Development").
Copy the API key immediately. For security reasons, you won't be able to view it again.
## Using Your API Key
Include your API key in the `Authorization` header using the Bearer scheme:
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/score/address/vitalik.eth" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const response = await fetch('https://api.credprotocol.com/api/v2/score/address/vitalik.eth', {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
```
```python Python theme={null}
import requests
response = requests.get(
'https://api.credprotocol.com/api/v2/score/address/vitalik.eth',
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
```
## Authentication Errors
### 401 Unauthorized
If your API key is missing, invalid, or expired, you'll receive a `401` error:
```json theme={null}
{
"detail": "Invalid or missing API key"
}
```
**Common causes:**
* Missing `Authorization` header
* Typo in the API key
* Using `API_KEY` instead of `Bearer API_KEY`
* Revoked or deleted API key
### 403 Forbidden
If your API key doesn't have permission for the requested resource:
```json theme={null}
{
"detail": "Insufficient permissions"
}
```
## Best Practices
API keys should be kept on your server. Never include them in frontend JavaScript, mobile apps, or public repositories.
```javascript theme={null}
// ❌ Bad - API key exposed in client-side code
fetch('https://api.credprotocol.com/api/v2/score/address/vitalik.eth', {
headers: { 'Authorization': 'Bearer sk_live_abc123' }
});
// ✅ Good - Call your own backend
fetch('/api/credit-score?address=vitalik.eth');
```
Store your API key in environment variables, not in code:
```bash theme={null}
# .env
CRED_API_KEY=your_api_key_here
```
```javascript theme={null}
// server.js
const apiKey = process.env.CRED_API_KEY;
```
Create separate API keys for development, staging, and production. This makes it easy to rotate keys without affecting other environments.
Periodically rotate your API keys, especially if you suspect they may have been compromised.
Regularly check your API usage in the Dashboard to detect unusual activity.
## Key Management
### Viewing Your Keys
You can view all your API keys (but not the key values) in the Dashboard. Each key shows:
* **Name**: The name you gave the key
* **Created**: When the key was created
* **Last Used**: The most recent API request using this key
* **Status**: Active or revoked
### Revoking a Key
If you need to revoke an API key:
1. Go to the **API Keys** section in your Dashboard
2. Find the key you want to revoke
3. Click **Revoke**
Revoking a key is immediate and permanent. Any applications using that key will stop working.
## Testing Authentication
Use this endpoint to verify your API key is working:
```bash theme={null}
curl -X GET "https://api.credprotocol.com/users/me" \
-H "Authorization: Bearer YOUR_API_KEY"
```
A successful response returns your user profile:
```json theme={null}
{
"id": "uuid",
"email": "you@example.com",
"is_active": true,
"is_verified": true
}
```
# Get Identity Attestations
Source: https://docs.credprotocol.com/api-reference/identity/get-identity
GET /api/v2/identity/address/{address}/attestations
Get identity attestations for an Ethereum address
## Overview
Returns identity attestations and verification data for the specified Ethereum address, including ENS domains, Gitcoin Passport, POAPs, and other identity signals.
Identity data is useful for verifying the legitimacy of an address and can boost credit scores.
## Authentication
This endpoint supports two authentication methods:
| Method | Header | Cost |
| - | - | - |
| API Token | `Authorization: Bearer YOUR_API_KEY` | 1 Cred Unit |
| x402 Payment | `X-PAYMENT: ` | \$0.01 USDC |
**x402 payments** allow instant, accountless access. Pay per request with USDC on Base — no signup required.
[Try it live →](https://credprotocol.com/try)
## Path Parameters
Ethereum address or ENS name (e.g., `vitalik.eth` or `0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17`)
## Response
The resolved Ethereum address (checksummed)
ENS (Ethereum Name Service) data
Primary ENS name set for this address
List of ENS names owned by this address
Gitcoin Passport verification data
Gitcoin Passport humanity score (0-100)
List of verified stamps/credentials
POAP (Proof of Attendance Protocol) data
Total number of POAPs owned
List of POAP events attended
Social profile links (if available)
Whether the response was served from cache
## Data Sources
| Source | Description |
| - | - |
| ENS | Ethereum Name Service domains |
| Gitcoin Passport | Sybil resistance and identity verification |
| POAPs | Proof of Attendance Protocol tokens |
| Lens Protocol | Decentralized social profile |
| Farcaster | Web3 social network profile |
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/identity/address/vitalik.eth/attestations" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const response = await fetch('https://api.credprotocol.com/api/v2/identity/address/vitalik.eth/attestations', {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const identity = await response.json();
console.log(`ENS: ${identity.ens.primary_name}`);
console.log(`Passport Score: ${identity.gitcoin_passport.score}`);
```
```python Python theme={null}
import requests
response = requests.get(
'https://api.credprotocol.com/api/v2/identity/address/vitalik.eth/attestations',
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
identity = response.json()
print(f"ENS: {identity['ens']['primary_name']}")
print(f"Passport Score: {identity['gitcoin_passport']['score']}")
```
```json 200 theme={null}
{
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"ens": {
"primary_name": "vitalik.eth",
"owned_names": ["vitalik.eth", "vbuterin.eth"],
"avatar": "https://metadata.ens.domains/mainnet/avatar/vitalik.eth"
},
"gitcoin_passport": {
"score": 42.5,
"stamps": [
{
"provider": "Google",
"verified": true
},
{
"provider": "Twitter",
"verified": true
},
{
"provider": "GitHub",
"verified": true
}
]
},
"poaps": {
"count": 156,
"events": [
{
"name": "ETHDenver 2024",
"date": "2024-02-29"
},
{
"name": "Devcon VI",
"date": "2022-10-11"
}
]
},
"social": {
"lens": "vitalik.lens",
"farcaster": "vitalik.eth"
},
"cached": false,
"timestamp": "2024-01-15T10:30:00Z"
}
```
```json 404 theme={null}
{
"detail": "No identity data found for this address"
}
```
## Use Cases
Use Gitcoin Passport scores to verify that an address represents a unique human, reducing the risk of sybil attacks in airdrops or governance.
Display ENS names and social profiles to provide a more human-readable identity for wallet addresses in your application.
Check POAP holdings to verify attendance at events or membership in communities.
## Performance
* **Response Time**: Typically 1-3 seconds
* **Caching**: Results cached for 5 minutes per address
# Sybil Detection
Source: https://docs.credprotocol.com/api-reference/identity/sybil-detection
GET /api/v2/identity/address/{address}/sybil
Analyze an Ethereum address for sybil behavior using on-chain transaction signals
## Overview
Analyzes an Ethereum address for sybil behavior by computing behavioral and relational signals from on-chain transaction data. Returns a composite sybil score (0-100, where higher = more likely sybil) along with individual indicator values.
This endpoint examines **Ethereum mainnet** transaction history to detect patterns consistent with sybil wallets -low diversity of counterparties, scripted timing, minimal gas expenditure, and lack of identity attestations.
## Authentication
This endpoint supports two authentication methods:
| Method | Header | Cost |
| - | - | - |
| API Token | `Authorization: Bearer YOUR_API_KEY` | 3 Cred Units |
| x402 Payment | `X-PAYMENT: ` | \$0.03 USDC |
**x402 payments** allow instant, accountless access. Pay per request with USDC on Base -no signup required.
[Try it live →](https://credprotocol.com/try)
## Path Parameters
Ethereum address or ENS name (e.g., `vitalik.eth` or `0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045`)
## Response
The resolved Ethereum address (checksummed)
ISO 8601 timestamp of when the analysis was computed
Composite sybil score from 0-100. Higher scores indicate a greater likelihood that the address is a sybil.
Human-readable risk classification derived from `sybil_score`. One of: `low`, `medium`, `high`, `critical`.
Individual signals used to compute the composite score.
Number of unique addresses this wallet has transacted with (normal transactions + ERC-20 token transfers), excluding itself.
Number of unique smart contracts called (transactions with non-empty input data) or created.
Total gas spent on outbound transactions, in ETH. Calculated as the sum of gasUsed times gasPrice for all transactions sent from this address.
The address that first funded this wallet (sender of the first inbound ETH transfer). Null if no inbound value transfers exist.
Shannon entropy of inter-transaction time deltas, normalized to 0-1. Higher values indicate more varied (human-like) timing patterns; lower values suggest scripted/automated behavior.
Number of verified identity attestations associated with this address (ENS name, Gitcoin Passport, POAPs, credentials, etc.).
Number of days since the wallet's first transaction on Ethereum mainnet.
Total number of normal transactions on Ethereum mainnet.
## Risk Levels
| Score | Risk Level | Interpretation |
| - | - | - |
| 0-24 | `low` | Unlikely sybil -diverse activity, verified identity |
| 25-49 | `medium` | Some suspicious characteristics |
| 50-74 | `high` | Likely sybil -limited activity or identity |
| 75-100 | `critical` | Very likely sybil -minimal on-chain presence |
## Scoring Methodology
The sybil score is computed by normalizing each indicator through a sigmoid function and combining them with the following weights:
| Indicator | Weight | Description |
| - | - | - |
| Identity Attestations | 25% | Verified on-chain/off-chain identity proofs |
| Unique Counterparties | 20% | Diversity of transaction partners |
| Unique Contracts | 15% | Breadth of smart contract interactions |
| Gas Spent | 10% | Economic commitment to the network |
| Time Entropy | 10% | Human-like transaction timing |
| Wallet Age | 10% | Longevity of the address |
| Transaction Count | 10% | Overall activity level |
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/identity/address/vitalik.eth/sybil" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://api.credprotocol.com/api/v2/identity/address/vitalik.eth/sybil',
{
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
const sybil = await response.json();
console.log(`Sybil Score: ${sybil.sybil_score}/100`);
console.log(`Risk Level: ${sybil.risk_level}`);
console.log(`Unique Counterparties: ${sybil.indicators.count_unique_counterparties}`);
```
```python Python theme={null}
import requests
response = requests.get(
"https://api.credprotocol.com/api/v2/identity/address/vitalik.eth/sybil",
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
sybil = response.json()
print(f"Sybil Score: {sybil['sybil_score']}/100")
print(f"Risk Level: {sybil['risk_level']}")
print(f"Unique Counterparties: {sybil['indicators']['count_unique_counterparties']}")
```
```json 200 theme={null}
{
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"timestamp": "2024-03-12T14:30:00+00:00",
"sybil_score": 12,
"risk_level": "low",
"indicators": {
"count_unique_counterparties": 142,
"count_unique_contracts_interacted": 37,
"total_gas_spent_eth": 0.847,
"funding_source_address": "0x71C7656EC7ab88b098defB751B7401B5f6d8976F",
"transaction_time_entropy": 0.82,
"identity_attestations": 3,
"wallet_age_days": 1095,
"transaction_count": 456
}
}
```
```json 400 theme={null}
{
"error": "Invalid Ethereum address",
"status_code": 400
}
```
```json 401 theme={null}
{
"detail": "Invalid or expired API token. Please create a new API token in /dashboard/console."
}
```
```json 402 theme={null}
{
"error": "authentication_required",
"message": "This endpoint requires authentication.",
"cred_units": 3,
"options": [
{ "method": "api_token", "cost": "3 Cred Units" },
{ "method": "x402_payment", "price": "$0.03", "currency": "USDC" }
]
}
```
## Use Cases
Screen recipient addresses before distributing tokens. Flag addresses with `high` or `critical` risk levels to prevent sybil farming.
Verify that voters in DAO governance represent unique humans by checking sybil scores before counting votes or distributing voting power.
Combine sybil detection with credit scoring to identify borrowers who may be operating multiple wallets to circumvent lending limits.
Gate access to communities, allowlists, or early access programs by requiring a sybil score below a threshold (e.g., score under 25).
## Performance
* **Response Time**: Typically 2-5 seconds (uncached), under 100ms (cached)
* **Caching**: Results cached for 30 minutes per address
* **Data Source**: Ethereum mainnet only (via Etherscan API)
# API Overview
Source: https://docs.credprotocol.com/api-reference/overview
Overview of the Cred Protocol API
## Base URL
All API requests should be made to:
```
https://api.credprotocol.com
```
## Authentication
All API endpoints require authentication using a Bearer token. Include your API key in the `Authorization` header:
```bash theme={null}
Authorization: Bearer YOUR_API_KEY
```
Get your API key from the [Dashboard](https://app.credprotocol.com/dashboard).
## API Endpoints
The Cred Protocol API is organized into the following categories:
### Score Endpoints
| Endpoint | Method | Description |
| - | - | - |
| `/api/v2/score/address/{address}` | GET | Get credit score for a single address |
| `/api/v2/score/` | GET | Get aggregated score for multiple addresses |
| `/api/v2/score/batch/` | GET | Get individual scores for multiple addresses |
| `/api/v2/score/address/{address}` | POST | Get enhanced score with off-chain data |
### Report Endpoints
| Endpoint | Method | Description |
| - | - | - |
| `/api/v2/report/address/{address}` | GET | Get comprehensive credit report |
| `/api/v2/report/address/{address}` | POST | Get enhanced report with off-chain data |
| `/api/v2/report/` | GET | Get aggregated report for multiple addresses |
| `/api/v2/report/address/{address}/summary` | GET | Get lightweight summary report |
| `/api/v2/report/address/{address}/chain/{chain_id}` | GET | Get chain-specific report |
| `/api/v2/report/address/{address}/total/usd` | GET | Get portfolio composition by chain |
| `/api/v2/report/address/{address}/total/usd/aggregate` | GET | Get total portfolio value |
### Identity Endpoints
| Endpoint | Method | Description |
| - | - | - |
| `/api/v2/identity/address/{address}/attestations` | GET | Get identity attestations |
### Sandbox Endpoints
All production endpoints have sandbox equivalents. See [Sandbox Overview](/api-reference/sandbox/overview) for the full list.
| Endpoint | Method | Description |
| - | - | - |
| `/api/v2/sandbox/score/address/{address}` | GET | Get mock credit score |
| `/api/v2/sandbox/report/address/{address}` | GET | Get mock credit report |
## Request Format
### Path Parameters
Some endpoints accept path parameters (e.g., `{address}`). These support:
* **Ethereum addresses**: `0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17`
* **ENS names**: `vitalik.eth`
### Query Parameters
Query parameters should be URL-encoded and appended to the URL:
```bash theme={null}
GET /api/v2/score/batch?addresses=0x123...,0x456...
```
## Response Format
All responses are returned in JSON format:
```json theme={null}
{
"address": "0x...",
"score": 847,
"decile": 7,
"range": "very_good",
"model_version": "andromeda_1.1",
"timestamp": "2024-01-15T10:30:00Z"
}
```
### Common Response Fields
| Field | Type | Description |
| - | - | - |
| `address` | string | The resolved Ethereum address |
| `score` | integer | Credit score between 300-1000 |
| `decile` | integer | Score decile (1-10) |
| `range` | string | Score range (low, fair, good, very\_good, excellent) |
| `model_version` | string | Scoring model version |
| `timestamp` | string | ISO 8601 timestamp of the response |
## Usage Limits
API usage is measured in Cred Units (CUs). Each endpoint consumes a specific number of CUs based on computational complexity.
| Plan | Cred Units/Month | Price |
| - | - | - |
| Free | 1,000 | \$0 |
| Pro | 50,000 | \$249/mo |
| Enterprise | Unlimited | Custom |
See the [Pricing FAQ](https://credprotocol.com/pricing#what-are-cred-units) for details on Cred Units.
When you exceed your monthly limit, you'll receive a `429 Too Many Requests` response. Upgrade your plan or wait for the next billing cycle to continue making requests.
## Cred Unit Costs
Every API request consumes Cred Units based on the complexity of the operation. Simple queries cost less, while comprehensive reports that aggregate data across multiple blockchains cost more.
### Cost Tiers
| Operation Type | Cost Range | Examples |
| - | - | - |
| **Basic Queries** | 1-2 CU | Credit scores, single-chain summaries, asset values |
| **Standard Reports** | 3-5 CU | Single-chain reports, cross-chain summaries, boosted scores |
| **Comprehensive Reports** | 7-10 CU | Full cross-chain reports, enhanced reports with off-chain data |
### What Affects Cost?
* **Scope**: Single-chain queries cost less than cross-chain aggregations
* **Detail Level**: Summaries cost less than full reports with balances, NFTs, and transaction history
* **Data Enrichment**: Reports enhanced with off-chain data require additional processing
### Example Usage
| Use Case | Typical Cost |
| - | - |
| Check a wallet's credit score | 1 CU |
| Get a quick portfolio summary | 3-5 CU |
| Full credit report for underwriting | 7-10 CU |
Use the [Sandbox environment](/api-reference/sandbox/overview) for unlimited free testing during development.
## Caching
Responses are cached for **5 minutes** per address to optimize performance.
To force a fresh calculation, wait for the cache to expire or contact support for cache invalidation.
## Error Handling
See the [Error Handling Guide](/guides/error-handling) for detailed information on handling API errors.
### Common Error Codes
| Code | Description |
| - | - |
| 400 | Bad Request - Invalid parameters |
| 401 | Unauthorized - Invalid or missing API key |
| 404 | Not Found - Address not found or invalid |
| 429 | Too Many Requests - Rate limit exceeded |
| 500 | Internal Server Error |
## SDKs & Libraries
Coming soon:
* JavaScript/TypeScript SDK
* Python SDK
* Go SDK
In the meantime, you can use any HTTP client to interact with the API.
# Aggregated Credit Report
Source: https://docs.credprotocol.com/api-reference/report/aggregated-report
GET /api/v2/report/
Get an aggregated credit report for multiple Ethereum addresses
## Overview
Generates a single aggregated credit report combining metrics from multiple Ethereum addresses. All numeric values are summed, attestations are merged, and transaction timestamps span the earliest to most recent across all wallets.
This endpoint is ideal for assessing the combined creditworthiness of multi-signature wallets, joint accounts, or organizational treasuries.
## Query Parameters
Comma-separated list of Ethereum addresses or ENS names (e.g., `address=0x123...,0x456...,vitalik.eth`)
## Response
Array of all successfully analyzed addresses
ISO 8601 timestamp when the report was generated
Earliest transaction across all addresses
Most recent transaction across all addresses
Aggregated summary metrics (summed across all addresses)
Combined total assets in USD
Combined total collateral in USD
Combined total debt in USD
Total transaction count across all addresses
Count of unique attestations across all addresses
Merged list of unique identity attestations
## Aggregation Method
| Metric Type | Aggregation |
| - | - |
| USD Values | Summed |
| Counts | Summed |
| Attestations | Merged (deduplicated) |
| First Transaction | Earliest timestamp |
| Last Transaction | Latest timestamp |
## Use Cases
* **Multi-signature Wallets**: Complete financial picture of all signers
* **Organization Assessment**: Combined view of treasury wallets
* **Joint Account Analysis**: Aggregate credit for shared holdings
* **Family Portfolios**: Combined net worth and credit metrics
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/report/?address=vitalik.eth,0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const addresses = ['vitalik.eth', '0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17'];
const response = await fetch(
`https://api.credprotocol.com/api/v2/report/?address=${addresses.join(',')}`,
{
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
const data = await response.json();
console.log(`Combined assets: $${data.report.summary.total_asset_usd}`);
```
```python Python theme={null}
import requests
addresses = ['vitalik.eth', '0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17']
response = requests.get(
'https://api.credprotocol.com/api/v2/report/',
params={'address': ','.join(addresses)},
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
data = response.json()
print(f"Combined assets: ${data['report']['summary']['total_asset_usd']}")
```
```json 200 theme={null}
{
"report": {
"address": [
"0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17"
],
"timestamp": "2024-01-15T10:30:00Z",
"first_transaction": {
"timestamp": 1438918251,
"block_number": 46147,
"chain_id": 1
},
"last_transaction": {
"timestamp": 1710255000,
"block_number": 19123456,
"chain_id": 1
},
"summary": {
"total_asset_usd": 250000.00,
"total_collateral_usd": 100000.00,
"total_debt_usd": 30000.00,
"count_transactions": 4820,
"count_transfers": 2460,
"count_balances": 48,
"count_identity_attestations": 6,
"list_identity_attestations": [
"ENS Name",
"Gitcoin Passport",
"POAP - ETHDenver 2024"
]
}
}
}
```
```json 400 theme={null}
{
"error": "No valid addresses provided",
"status_code": 400
}
```
## Performance
* **Response Time**: Typically 5-15 seconds (varies with address count)
* **Caching**: Individual address reports are cached for 5 minutes
* **Parallelization**: Reports are generated in parallel for optimal performance
# Chain Portfolio Value
Source: https://docs.credprotocol.com/api-reference/report/chain-portfolio
GET /api/v2/report/address/{address}/chain/{chain_id}/total/usd
Get the total USD portfolio value for a specific blockchain
## Overview
Returns the total USD value of assets held by an address on a specific blockchain network. This is the fastest way to check holdings on a single chain.
Same pricing and inclusion rules as the all-chains portfolio endpoints, but scoped to a single network.
## Path Parameters
Ethereum address or ENS name (e.g., `vitalik.eth` or `0x742d35Cc6634C0532925a3b844Bc454e4438f44e`)
The chain ID to fetch data from (e.g., `1` for Ethereum mainnet)
## Supported Chain IDs
| Network | Chain ID |
| - | - |
| Ethereum | 1 |
| Optimism | 10 |
| BNB Chain | 56 |
| Polygon | 137 |
| Base | 8453 |
| Celo | 42220 |
| Arbitrum | 42161 |
| Avalanche | 43114 |
| Scroll | 534352 |
| Linea | 59144 |
## Response
The resolved Ethereum address (checksummed)
ISO 8601 timestamp when the value was calculated
Array containing the single chain's data
The requested chain ID
Human-readable chain name
Total asset value on this chain in USD
## Included Assets
| Asset Type | Included |
| - | - |
| Native tokens | Yes |
| ERC-20 tokens | Yes |
| Stablecoins | Yes |
| LP tokens | Yes |
| Wrapped tokens | Yes |
| Collateral deposits | Yes |
| NFTs | No |
| Debt positions | No |
## Use Cases
* **Chain-Specific Monitoring**: Track holdings on a specific L2
* **Pre-Transaction Check**: Verify balance before bridging
* **Gas Planning**: Check native token balance for gas
* **Protocol Analysis**: Monitor holdings on specific chains
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/report/address/vitalik.eth/chain/1/total/usd" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const response = await fetch('https://api.credprotocol.com/api/v2/report/address/vitalik.eth/chain/1/total/usd', {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const data = await response.json();
const ethereumValue = data.chains[0].total_asset_usd;
console.log(`Ethereum holdings: $${ethereumValue.toLocaleString()}`);
```
```python Python theme={null}
import requests
response = requests.get(
'https://api.credprotocol.com/api/v2/report/address/vitalik.eth/chain/1/total/usd',
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
data = response.json()
ethereum_value = data['chains'][0]['total_asset_usd']
print(f"Ethereum holdings: ${ethereum_value:,.2f}")
```
```json 200 theme={null}
{
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"timestamp": "2024-01-15T10:30:00Z",
"chains": [
{
"chain_id": 1,
"chain_name": "Ethereum",
"total_asset_usd": 85000.50
}
]
}
```
```json 400 theme={null}
{
"error": "Unsupported chain: 999"
}
```
## Performance
* **Response Time**: \< 1 second
* **Caching**: Results cached for 5 minutes per address+chain combination
# Chain-Specific Report
Source: https://docs.credprotocol.com/api-reference/report/chain-report
GET /api/v2/report/address/{address}/chain/{chain_id}
Get a credit report for a specific blockchain network
## Overview
Returns a credit report for a single blockchain network, useful when you only need data from a specific chain.
Use this endpoint for faster responses when you don't need cross-chain data.
## Path Parameters
Ethereum address or ENS name (e.g., `vitalik.eth` or `0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17`)
The chain ID to fetch data from (e.g., `1` for Ethereum mainnet)
## Supported Chain IDs
| Network | Chain ID |
| - | - |
| Ethereum | 1 |
| Polygon | 137 |
| Arbitrum | 42161 |
| Optimism | 10 |
| Base | 8453 |
| Avalanche | 43114 |
| BNB Chain | 56 |
| Fantom | 250 |
| zkSync | 324 |
| Linea | 59144 |
## Response
The resolved Ethereum address (checksummed)
The chain ID for this report
Human-readable chain name
Asset holdings on this chain
DeFi positions on this chain
Transaction activity on this chain
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/report/address/vitalik.eth/chain/1" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const response = await fetch('https://api.credprotocol.com/api/v2/report/address/vitalik.eth/chain/1', {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const report = await response.json();
console.log(`Ethereum holdings: $${report.assets.total_value_usd}`);
```
```python Python theme={null}
import requests
response = requests.get(
'https://api.credprotocol.com/api/v2/report/address/vitalik.eth/chain/1',
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
report = response.json()
print(f"Ethereum holdings: ${report['assets']['total_value_usd']}")
```
```json 200 theme={null}
{
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"chain_id": 1,
"chain_name": "Ethereum",
"assets": {
"total_value_usd": 100000000,
"tokens": [
{
"symbol": "ETH",
"name": "Ethereum",
"balance": "50000.5",
"value_usd": 100000000
}
],
"nfts": [
{
"name": "CryptoPunk #1234",
"collection": "CryptoPunks"
}
]
},
"defi": {
"protocols": [
{
"name": "Aave",
"supplied": 1000000,
"borrowed": 0
}
],
"total_supplied": 1000000,
"total_borrowed": 0
},
"activity": {
"first_transaction": "2015-08-07T00:00:00Z",
"total_transactions": 12000
},
"cached": false,
"timestamp": "2024-01-15T10:30:00Z"
}
```
```json 400 theme={null}
{
"detail": "Invalid chain ID. See documentation for supported chains."
}
```
## Performance
* **Response Time**: Typically 1-3 seconds (faster than full report)
* **Caching**: Results cached for 5 minutes per address/chain combination
# Chain-Specific Summary
Source: https://docs.credprotocol.com/api-reference/report/chain-summary
GET /api/v2/report/address/{address}/chain/{chain_id}/summary
Get a lightweight summary report for a specific blockchain
## Overview
Returns a lightweight summary of key credit metrics for a single blockchain network, without detailed asset breakdowns. This is the fastest way to get chain-specific credit data.
Combines the speed of the summary endpoint with the focus of chain-specific analysis.
## Path Parameters
Ethereum address or ENS name (e.g., `vitalik.eth` or `0x742d35Cc6634C0532925a3b844Bc454e4438f44e`)
The chain ID to fetch data from (e.g., `1` for Ethereum mainnet)
## Supported Chain IDs
| Network | Chain ID |
| - | - |
| Ethereum | 1 |
| Optimism | 10 |
| BNB Chain | 56 |
| Polygon | 137 |
| Base | 8453 |
| Celo | 42220 |
| Arbitrum | 42161 |
| Avalanche | 43114 |
| Scroll | 534352 |
| Linea | 59144 |
## Response
The resolved Ethereum address (checksummed)
ISO 8601 timestamp when the report was generated
First transaction on this chain
Most recent transaction on this chain
Summary metrics for this chain only
## Use Cases
* **Chain Migration Analysis**: Quick assessment before moving assets
* **L2 Adoption Tracking**: Monitor activity on specific Layer 2s
* **Protocol-Specific Risk**: Assess exposure on a single network
* **Gas Optimization**: Check activity before transactions
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/report/address/vitalik.eth/chain/1/summary" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const response = await fetch('https://api.credprotocol.com/api/v2/report/address/vitalik.eth/chain/1/summary', {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const data = await response.json();
console.log(`Ethereum assets: $${data.report.summary.total_asset_usd}`);
```
```python Python theme={null}
import requests
response = requests.get(
'https://api.credprotocol.com/api/v2/report/address/vitalik.eth/chain/1/summary',
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
data = response.json()
print(f"Ethereum assets: ${data['report']['summary']['total_asset_usd']}")
```
```json 200 theme={null}
{
"report": {
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"timestamp": "2024-01-15T10:30:00Z",
"first_transaction": {
"timestamp": 1438918251,
"block_number": 46147,
"chain_id": 1
},
"last_transaction": {
"timestamp": 1710255000,
"block_number": 19123456,
"chain_id": 1
},
"summary": {
"total_asset_usd": 85000.00,
"total_collateral_usd": 40000.00,
"total_debt_usd": 10000.00,
"count_transactions": 1800,
"count_transfers": 900,
"count_balances": 15
}
}
}
```
```json 400 theme={null}
{
"error": "Unsupported chain: 999"
}
```
## Performance
* **Response Time**: \< 1 second
* **Caching**: Results cached for 5 minutes per address+chain combination
# Enhanced Credit Report
Source: https://docs.credprotocol.com/api-reference/report/enhanced-report
POST /api/v2/report/address/{address}
Get an enhanced credit report with off-chain data integration
## Overview
Generates a comprehensive credit report that combines on-chain blockchain data with additional off-chain metrics you provide. This allows for more accurate credit assessments by including verified external data sources like centralized exchange balances or traditional financial data.
Off-chain data is added to the on-chain totals, providing a complete financial picture across both DeFi and traditional finance.
## Path Parameters
Ethereum address or ENS name (e.g., `vitalik.eth` or `0x742d35Cc6634C0532925a3b844Bc454e4438f44e`)
## Request Body
Source name for the additional data (e.g., "Coinbase Account", "Bank of America", "Binance")
Total value of off-chain assets in USD
Total collateral value from off-chain sources in USD
Total debt/liabilities from off-chain sources in USD
Number of verified off-chain transactions
Number of verified off-chain transfers
## Response
The response follows the same structure as the standard credit report, with an additional `additional` field containing the off-chain data source information.
The complete credit report object
The resolved Ethereum address (checksummed)
Combined summary metrics (on-chain + off-chain totals)
Off-chain data source information
Name of the off-chain data source
The off-chain metrics that were added
Per-chain breakdown of on-chain data
## Use Cases
Include balances from centralized exchanges like Coinbase, Binance, or Kraken to show complete crypto holdings beyond on-chain wallets.
Incorporate verified bank account balances or traditional credit data for a hybrid DeFi/TradFi credit assessment.
Lenders can request users provide off-chain data for more accurate creditworthiness evaluation and better loan terms.
Show the full financial picture when users have assets across multiple platforms and chains.
```bash cURL theme={null}
curl -X POST "https://api.credprotocol.com/api/v2/report/address/vitalik.eth" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Coinbase Account",
"total_asset_usd": 75000,
"total_collateral_usd": 25000,
"count_transactions": 450
}'
```
```javascript JavaScript theme={null}
const response = await fetch('https://api.credprotocol.com/api/v2/report/address/vitalik.eth', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Coinbase Account',
total_asset_usd: 75000,
total_collateral_usd: 25000,
count_transactions: 450
})
});
const report = await response.json();
console.log(`Combined assets: $${report.report.summary.total_asset_usd}`);
```
```python Python theme={null}
import requests
response = requests.post(
'https://api.credprotocol.com/api/v2/report/address/vitalik.eth',
headers={'Authorization': 'Bearer YOUR_API_KEY'},
json={
'name': 'Coinbase Account',
'total_asset_usd': 75000,
'total_collateral_usd': 25000,
'count_transactions': 450
}
)
report = response.json()
print(f"Combined assets: ${report['report']['summary']['total_asset_usd']}")
```
```json 200 theme={null}
{
"report": {
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"timestamp": "2024-01-15T10:30:00Z",
"first_transaction": {
"timestamp": 1438918251,
"block_number": 46147,
"chain_id": 1
},
"summary": {
"total_asset_usd": 200000.50,
"total_collateral_usd": 75000.00,
"total_debt_usd": 15000.00,
"count_transactions": 2906,
"count_transfers": 1234
},
"additional": {
"source": {
"name": "Coinbase Account",
"data": {
"total_asset_usd": 75000,
"total_collateral_usd": 25000,
"count_transactions": 450
}
}
},
"chains": []
}
}
```
```json 400 theme={null}
{
"error": "Additional data must provide a 'name' field"
}
```
## Performance
* **Response Time**: Typically 4-12 seconds
* **Caching**: Not cached - recalculated on each request to include fresh off-chain data
* **Validation**: All numeric values must be non-negative
# Get Credit Report
Source: https://docs.credprotocol.com/api-reference/report/get-report
GET /api/v2/report/address/{address}
Get a comprehensive credit report for an Ethereum address
## Overview
Returns a comprehensive credit report including asset balances, NFT holdings, DeFi positions, and transaction history across multiple blockchain networks.
Reports aggregate data from 10+ supported networks and are cached for 5 minutes.
## Path Parameters
Ethereum address or ENS name (e.g., `vitalik.eth` or `0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17`)
## Response
The resolved Ethereum address (checksummed)
Credit score summary
Credit score between 300-1000
Score classification
Asset holdings across all networks
Total portfolio value in USD
List of token holdings
List of NFT holdings
DeFi positions and activity
Active DeFi protocol positions
Total value supplied to lending protocols
Total value borrowed from lending protocols
Transaction activity summary
Date of first transaction
Total number of transactions
Whether the response was served from cache
## Credit Events
The full report includes a `credit_events` section with the address's lending-protocol event history. See [Chains & Protocols](/chains-and-protocols) for coverage.
The least complete `coverage` of any pool. `complete` means every pool's history is complete and current.
Event counts across all covered pools: `supply`, `withdraw`, `borrow`, `repay`, `liquidation`
One entry per covered lending pool contract. Protocols with several markets on a chain (Compound) have one entry per market.
`aave_v2`, `aave_v3`, `compound_v3` or `compound_v2`
Market name for protocols with several markets per chain (for example `cUSDCv3`, `cDAI`); `null` for single-pool protocols
Whether this pool's repayments and liquidations count towards the score. `false` for a protocol still being validated: its events are shown but do not move the score.
Chain the pool is deployed on
How complete the event history is for this pool. See the table below.
The block the event history is complete through. `null` if the pool has not been read yet.
Event counts for this pool, by event type. A count is `null` for an event type that is not collected for the protocol (Compound V2 `supply` and `withdraw`), which is different from `0`.
Timestamp of the earliest event, or `null` if there are none
Timestamp of the most recent event, or `null` if there are none
`{"status": "not_applicable"}` with a reason. Defaults are not observable on overcollateralized protocols.
`{"status": "not_applicable"}` with a reason
Lending protocols whose event history is not yet available, so that a missing record is not read as a clean one
Whether these events contribute to the address's Cred Score
### Coverage
| Value | Meaning |
| - | - |
| `complete` | The event history is complete and current |
| `partial` | The history is complete through `synced_to_block` but not yet current |
| `pending` | The address is being read for the first time. Request the report again shortly. |
| `failed` | The pool could not be read. Counts for this pool are not available. |
The first report for an address with a long borrowing history may return `pending` while its events are read in the background, usually within a few seconds. Until `coverage` is `complete`, the counts, and any score that depends on them, may understate the address's history. Check `coverage` before relying on `count_repayments` or `count_liquidations`. An incomplete report is never cached for more than 30 seconds.
### Example
```json theme={null}
"credit_events": {
"coverage": "complete",
"feeds_score": true,
"totals": { "supply": 5, "withdraw": 0, "borrow": 7, "repay": 4, "liquidation": 0 },
"pools": [
{
"protocol": "aave_v3",
"chain_id": 1,
"market_address": "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2",
"market": null,
"feeds_score": true,
"coverage": "complete",
"synced_to_block": 26080712,
"counts": { "supply": 5, "withdraw": 0, "borrow": 7, "repay": 4, "liquidation": 0 },
"first_event_at": "2025-03-08T08:24:47+00:00",
"last_event_at": "2026-09-01T16:59:23+00:00"
},
{
"protocol": "compound_v3",
"chain_id": 1,
"market_address": "0xc3d688b66703497daa19211eedff47f25384cdc3",
"market": "cUSDCv3",
"feeds_score": false,
"coverage": "complete",
"synced_to_block": 26080712,
"counts": { "supply": 2, "withdraw": 1, "borrow": 3, "repay": 3, "liquidation": 0 },
"first_event_at": "2025-06-11T10:02:35+00:00",
"last_event_at": "2026-08-20T21:14:59+00:00"
},
{
"protocol": "compound_v2",
"chain_id": 1,
"market_address": "0x39aa39c021dfbae8fac545936693ac917d5e7563",
"market": "cUSDC",
"feeds_score": false,
"coverage": "complete",
"synced_to_block": 26080700,
"counts": { "supply": null, "withdraw": null, "borrow": 1, "repay": 1, "liquidation": 0 },
"first_event_at": "2021-02-03T14:40:11+00:00",
"last_event_at": "2021-05-19T07:12:44+00:00"
}
],
"defaults": { "status": "not_applicable", "reason": "..." },
"delinquencies": { "status": "not_applicable", "reason": "..." },
"not_covered": []
}
```
## Supported Networks
Reports aggregate data from the following networks:
| Network | Chain ID |
| - | - |
| Ethereum | 1 |
| Polygon | 137 |
| Arbitrum | 42161 |
| Optimism | 10 |
| Base | 8453 |
| Avalanche | 43114 |
| BNB Chain | 56 |
| Fantom | 250 |
| zkSync | 324 |
| Linea | 59144 |
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/report/address/vitalik.eth" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const response = await fetch('https://api.credprotocol.com/api/v2/report/address/vitalik.eth', {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const report = await response.json();
console.log(`Total Value: $${report.assets.total_value_usd}`);
```
```python Python theme={null}
import requests
response = requests.get(
'https://api.credprotocol.com/api/v2/report/address/vitalik.eth',
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
report = response.json()
print(f"Total Value: ${report['assets']['total_value_usd']}")
```
```json 200 theme={null}
{
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"score": {
"value": 847,
"classification": "Excellent"
},
"assets": {
"total_value_usd": 125000000.50,
"tokens": [
{
"symbol": "ETH",
"name": "Ethereum",
"balance": "50000.5",
"value_usd": 100000000,
"chain_id": 1
}
],
"nfts": [
{
"name": "CryptoPunk #1234",
"collection": "CryptoPunks",
"chain_id": 1
}
]
},
"defi": {
"protocols": [
{
"name": "Aave",
"supplied": 1000000,
"borrowed": 0,
"chain_id": 1
}
],
"total_supplied": 1000000,
"total_borrowed": 0
},
"activity": {
"first_transaction": "2015-08-07T00:00:00Z",
"total_transactions": 15420,
"active_chains": [1, 137, 42161]
},
"cached": false,
"timestamp": "2024-01-15T10:30:00Z"
}
```
## Performance
* **Response Time**: Typically 3-10 seconds depending on activity
* **Caching**: Results cached for 5 minutes per address
# Portfolio Composition
Source: https://docs.credprotocol.com/api-reference/report/portfolio-composition
GET /api/v2/report/address/{address}/total/usd
Get USD portfolio value breakdown by blockchain network
## Overview
Returns the portfolio composition showing the USD value of assets held by an address on each supported blockchain network. This endpoint is useful for understanding cross-chain asset distribution and portfolio diversification.
This endpoint provides a breakdown of value by chain, while the `/total/usd/aggregate` endpoint provides a single combined total.
## Path Parameters
Ethereum address or ENS name (e.g., `vitalik.eth` or `0x742d35Cc6634C0532925a3b844Bc454e4438f44e`)
## Response
The resolved Ethereum address (checksummed)
ISO 8601 timestamp when values were calculated
Combined total portfolio value across all chains
Per-chain breakdown of asset values
Blockchain network ID
Human-readable chain name
Total asset value on this chain in USD
## Included Assets
| Asset Type | Included |
| - | - |
| Native tokens (ETH, MATIC, etc.) | Yes |
| ERC-20 tokens | Yes |
| Stablecoins (USDC, USDT, DAI) | Yes |
| LP tokens (Uniswap, Curve) | Yes |
| Wrapped tokens (WETH, WBTC) | Yes |
| Collateral deposits | Yes |
| NFTs | No |
| Unclaimed rewards | No |
| Pending transactions | No |
| Debt positions | No (separate field) |
## Pricing Sources
* **Primary**: Chainlink on-chain oracles (real-time)
* **Fallback**: CoinGecko API (for tokens without oracle coverage)
* **Update Frequency**: Prices refresh every 60 seconds
* **Denomination**: All values in USD
## Use Cases
* **Portfolio Diversification**: Visualize asset distribution across chains
* **Chain-Level Tracking**: Monitor holdings on specific networks
* **Rebalancing Decisions**: Identify over/under-weighted chains
* **Cross-Chain Analytics**: Compare activity across L1s and L2s
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/report/address/vitalik.eth/total/usd" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const response = await fetch('https://api.credprotocol.com/api/v2/report/address/vitalik.eth/total/usd', {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const data = await response.json();
console.log(`Total Portfolio: $${data.total_asset_usd}`);
data.chains.forEach(chain => {
console.log(`${chain.chain_name}: $${chain.total_asset_usd}`);
});
```
```python Python theme={null}
import requests
response = requests.get(
'https://api.credprotocol.com/api/v2/report/address/vitalik.eth/total/usd',
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
data = response.json()
print(f"Total Portfolio: ${data['total_asset_usd']}")
for chain in data['chains']:
print(f"{chain['chain_name']}: ${chain['total_asset_usd']}")
```
```json 200 theme={null}
{
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"timestamp": "2024-01-15T10:30:00Z",
"total_asset_usd": 125000.50,
"chains": [
{
"chain_id": 1,
"chain_name": "Ethereum",
"total_asset_usd": 85000.50
},
{
"chain_id": 8453,
"chain_name": "Base",
"total_asset_usd": 25000.00
},
{
"chain_id": 137,
"chain_name": "Polygon",
"total_asset_usd": 15000.00
}
]
}
```
## Performance
* **Response Time**: \< 1 second
* **Caching**: Results cached for 5 minutes per address
# Total Portfolio Value
Source: https://docs.credprotocol.com/api-reference/report/portfolio-total
GET /api/v2/report/address/{address}/total/usd/aggregate
Get the aggregated total USD portfolio value across all chains
## Overview
Returns the aggregated total USD value of all assets held by an address across all supported blockchain networks. This is the simplest endpoint for getting a wallet's total value.
This endpoint returns a single total value. For a breakdown by chain, use the `/total/usd` endpoint instead.
## Path Parameters
Ethereum address or ENS name (e.g., `vitalik.eth` or `0x742d35Cc6634C0532925a3b844Bc454e4438f44e`)
## Response
The resolved Ethereum address (checksummed)
Total portfolio value in USD across all chains
ISO 8601 timestamp when the value was calculated
## Included Assets
| Asset Type | Included |
| - | - |
| Native tokens (ETH, MATIC, etc.) | Yes |
| ERC-20 tokens | Yes |
| Stablecoins (USDC, USDT, DAI) | Yes |
| LP tokens (Uniswap, Curve) | Yes |
| Wrapped tokens (WETH, WBTC) | Yes |
| Collateral deposits | Yes |
| NFTs | No |
| Unclaimed rewards | No |
| Pending transactions | No |
| Debt positions | No |
## Pricing Sources
* **Primary**: Chainlink on-chain oracles (real-time)
* **Fallback**: CoinGecko API (for tokens without oracle coverage)
* **Update Frequency**: Prices refresh every 60 seconds
* **Denomination**: All values in USD
## Use Cases
* **Quick Net Worth**: Single API call for total portfolio value
* **Portfolio Tracking**: Monitor total holdings over time
* **Lending Capacity**: Assess collateral potential
* **Wallet Comparison**: Compare total holdings across wallets
## Related Endpoints
| Endpoint | Returns |
| - | - |
| `/total/usd/aggregate` | Single total value |
| `/total/usd` | Breakdown by chain |
| `/chain/{chain_id}/total/usd` | Single chain value |
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/report/address/vitalik.eth/total/usd/aggregate" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const response = await fetch('https://api.credprotocol.com/api/v2/report/address/vitalik.eth/total/usd/aggregate', {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const data = await response.json();
console.log(`Total Portfolio Value: $${data.total_asset_usd.toLocaleString()}`);
```
```python Python theme={null}
import requests
response = requests.get(
'https://api.credprotocol.com/api/v2/report/address/vitalik.eth/total/usd/aggregate',
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
data = response.json()
print(f"Total Portfolio Value: ${data['total_asset_usd']:,.2f}")
```
```json 200 theme={null}
{
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"total_asset_usd": 125000.50,
"timestamp": "2024-01-15T10:30:00Z"
}
```
## Performance
* **Response Time**: \< 1 second
* **Caching**: Results cached for 5 minutes per address
# Summary Credit Report
Source: https://docs.credprotocol.com/api-reference/report/summary-report
GET /api/v2/report/address/{address}/summary
Get a lightweight summary credit report without per-chain details
## Overview
Returns a lightweight summary of key credit metrics across all supported blockchain networks, without the detailed per-chain breakdowns included in the full report. This endpoint is optimized for speed and is ideal for dashboards and quick assessments.
This endpoint returns aggregated statistics only, making it significantly faster than the full report while still providing essential financial health indicators.
## Path Parameters
Ethereum address or ENS name (e.g., `vitalik.eth` or `0x742d35Cc6634C0532925a3b844Bc454e4438f44e`)
## Response
The resolved Ethereum address (checksummed)
ISO 8601 timestamp when the report was generated
First transaction details (timestamp, block\_number, chain\_id)
Most recent transaction details
Aggregated credit metrics
Total portfolio value in USD
Total collateral deposited in lending protocols
Total debt across all DeFi protocols
Total transaction count across all chains
Total token transfer count
Number of unique token holdings
Number of collateral positions
Number of active loan positions
Number of times the address was liquidated on Aave V2 or V3 (Ethereum) or Aave V3 (Base)
Always `0`. Overcollateralized lending protocols close positions by liquidation and have no default state.
Number of voluntary loan repayments on Aave V2 or V3 (Ethereum) or Aave V3 (Base). Repayments made through liquidation are not counted.
Number of identity attestations
## Summary vs Full Report
| Feature | Summary Report | Full Report |
| - | - | - |
| Response Time | 1-3 seconds | 3-10 seconds |
| Payload Size | \~1 KB | \~10-50 KB |
| Chain Details | No | Yes |
| Token Balances | No | Yes |
| NFT Listings | No | Yes |
| DeFi Positions | No | Yes |
| Caching | 5 minutes | 5 minutes |
## Use Cases
* **Dashboard Summary Cards**: Quick overview of wallet health
* **Mobile Applications**: Faster load times with smaller payloads
* **High-Volume Screening**: Efficiently evaluate many addresses
* **Portfolio Overviews**: Quick net worth and activity snapshots
* **Risk Pre-screening**: Fast initial creditworthiness check
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/report/address/vitalik.eth/summary" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const response = await fetch('https://api.credprotocol.com/api/v2/report/address/vitalik.eth/summary', {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const data = await response.json();
console.log(`Total Assets: $${data.report.summary.total_asset_usd}`);
console.log(`Active Loans: ${data.report.summary.count_active_loans}`);
```
```python Python theme={null}
import requests
response = requests.get(
'https://api.credprotocol.com/api/v2/report/address/vitalik.eth/summary',
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
data = response.json()
print(f"Total Assets: ${data['report']['summary']['total_asset_usd']}")
print(f"Active Loans: {data['report']['summary']['count_active_loans']}")
```
```json 200 theme={null}
{
"report": {
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"timestamp": "2024-01-15T10:30:00Z",
"first_transaction": {
"timestamp": 1438918251,
"block_number": 46147,
"chain_id": 1
},
"last_transaction": {
"timestamp": 1710255000,
"block_number": 19123456,
"chain_id": 1
},
"summary": {
"total_asset_usd": 125000.50,
"total_collateral_usd": 50000.00,
"total_debt_usd": 15000.00,
"count_transactions": 2456,
"count_transfers": 1234,
"count_balances": 25,
"count_collateral_deposits": 5,
"count_active_loans": 2,
"count_liquidations": 0,
"count_defaults": 0,
"count_repayments": 12,
"count_identity_attestations": 4
}
}
}
```
## Performance
* **Response Time**: 1-3 seconds (significantly faster than full report)
* **Caching**: Results cached for 5 minutes per address
# Mock Aggregated Report
Source: https://docs.credprotocol.com/api-reference/sandbox/mock-aggregated-report
GET /api/v2/sandbox/report/
Get a mock aggregated credit report for multiple addresses
## Overview
Returns a mock aggregated credit report combining metrics from multiple addresses. Use this to test multi-wallet report scenarios.
**SANDBOX**: This endpoint returns mock data for testing only. Do not use for production decisions.
## Query Parameters
Comma-separated list of Ethereum addresses (e.g., `address=0x123...,0x456...`)
## Response
Array of validated Ethereum addresses
Aggregated mock summary metrics (summed across addresses)
Earliest mock transaction across all addresses
Most recent mock transaction across all addresses
## Mock Aggregation
The sandbox aggregates mock data as:
* Numeric values are summed across addresses
* Attestations are merged and deduplicated
* First/last transactions span the full range
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/sandbox/report/?address=0x1111111111111111111111111111111111111111,0x2222222222222222222222222222222222222222" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const addresses = [
'0x1111111111111111111111111111111111111111',
'0x2222222222222222222222222222222222222222'
];
const response = await fetch(
`https://api.credprotocol.com/api/v2/sandbox/report/?address=${addresses.join(',')}`,
{
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
const report = await response.json();
console.log(`Combined assets: $${report.report.summary.total_asset_usd}`);
```
```python Python theme={null}
import requests
addresses = [
'0x1111111111111111111111111111111111111111',
'0x2222222222222222222222222222222222222222'
]
response = requests.get(
'https://api.credprotocol.com/api/v2/sandbox/report/',
params={'address': ','.join(addresses)},
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
report = response.json()
print(f"Combined assets: ${report['report']['summary']['total_asset_usd']}")
```
```json 200 theme={null}
{
"report": {
"address": [
"0x1111111111111111111111111111111111111111",
"0x2222222222222222222222222222222222222222"
],
"timestamp": "2024-01-15T10:30:00Z",
"first_transaction": {
"timestamp": "2022-01-15T10:30:00Z",
"block_number": 14000000,
"chain_id": 1
},
"last_transaction": {
"timestamp": "2024-01-10T15:45:00Z",
"block_number": 19500000,
"chain_id": 1
},
"summary": {
"total_asset_usd": 250000.00,
"total_collateral_usd": 100000.00,
"count_transactions": 4820,
"count_identity_attestations": 6
}
}
}
```
## Performance
* **Response Time**: Instant (no blockchain queries)
* **Quota**: Does not count against your API quota
# Mock Aggregated Score
Source: https://docs.credprotocol.com/api-reference/sandbox/mock-aggregated-score
GET /api/v2/sandbox/score/
Get a mock aggregated credit score for multiple addresses
## Overview
Returns a mock aggregated credit score combining multiple addresses into a single score. Use this to test multi-wallet scoring scenarios like multi-signature wallets or joint accounts.
**SANDBOX**: This endpoint returns mock data for testing only. Do not use for production decisions.
## Query Parameters
Comma-separated list of Ethereum addresses (e.g., `address=0x123...,0x456...,0x789...`)
## Response
Array of validated Ethereum addresses
Mock aggregated credit score (mean of individual mock scores)
Aggregated score decile from 1 to 10
Score range: `low`, `fair`, `good`, `very_good`, or `excellent`
Always returns `andromeda_1.1`
## Mock Aggregation
The sandbox calculates the aggregated score as:
1. Generate deterministic mock score for each address
2. Calculate the mean of all individual scores
3. Derive decile and range from the aggregated score
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/sandbox/score/?address=0x1111111111111111111111111111111111111111,0x2222222222222222222222222222222222222222" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const addresses = [
'0x1111111111111111111111111111111111111111',
'0x2222222222222222222222222222222222222222'
];
const response = await fetch(
`https://api.credprotocol.com/api/v2/sandbox/score/?address=${addresses.join(',')}`,
{
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
const data = await response.json();
console.log(`Aggregated score: ${data.score}`);
```
```python Python theme={null}
import requests
addresses = [
'0x1111111111111111111111111111111111111111',
'0x2222222222222222222222222222222222222222'
]
response = requests.get(
'https://api.credprotocol.com/api/v2/sandbox/score/',
params={'address': ','.join(addresses)},
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
data = response.json()
print(f"Aggregated score: {data['score']}")
```
```json 200 theme={null}
{
"address": [
"0x1111111111111111111111111111111111111111",
"0x2222222222222222222222222222222222222222"
],
"score": 745,
"decile": 8,
"range": "good",
"model_version": "andromeda_1.1",
"timestamp": "2024-01-15T10:30:00Z"
}
```
```json 400 theme={null}
{
"error": "No valid addresses provided",
"status_code": 400
}
```
## Performance
* **Response Time**: Instant (no blockchain queries)
* **Quota**: Does not count against your API quota
# Mock Batch Scores
Source: https://docs.credprotocol.com/api-reference/sandbox/mock-batch-score
GET /api/v2/sandbox/score/batch/
Get mock individual credit scores for multiple addresses
## Overview
Returns mock individual credit scores for multiple addresses without aggregation. Use this to test batch scoring scenarios where you need per-wallet scores.
**SANDBOX**: This endpoint returns mock data for testing only. Do not use for production decisions.
## Query Parameters
Comma-separated list of Ethereum addresses (e.g., `address=0x123...,0x456...,0x789...`)
## Response
Array of individual mock score objects
The Ethereum address
Mock credit score between 300 and 1000
Score decile from 1 to 10
Score range: `low`, `fair`, `good`, `very_good`, or `excellent`
Number of scores returned
## Comparison: Batch vs Aggregated
| Endpoint | Returns | Use Case |
| - | - | - |
| `/sandbox/score/batch/` | Individual scores per address | Per-wallet display |
| `/sandbox/score/` | Single aggregated score | Combined assessment |
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/sandbox/score/batch/?address=0x1111111111111111111111111111111111111111,0x2222222222222222222222222222222222222222" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const addresses = [
'0x1111111111111111111111111111111111111111',
'0x2222222222222222222222222222222222222222'
];
const response = await fetch(
`https://api.credprotocol.com/api/v2/sandbox/score/batch/?address=${addresses.join(',')}`,
{
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
const data = await response.json();
data.scores.forEach(s => console.log(`${s.address}: ${s.score}`));
```
```python Python theme={null}
import requests
addresses = [
'0x1111111111111111111111111111111111111111',
'0x2222222222222222222222222222222222222222'
]
response = requests.get(
'https://api.credprotocol.com/api/v2/sandbox/score/batch/',
params={'address': ','.join(addresses)},
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
data = response.json()
for s in data['scores']:
print(f"{s['address']}: {s['score']}")
```
```json 200 theme={null}
{
"scores": [
{
"address": "0x1111111111111111111111111111111111111111",
"score": 726,
"decile": 8,
"range": "good",
"model_version": "andromeda_1.1",
"timestamp": "2024-01-15T10:30:00Z"
},
{
"address": "0x2222222222222222222222222222222222222222",
"score": 845,
"decile": 9,
"range": "very_good",
"model_version": "andromeda_1.1",
"timestamp": "2024-01-15T10:30:00Z"
}
],
"count": 2
}
```
## Performance
* **Response Time**: Instant (no blockchain queries)
* **Quota**: Does not count against your API quota
# Mock Chain Report
Source: https://docs.credprotocol.com/api-reference/sandbox/mock-chain-report
GET /api/v2/sandbox/report/address/{address}/chain/{chain_id}
Get a mock single-chain credit report for testing
## Overview
Returns a mock credit report for a specific blockchain network. Use this to test chain-specific integrations.
**SANDBOX**: This endpoint returns mock data for testing only. Do not use for production decisions.
## Path Parameters
Any Ethereum address (e.g., `0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17`)
The chain ID (e.g., `1` for Ethereum, `8453` for Base)
## Supported Chain IDs
| Network | Chain ID |
| - | - |
| Ethereum | 1 |
| Optimism | 10 |
| BNB Chain | 56 |
| Polygon | 137 |
| Base | 8453 |
| Celo | 42220 |
| Arbitrum | 42161 |
| Avalanche | 43114 |
| Scroll | 534352 |
| Linea | 59144 |
## Response
Array containing single chain mock data with balances
Mock summary metrics for this chain only
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/sandbox/report/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17/chain/1" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://api.credprotocol.com/api/v2/sandbox/report/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17/chain/1',
{
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
const report = await response.json();
console.log(`Ethereum assets: $${report.report.summary.total_asset_usd}`);
```
```python Python theme={null}
import requests
response = requests.get(
'https://api.credprotocol.com/api/v2/sandbox/report/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17/chain/1',
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
report = response.json()
print(f"Ethereum assets: ${report['report']['summary']['total_asset_usd']}")
```
```json 200 theme={null}
{
"report": {
"address": "0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17",
"timestamp": "2024-01-15T10:30:00Z",
"summary": {
"total_asset_usd": 85000.00,
"count_transactions": 1800,
"count_transfers": 900,
"count_balances": 15
},
"chains": [
{
"chain": {
"id": 1,
"name": "Ethereum Mainnet",
"has_past_activity": true,
"current_balance_usd": 85000.00,
"transaction_count": 1800,
"balances": [
{
"symbol": "ETH",
"name": "Ethereum",
"usd_value": 50000.00
},
{
"symbol": "USDC",
"name": "USD Coin",
"usd_value": 35000.00
}
]
}
}
]
}
}
```
## Related Endpoints
| Endpoint | Description |
| - | - |
| `/sandbox/report/address/{address}/chain/{chain_id}/summary` | Chain summary without balances |
| `/sandbox/report/address/{address}/chain/{chain_id}/total/usd` | Chain portfolio value only |
## Performance
* **Response Time**: Instant (no blockchain queries)
* **Quota**: Does not count against your API quota
# Mock Enhanced Report
Source: https://docs.credprotocol.com/api-reference/sandbox/mock-enhanced-report
POST /api/v2/sandbox/report/address/{address}
Get a mock enhanced credit report with off-chain data for testing
## Overview
Returns a mock enhanced credit report that simulates combining on-chain data with off-chain metrics. Use this to test your integration with the enhanced report endpoint.
**SANDBOX**: This endpoint returns mock data for testing only. Do not use for production decisions.
## Path Parameters
Any Ethereum address (e.g., `0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17`)
## Request Body
Source name for the additional data (e.g., "Coinbase Account")
Simulated off-chain asset value in USD
Simulated off-chain collateral value in USD
Simulated off-chain transaction count
## Response
The response includes mock on-chain data plus the additional off-chain data merged into the summary.
Combined summary metrics (mock on-chain + provided off-chain)
The off-chain data source information you provided
```bash cURL theme={null}
curl -X POST "https://api.credprotocol.com/api/v2/sandbox/report/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Coinbase Account",
"total_asset_usd": 75000,
"count_transactions": 450
}'
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://api.credprotocol.com/api/v2/sandbox/report/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17',
{
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Coinbase Account',
total_asset_usd: 75000,
count_transactions: 450
})
}
);
const report = await response.json();
console.log(`Combined assets: $${report.report.summary.total_asset_usd}`);
```
```python Python theme={null}
import requests
response = requests.post(
'https://api.credprotocol.com/api/v2/sandbox/report/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17',
headers={'Authorization': 'Bearer YOUR_API_KEY'},
json={
'name': 'Coinbase Account',
'total_asset_usd': 75000,
'count_transactions': 450
}
)
report = response.json()
print(f"Combined assets: ${report['report']['summary']['total_asset_usd']}")
```
```json 200 theme={null}
{
"report": {
"address": "0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17",
"timestamp": "2024-01-15T10:30:00Z",
"summary": {
"total_asset_usd": 175000.00,
"count_transactions": 1450
},
"additional": {
"source": {
"name": "Coinbase Account",
"data": {
"total_asset_usd": 75000,
"count_transactions": 450
}
}
},
"chains": []
}
}
```
```json 400 theme={null}
{
"error": "Additional data must provide a 'name' field"
}
```
## Performance
* **Response Time**: Instant (no blockchain queries)
* **Quota**: Does not count against your API quota
# Mock Enhanced Score
Source: https://docs.credprotocol.com/api-reference/sandbox/mock-enhanced-score
POST /api/v2/sandbox/score/address/{address}
Get a mock enhanced credit score with off-chain data for testing
## Overview
Returns a mock enhanced credit score that simulates the boost calculation from off-chain assets. Use this to test your integration with the enhanced score endpoint.
**SANDBOX**: This endpoint returns mock data for testing only. Do not use for production decisions.
## Path Parameters
Any Ethereum address (e.g., `0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17`)
## Request Body
Simulated off-chain asset value in USD. Higher values result in a larger mock boost.
## Response
The response format is identical to the production POST `/api/v2/score/address/{address}` endpoint.
The input Ethereum address
Mock enhanced credit score between 300 and 1000
Score decile from 1 to 10
Score range: `low`, `fair`, `good`, `very_good`, or `excellent`
## Mock Boost Calculation
The sandbox simulates the boost calculation:
* Boost factor = min(total\_asset\_usd / 100000, 1.0)
* Maximum boost at \$100,000 in off-chain assets
* Boost increases the base mock score proportionally
```bash cURL theme={null}
curl -X POST "https://api.credprotocol.com/api/v2/sandbox/score/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"total_asset_usd": 50000}'
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://api.credprotocol.com/api/v2/sandbox/score/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17',
{
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({ total_asset_usd: 50000 })
}
);
const data = await response.json();
console.log(`Enhanced score: ${data.score}`);
```
```python Python theme={null}
import requests
response = requests.post(
'https://api.credprotocol.com/api/v2/sandbox/score/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17',
headers={'Authorization': 'Bearer YOUR_API_KEY'},
json={'total_asset_usd': 50000}
)
data = response.json()
print(f"Enhanced score: {data['score']}")
```
```json 200 theme={null}
{
"address": "0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17",
"score": 795,
"decile": 8,
"range": "good",
"model_version": "andromeda_1.1",
"timestamp": "2024-01-15T10:30:00Z"
}
```
## Performance
* **Response Time**: Instant (no blockchain queries)
* **Quota**: Does not count against your API quota
# Mock Portfolio Value
Source: https://docs.credprotocol.com/api-reference/sandbox/mock-portfolio
GET /api/v2/sandbox/report/address/{address}/total/usd
Get mock portfolio value endpoints for testing
## Overview
Returns mock portfolio value data for testing. This page covers both the all-chains and single-chain portfolio value endpoints.
**SANDBOX**: These endpoints return mock data for testing only. Do not use for production decisions.
## All-Chains Portfolio Value
### Endpoint
```
GET /api/v2/sandbox/report/address/{address}/total/usd
```
### Path Parameters
Any Ethereum address
### Response
The input Ethereum address
Mock total portfolio value in USD
ISO 8601 timestamp
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/sandbox/report/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17/total/usd" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://api.credprotocol.com/api/v2/sandbox/report/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17/total/usd',
{
headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
}
);
const data = await response.json();
console.log(`Total value: $${data.total_asset_usd}`);
```
```python Python theme={null}
import requests
response = requests.get(
'https://api.credprotocol.com/api/v2/sandbox/report/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17/total/usd',
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
data = response.json()
print(f"Total value: ${data['total_asset_usd']}")
```
```json 200 theme={null}
{
"address": "0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17",
"timestamp": "2024-01-15T10:30:00Z",
"total_asset_usd": 125000.50
}
```
***
## Single-Chain Portfolio Value
### Endpoint
```
GET /api/v2/sandbox/report/address/{address}/chain/{chain_id}/total/usd
```
### Path Parameters
Any Ethereum address
The chain ID (e.g., `1` for Ethereum)
### Response
The input Ethereum address
The requested chain ID
Human-readable chain name
Mock portfolio value on this chain
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/sandbox/report/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17/chain/1/total/usd" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://api.credprotocol.com/api/v2/sandbox/report/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17/chain/1/total/usd',
{
headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
}
);
const data = await response.json();
console.log(`Ethereum value: $${data.total_asset_usd}`);
```
```python Python theme={null}
import requests
response = requests.get(
'https://api.credprotocol.com/api/v2/sandbox/report/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17/chain/1/total/usd',
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
data = response.json()
print(f"Ethereum value: ${data['total_asset_usd']}")
```
```json 200 theme={null}
{
"address": "0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17",
"timestamp": "2024-01-15T10:30:00Z",
"total_asset_usd": 85000.50,
"chain_id": 1,
"chain_name": "Ethereum"
}
```
## Performance
* **Response Time**: Instant (no blockchain queries)
* **Quota**: Does not count against your API quota
# Mock Credit Report
Source: https://docs.credprotocol.com/api-reference/sandbox/mock-report
GET /api/v2/sandbox/report/address/{address}
Get a mock credit report for testing purposes
## Overview
Returns a deterministic mock credit report for testing your integration. The report contains realistic mock data structure identical to production responses.
⚠️ **SANDBOX**: This endpoint returns mock data for testing only. Do not use for production decisions.
## Path Parameters
Any Ethereum address (e.g., `0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17`)
## Response
The response format is identical to the production `/api/v2/report/address/{address}` endpoint.
The input Ethereum address
Mock credit score summary
Mock asset holdings
Mock DeFi positions
Mock transaction activity
Always `true` for sandbox responses
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/sandbox/report/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://api.credprotocol.com/api/v2/sandbox/report/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17',
{
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
const report = await response.json();
console.log(report.report.summary.total_asset_usd);
```
```python Python theme={null}
import requests
response = requests.get(
'https://api.credprotocol.com/api/v2/sandbox/report/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17',
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
report = response.json()
print(report['report']['summary']['total_asset_usd'])
```
```json 200 theme={null}
{
"address": "0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17",
"score": {
"value": 723,
"classification": "Good"
},
"assets": {
"total_value_usd": 50000.00,
"tokens": [
{
"symbol": "ETH",
"name": "Ethereum",
"balance": "10.5",
"value_usd": 35000,
"chain_id": 1
},
{
"symbol": "USDC",
"name": "USD Coin",
"balance": "15000",
"value_usd": 15000,
"chain_id": 1
}
],
"nfts": [
{
"name": "Mock NFT #1234",
"collection": "Mock Collection",
"chain_id": 1
}
]
},
"defi": {
"protocols": [
{
"name": "Mock Protocol",
"supplied": 10000,
"borrowed": 0,
"chain_id": 1
}
],
"total_supplied": 10000,
"total_borrowed": 0
},
"activity": {
"first_transaction": "2021-01-01T00:00:00Z",
"total_transactions": 500,
"active_chains": [1, 137]
},
"sandbox": true,
"cached": false,
"timestamp": "2024-01-15T10:30:00Z"
}
```
## Performance
* **Response Time**: Instant (no blockchain queries)
* **Caching**: Mock data is deterministic, no caching needed
* **Rate Limits**: Standard rate limits apply
* **Quota**: Does not count against your API quota
# Mock Credit Score
Source: https://docs.credprotocol.com/api-reference/sandbox/mock-score
GET /api/v2/sandbox/score/address/{address}
Get a mock credit score for testing purposes
## Overview
Returns a deterministic mock credit score for testing your integration. The score is calculated based on the address, so the same address always returns the same mock score.
⚠️ **SANDBOX**: This endpoint returns mock data for testing only. Do not use for production decisions.
## Path Parameters
Any Ethereum address (e.g., `0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17`)
## Response
The response format is identical to the production `/api/v2/score/address/{address}` endpoint.
The input Ethereum address
Mock credit score between 300 and 1000
Score decile from 1 to 10
Score range: `low`, `fair`, `good`, `very_good`, or `excellent`
Always returns `andromeda_1.1`
ISO 8601 timestamp when the mock score was generated
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/sandbox/score/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://api.credprotocol.com/api/v2/sandbox/score/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17',
{
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
const data = await response.json();
console.log(data.score);
```
```python Python theme={null}
import requests
response = requests.get(
'https://api.credprotocol.com/api/v2/sandbox/score/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17',
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
data = response.json()
print(data['score'])
```
```json 200 theme={null}
{
"address": "0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17",
"score": 726,
"decile": 8,
"range": "good",
"model_version": "andromeda_1.1",
"timestamp": "2024-01-15T10:30:00Z"
}
```
## Performance
* **Response Time**: Instant (no blockchain queries)
* **Caching**: Mock data is deterministic, no caching needed
* **Rate Limits**: Standard rate limits apply
* **Quota**: Does not count against your API quota
# Mock Summary Report
Source: https://docs.credprotocol.com/api-reference/sandbox/mock-summary-report
GET /api/v2/sandbox/report/address/{address}/summary
Get a mock lightweight summary report for testing
## Overview
Returns a mock lightweight summary report without detailed chain breakdowns. Use this to test dashboard integrations that need quick summary data.
**SANDBOX**: This endpoint returns mock data for testing only. Do not use for production decisions.
## Path Parameters
Any Ethereum address (e.g., `0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17`)
## Response
The response includes mock summary metrics without per-chain details.
The input Ethereum address
Mock aggregated summary metrics
Mock total portfolio value
Mock transaction count
Mock attestation count
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/sandbox/report/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17/summary" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://api.credprotocol.com/api/v2/sandbox/report/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17/summary',
{
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
const report = await response.json();
console.log(`Total assets: $${report.report.summary.total_asset_usd}`);
```
```python Python theme={null}
import requests
response = requests.get(
'https://api.credprotocol.com/api/v2/sandbox/report/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17/summary',
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
report = response.json()
print(f"Total assets: ${report['report']['summary']['total_asset_usd']}")
```
```json 200 theme={null}
{
"report": {
"address": "0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17",
"timestamp": "2024-01-15T10:30:00Z",
"first_transaction": {
"timestamp": "2022-06-15T10:30:00Z",
"block_number": 15000000,
"chain_id": 1
},
"last_transaction": {
"timestamp": "2024-01-10T15:45:00Z",
"block_number": 19000000,
"chain_id": 1
},
"summary": {
"total_asset_usd": 125000.50,
"total_collateral_usd": 50000.00,
"total_debt_usd": 15000.00,
"count_transactions": 2456,
"count_transfers": 1234,
"count_identity_attestations": 4
}
}
}
```
## Performance
* **Response Time**: Instant (no blockchain queries)
* **Quota**: Does not count against your API quota
# Sandbox Overview
Source: https://docs.credprotocol.com/api-reference/sandbox/overview
Test your integration with mock data before going live
## What is the Sandbox?
The Sandbox provides mock API endpoints that return deterministic test data. Use these endpoints to develop and test your integration without consuming your API quota or waiting for real blockchain queries.
**SANDBOX**: All data returned by sandbox endpoints is mock data for testing purposes only. Do not use sandbox responses for production decisions.
## Sandbox vs Production
| Feature | Sandbox | Production |
| - | - | - |
| Data | Mock/deterministic | Real blockchain data |
| Response time | Instant | 1-10 seconds |
| API quota | Not counted | Counted |
| Base URL | Same | Same |
| Endpoint prefix | `/api/v2/sandbox/` | `/api/v2/` |
## Available Sandbox Endpoints
All production endpoints have sandbox equivalents. Simply add `/sandbox/` after `/api/v2/`:
### Score Endpoints
| Sandbox Endpoint | Production Equivalent | Description |
| - | - | - |
| `GET /sandbox/score/address/{address}` | `/score/address/{address}` | Mock credit score |
| `POST /sandbox/score/address/{address}` | `/score/address/{address}` | Mock enhanced score |
| `GET /sandbox/score/` | `/score/` | Mock aggregated score |
| `GET /sandbox/score/batch/` | `/score/batch/` | Mock batch individual scores |
### Report Endpoints
| Sandbox Endpoint | Production Equivalent | Description |
| - | - | - |
| `GET /sandbox/report/address/{address}` | `/report/address/{address}` | Mock comprehensive report |
| `POST /sandbox/report/address/{address}` | `/report/address/{address}` | Mock enhanced report |
| `GET /sandbox/report/` | `/report/` | Mock aggregated report |
| `GET /sandbox/report/address/{address}/summary` | `/report/address/{address}/summary` | Mock summary report |
| `GET /sandbox/report/address/{address}/chain/{chain_id}` | `/report/address/{address}/chain/{chain_id}` | Mock single-chain report |
| `GET /sandbox/report/address/{address}/chain/{chain_id}/summary` | `/report/address/{address}/chain/{chain_id}/summary` | Mock chain summary |
| `GET /sandbox/report/address/{address}/total/usd` | `/report/address/{address}/total/usd` | Mock portfolio value |
| `GET /sandbox/report/address/{address}/chain/{chain_id}/total/usd` | `/report/address/{address}/chain/{chain_id}/total/usd` | Mock chain portfolio |
## Deterministic Responses
Sandbox responses are deterministic based on the address provided:
* The same address always returns the same mock data
* Different addresses return different (but consistent) mock scores
* This allows you to test various scenarios reliably
## When to Use the Sandbox
Build and test your integration without using real API quota
Run automated tests against consistent mock data
Build demos without depending on real blockchain data
Design and test your UI with various score scenarios
## Example Workflow
Use sandbox endpoints while building your integration
```bash theme={null}
curl "https://api.credprotocol.com/api/v2/sandbox/score/address/0x123..." \
-H "Authorization: Bearer YOUR_API_KEY"
```
Test different addresses to see various score ranges
Simply remove `/sandbox/` from the URL to use production endpoints
```bash theme={null}
curl "https://api.credprotocol.com/api/v2/score/address/0x123..." \
-H "Authorization: Bearer YOUR_API_KEY"
```
## Test Addresses
Mock scores are generated deterministically from the address. Here are example addresses for testing specific scenarios:
| Address | Approximate Score | Classification |
| - | - | - |
| `0x0000000000000000000000000000000000000001` | \~850 | Excellent |
| `0x0000000000000000000000000000000000000002` | \~720 | Good |
| `0x0000000000000000000000000000000000000003` | \~550 | Fair |
| `0x0000000000000000000000000000000000000004` | \~400 | Low |
The actual mock score is calculated using the last 8 characters of the address, so any address will produce a consistent, deterministic result.
# Aggregated Credit Score
Source: https://docs.credprotocol.com/api-reference/score/aggregated-score
GET /api/v2/score/
Get a single aggregated credit score for multiple Ethereum addresses
## Overview
Returns a single aggregated credit score for multiple Ethereum addresses, combining individual scores into one unified value. This is useful for multi-signature wallets, joint accounts, or portfolio-wide credit assessments.
Unlike the batch endpoint which returns individual scores, this endpoint aggregates all addresses into a single combined score.
## Query Parameters
Comma-separated list of Ethereum addresses or ENS names (e.g., `address=0x123...,0x456...,vitalik.eth`)
## Response
Array of resolved Ethereum addresses (checksummed)
Aggregated credit score between 300 and 1000 (mean of individual scores)
Aggregated score decile from 1 to 10
Score range: `low`, `fair`, `good`, `very_good`, or `excellent`
The scoring model version (currently `andromeda_1.1`)
ISO 8601 timestamp when the score was calculated
## Aggregation Method
The aggregated score is calculated as the **mean** of all individual address scores:
1. Each valid address is scored individually using the Andromeda model
2. Invalid addresses are skipped (logged as warnings)
3. The final score is the arithmetic mean of all valid scores
4. Decile and range are derived from the aggregated score
## Use Cases
* **Multi-signature Wallets**: Assess the combined creditworthiness of all signers
* **Joint Account Holders**: Evaluate combined credit for shared wallets
* **Organization Assessment**: Score a company's treasury across multiple wallets
* **Portfolio Credit Rating**: Get a single score representing an entire portfolio
## Comparison: Aggregated vs Batch
| Feature | Aggregated (`/score/`) | Batch (`/score/batch/`) |
| - | - | - |
| Output | Single combined score | Array of individual scores |
| Use Case | Portfolio-wide assessment | Per-wallet analysis |
| Response Size | Small | Larger (scales with addresses) |
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/score/?address=vitalik.eth,0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const addresses = ['vitalik.eth', '0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17'];
const response = await fetch(
`https://api.credprotocol.com/api/v2/score/?address=${addresses.join(',')}`,
{
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
const data = await response.json();
console.log(`Aggregated score: ${data.score}`);
```
```python Python theme={null}
import requests
addresses = ['vitalik.eth', '0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17']
response = requests.get(
'https://api.credprotocol.com/api/v2/score/',
params={'address': ','.join(addresses)},
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
data = response.json()
print(f"Aggregated score: {data['score']}")
```
```json 200 theme={null}
{
"address": [
"0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17"
],
"score": 806,
"decile": 6,
"range": "good",
"model_version": "andromeda_1.1",
"timestamp": "2024-01-15T10:30:00Z"
}
```
```json 400 theme={null}
{
"error": "No valid addresses provided",
"status_code": 400
}
```
## Performance
* **Response Time**: Typically 3-5 seconds (addresses scored in parallel)
* **Caching**: Individual address scores are cached for 5 minutes
# Batch Credit Scores
Source: https://docs.credprotocol.com/api-reference/score/batch-score
GET /api/v2/score/batch/
Get individual credit scores for multiple Ethereum addresses in a single request
## Overview
Returns credit scores for multiple Ethereum addresses in a single API call. This is more efficient than making individual requests when you need to score multiple addresses.
Maximum of **100 addresses** per batch request.
## Query Parameters
Comma-separated list of Ethereum addresses or ENS names (e.g., `address=0x123...,0x456...,vitalik.eth`)
## Response
Array of score results for each address
The resolved Ethereum address (checksummed)
Credit score between 300 and 1000
Score decile from 1 to 10
Score range: `low`, `fair`, `good`, `very_good`, or `excellent`
The scoring model version (currently `andromeda_1.1`)
ISO 8601 timestamp when the score was calculated
Total number of scores returned
## Use Cases
* **Portfolio Analysis**: Score all addresses in a user's portfolio
* **Batch Verification**: Check creditworthiness of multiple counterparties
* **Risk Assessment**: Evaluate a list of addresses for lending decisions
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/score/batch/?address=vitalik.eth,0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const addresses = ['vitalik.eth', '0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17'];
const response = await fetch(
`https://api.credprotocol.com/api/v2/score/batch/?address=${addresses.join(',')}`,
{
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
const data = await response.json();
console.log(data.scores);
```
```python Python theme={null}
import requests
addresses = ['vitalik.eth', '0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17']
response = requests.get(
'https://api.credprotocol.com/api/v2/score/batch/',
params={'address': ','.join(addresses)},
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
data = response.json()
print(data['scores'])
```
```json 200 theme={null}
{
"scores": [
{
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"score": 847,
"decile": 7,
"range": "very_good",
"model_version": "andromeda_1.1",
"timestamp": "2024-01-15T10:30:00Z"
},
{
"address": "0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17",
"score": 765,
"decile": 5,
"range": "good",
"model_version": "andromeda_1.1",
"timestamp": "2024-01-15T10:30:00Z"
}
],
"count": 2
}
```
```json 400 theme={null}
{
"detail": "Too many addresses. Maximum is 100 per request."
}
```
## Performance Notes
* **Response Time**: Typically 2-5 seconds for 10 addresses, longer for larger batches
* **Caching**: Individual address scores are cached for 5 minutes
* **Parallelization**: Requests are processed in parallel for optimal performance
Batch requests count as multiple API calls against your quota (one per address).
# Enhanced Credit Score
Source: https://docs.credprotocol.com/api-reference/score/boosted-score
POST /api/v2/score/address/{address}
Get an enhanced credit score with off-chain asset data
## Overview
Returns an enhanced credit score that combines on-chain activity with additional off-chain asset information for a more comprehensive creditworthiness assessment.
Enhanced scores incorporate verified off-chain asset data to provide a more complete financial picture.
## Path Parameters
Ethereum address or ENS name (e.g., `vitalik.eth` or `0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17`)
## Request Body
Total value of off-chain assets in USD to include in the score calculation
## Response
The resolved Ethereum address (checksummed)
Enhanced credit score between 300 and 1000
Score decile from 1 to 10
Score range: `low`, `fair`, `good`, `very_good`, or `excellent`
The scoring model version (currently `andromeda_1.1`)
ISO 8601 timestamp when the score was calculated
## Boost Calculation
The boost is calculated as a percentage of the gap between the current score and 1000:
* **Maximum boost**: 15% of (1000 - current\_score)
* **Boost factor**: Proportional to additional assets (capped at \$50,000)
* **Example**: Score 700 with \$50k off-chain assets = up to +45 points
```bash cURL theme={null}
curl -X POST "https://api.credprotocol.com/api/v2/score/address/vitalik.eth" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"total_asset_usd": 50000}'
```
```javascript JavaScript theme={null}
const response = await fetch('https://api.credprotocol.com/api/v2/score/address/vitalik.eth', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({ total_asset_usd: 50000 })
});
const data = await response.json();
console.log(`Enhanced score: ${data.score}`);
```
```python Python theme={null}
import requests
response = requests.post(
'https://api.credprotocol.com/api/v2/score/address/vitalik.eth',
headers={'Authorization': 'Bearer YOUR_API_KEY'},
json={'total_asset_usd': 50000}
)
data = response.json()
print(f"Enhanced score: {data['score']}")
```
```json 200 theme={null}
{
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"score": 870,
"decile": 8,
"range": "very_good",
"model_version": "andromeda_1.1",
"timestamp": "2024-01-15T10:30:00Z"
}
```
```json 404 theme={null}
{
"detail": "Address not found or has no on-chain activity"
}
```
## When to Use Enhanced Scores
Use enhanced scores for more accurate risk assessment when making lending decisions. The additional identity verification reduces the risk of sybil attacks.
When you need to assess the trustworthiness of a counterparty, enhanced scores provide a more holistic view by incorporating reputation data.
Offer better terms or reduced requirements to users with high enhanced scores, as they've demonstrated verified identity and reputation.
# Get Credit Score
Source: https://docs.credprotocol.com/api-reference/score/get-score
GET /api/v2/score/address/{address}
Get the credit score for a single Ethereum address
## Overview
Returns a credit score (300-1000) for the specified Ethereum address based on on-chain activity analysis.
Scores are calculated using the **Andromeda** scoring model and cached for 5 minutes.
## Path Parameters
Ethereum address or ENS name (e.g., `vitalik.eth` or `0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17`)
## Response
The resolved Ethereum address (checksummed)
Credit score between 300 and 1000
Score decile from 1 to 10
Score range: `low`, `fair`, `good`, `very_good`, or `excellent`
The scoring model version (currently `andromeda_1.1`)
ISO 8601 timestamp when the score was calculated
Optional array of score factors (when `include_factors=true`). Each factor includes `label`, `rating`, and `description`.
How completely the address's lending events had been read when the score was computed: `complete`, `partial`, `pending` or `failed`
`true` when `credit_events_coverage` is not `complete`. The score may not yet reflect the address's repayments and liquidations.
## Provisional Scores
The first time an address is scored, its lending history is read from the chain. For most addresses this completes within the request. For an address with a long history it can take longer, and the response is returned before it finishes:
```json theme={null}
{
"score": 761,
"credit_events_coverage": "pending",
"provisional": true
}
```
The rest of the history is read in the background, usually within a few seconds. Request the score again to get the complete result. A provisional score is never cached for more than 30 seconds.
A provisional score can be higher than the final score, because liquidations that have not been read yet are not counted. If you use scores to make credit decisions, check `provisional` and retry before acting.
## Score Ranges
| Score Range | Range | Description |
| - | - | - |
| 920-1000 | Excellent | Exceptional on-chain activity and credit history |
| 840-919 | Very Good | Strong creditworthiness indicators |
| 750-839 | Good | Solid on-chain history |
| 640-749 | Fair | Some positive activity, room for improvement |
| 300-639 | Low | Limited on-chain history or high-risk activity |
## Scoring Factors
The Andromeda model considers:
* **Wallet Age**: How long the address has been active
* **Transaction History**: Volume and frequency of transactions
* **DeFi Activity**: Lending, borrowing, and liquidity provision
* **Asset Holdings**: Token and NFT portfolio value
* **Repayment History**: DeFi loan repayments and liquidations
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/score/address/vitalik.eth" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const response = await fetch('https://api.credprotocol.com/api/v2/score/address/vitalik.eth', {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const data = await response.json();
console.log(data.score); // 847
```
```python Python theme={null}
import requests
response = requests.get(
'https://api.credprotocol.com/api/v2/score/address/vitalik.eth',
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
data = response.json()
print(data['score']) # 847
```
```json 200 theme={null}
{
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"score": 847,
"decile": 7,
"range": "very_good",
"model_version": "andromeda_1.1",
"timestamp": "2024-01-15T10:30:00Z"
}
```
```json 400 theme={null}
{
"detail": "Invalid Ethereum address format"
}
```
```json 401 theme={null}
{
"detail": "Invalid or missing API key"
}
```
```json 404 theme={null}
{
"detail": "Address not found or has no on-chain activity"
}
```
# Chains & Protocols
Source: https://docs.credprotocol.com/chains-and-protocols
Blockchain networks and DeFi protocols supported by Cred Protocol
## Chains Supported
Cred Protocol aggregates on-chain data across multiple blockchain networks to build comprehensive credit profiles. All chains are queried for transaction history, token balances, NFT holdings, and DeFi activity.
| Chain | Chain ID | Data Coverage |
| - | - | - |
| Ethereum | 1 | Full (lending, balances, NFTs, identity) |
| Base | 8453 | Full (lending, balances, NFTs, identity) |
| Polygon | 137 | Balances, NFTs, transactions, identity |
| Arbitrum | 42161 | Balances, NFTs, transactions |
| Optimism | 10 | Balances, NFTs, transactions |
| Avalanche | 43114 | Balances, NFTs, transactions |
| BNB Chain | 56 | Balances, NFTs, transactions |
| Celo | 42220 | Balances, transactions |
| Scroll | 534352 | Balances, transactions |
| Linea | 59144 | Balances, transactions |
Ethereum and Base have the deepest lending protocol coverage. All chains contribute to transaction history, balance data, and overall activity metrics.
***
## Lending Protocol Coverage
Cred Protocol tracks borrowing and lending activity across major DeFi protocols. This data directly contributes to the **Borrowing History**, **Wallet Health**, and **New Credit** scoring factors.
### Aave
| Protocol | Version | Chain | Positions | Event history |
| - | - | - | - | - |
| Aave | V3 | Ethereum | Collateral deposits, variable debt positions | Supply, withdraw, borrow, repay, liquidation |
| Aave | V3 | Base | Collateral deposits (USDC, USDbC, WETH, cbETH) | Supply, withdraw, borrow, repay, liquidation |
| Aave | V2 | Ethereum | Collateral deposits | Supply, withdraw, borrow, repay, liquidation |
**Positions** are read from current token balances. **Event history** is read from the pool's on-chain events since deployment, for every asset in the pool, and is returned in the report's `credit_events` section.
**Collateral tokens tracked:**
WETH, wstETH, WBTC, USDC, DAI, LINK, AAVE, cbETH, USDT, rETH, LUSD, CRV, MKR, SNX, BAL, UNI, LDO, ENS, 1INCH, FRAX, GHO, RPL, sDAI, STG, KNC, FXS, crvUSD, PYUSD, weETH, osETH, USDe, ETHx, sUSDe, tBTC, cbBTC, USDS, rsETH
**Debt tokens tracked:**
All corresponding variable debt tokens for the above assets
**Collateral tokens tracked:**
USDT, WBTC, WETH, YFI, ZRX, UNI, AAVE, BAT, BUSD, DAI, ENJ, KNC, LINK, MANA, MKR, REN, SNX, SUSD, TUSD, USDC, CRV, GUSD, BAL, XSUSHI, RENFIL, RAI, AMPL, PAX, DPI, FRAX, FEI, stETH, ENS, UST, CVX, 1INCH, LUSD
### Compound
| Protocol | Version | Chain | Positions | Event history |
| - | - | - | - | - |
| Compound | V3 (Comet) | Ethereum | — | Supply, withdraw, borrow, repay, liquidation for the USDC, WETH, USDT, wstETH and USDS markets |
| Compound | V3 (Comet) | Base | — | Supply, withdraw, borrow, repay, liquidation for the USDC, USDbC, WETH and AERO markets |
| Compound | V2 | Ethereum | Collateral deposits | Borrow, repay, liquidation for all 20 markets |
Compound events contribute to the score since Andromeda 1.2 and are returned in `credit_events` with `feeds_score: true`. Compound V3 has no explicit borrow or repay events: a base-asset withdrawal beyond the supplied balance is recorded as a `borrow` and a base-asset supply against open debt as a `repay`. Compound V2 supply-side events are not collected, so its `supply` and `withdraw` counts are `null`.
**Collateral tokens tracked (positions):**
cETH, cUSDC, cDAI, cBAT, cUNI, cZRX, cUSDT, cCOMP, cWBTC
**Markets with event history:**
cBAT, cDAI, cETH, cREP, cUSDC, cUSDT, cWBTC (both), cZRX, cSAI, cUNI, cCOMP, cTUSD, cLINK, cMKR, cSUSHI, cAAVE, cYFI, cUSDP, cFEI
***
## Additional Data Sources
Beyond lending protocols, Cred Protocol analyzes additional on-chain data that contributes to the **Trust**, **Wallet Composition**, and **Interactions** scoring factors.
### Identity & Reputation
These attestations contribute to the **Trust** factor:
| Source | Description | Networks |
| - | - | - |
| ENS | Ethereum Name Service domain ownership | Ethereum |
| Basename | Base network name service (e.g., username.base.eth) | Base |
| Gitcoin Passport | Humanity verification (score ≥ 20 required) | Cross-chain |
| POAPs | Proof of Attendance Protocol event tokens | Ethereum, Base, Polygon |
| Goldfinch UID | Goldfinch Unique Identity verification | Ethereum |
| Anima Reputation | Synaps identity verification badges | BNB Chain, Polygon |
### Asset & Activity Data
These metrics contribute to the **Wallet Composition**, **Wallet Health**, and **Interactions** factors:
| Data Type | Description | Networks |
| - | - | - |
| Token Balances | ERC-20 token holdings and values | All supported chains |
| Stablecoin Holdings | USDT, USDC, DAI, and 15+ other stablecoins | All supported chains |
| NFT Holdings | Non-fungible token ownership | Ethereum, Base, Polygon |
| Transaction History | Total transactions, first/last activity | All supported chains |
| Transfer Activity | Token transfer frequency and patterns | All supported chains |
Cred Protocol tracks holdings in the following stablecoins:
USDT (Tether), USDC (USD Coin), DAI, FDUSD (First Digital USD), USDD, PYUSD (PayPal USD), TUSD (True USD), USDe (Ethena), FRAX, USDY (Ondo), USDB, USDJ, EURS (STASIS EURO), USTC (TerraClassicUSD), USDP (Pax Dollar), EURC, LUSD (Liquity USD), GUSD (Gemini Dollar), cUSD (Celo Dollar), sUSD, GHO
***
## Payment Networks (x402)
Cred Protocol supports [x402 payment authentication](/guides/authentication#x402-payment-authentication), allowing instant API access by paying per request with USDC — no account required. The following networks are supported for x402 payments:
| Network | Chain ID | Type | Token | Facilitator |
| - | - | - | - | - |
| Base | 8453 | Mainnet | USDC | Coinbase Developer Platform |
| Base Sepolia | 84532 | Testnet | USDC | Coinbase Developer Platform |
| SKALE | 1187947933 | Mainnet | Bridged USDC (SKALE Bridge) | dirtroad.dev |
| SKALE Testnet | 324705682 | Testnet | Bridged USDC (SKALE Bridge) | dirtroad.dev |
SKALE offers zero-gas transactions with sub-second finality, making it ideal for high-frequency micropayments. See the [authentication guide](/guides/authentication#x402-payment-authentication) for integration details.
***
## Coming Soon
We're continuously expanding coverage. Planned additions include:
Morpho, Spark, Euler, and other major lending markets
zkSync, Mantle, and emerging L2s
MakerDAO, Liquity, and collateralized debt positions
Perpetual and options protocol activity
Have a protocol or chain you'd like us to support? [Contact us](mailto:support@credprotocol.com) to request coverage.
# ERC-8004 Validation
Source: https://docs.credprotocol.com/erc-8004-validation
How the Cred Protocol Validator computes composite trust assessments for agents and submits them to the ERC-8004 Reputation Registry
Cred Protocol runs an independent **ERC-8004 validator** at `https://validator.credprotocol.com`. Given an agent's wallet, it computes a 0–100 **composite trust score** from three on-chain signals, pins the evidence to IPFS, and (optionally) submits the assessment on-chain to the ERC-8004 Reputation Registry on Base. This page is the methodology reference linked from the validator's [agent card](https://validator.credprotocol.com/.well-known/agent-card.json).
Methodology version **1.0**. Deployed on Base Mainnet (chain 8453); testable on Sepolia (11155111). Validator wallet: `0xc38947DA1EB4466D17d5C6c34a0f26Dbe803d107`.
## Composite score
| Signal | Weight | Source | Normalisation |
| - | - | - | - |
| **Credit** | 40% | Cred Score (300–1000) from `/api/v2/score` | Linear to 0–100 |
| **Sybil resistance** | 30% | Sybil score (0–100) from `/api/v2/identity/.../sybil` | Inverted — lower sybil risk contributes more |
| **Identity** | 30% | Count of verified attestations (ENS, Gitcoin Passport, POAPs, …) from `/api/v2/identity/.../attestations` | Capped and scaled to 0–100 |
`composite_score = 0.40·credit + 0.30·sybil + 0.30·identity`, rounded to an integer. If a signal is unavailable its weight is redistributed and the result is marked lower-`confidence`.
### Trust levels
| `trust_level` | `composite_score` |
| - | - |
| `untrusted` | 0–24 |
| `low` | 25–49 |
| `moderate` | 50–74 |
| `high` | 75–100 |
An agent with `composite_score ≥ 50` is reported as `verified: true`.
### Confidence
| `confidence` | Meaning |
| - | - |
| `full` | All 3 signals available |
| `partial` | 1–2 signals available |
| `minimal` | No signals available |
## Pipeline
1. **Fetch signals** — credit score, sybil score and identity attestations for the wallet (from the Cred Protocol API).
2. **Score** — weighted composite as above.
3. **Pin evidence** — the full breakdown, raw signal values, model versions and timestamp are pinned to IPFS (Pinata); the CID is returned as `evidence_cid`.
4. **Submit on-chain** (optional) — `giveFeedback` on the ERC-8004 Reputation Registry (and the Validation Registry where deployed) with the composite score and evidence URI. `tx_hash` / `tx_status` (`pending` → `submitted` → `confirmed` | `failed`) track it.
5. **Persist** — results are readable afterwards without recomputation.
## API
```bash theme={null}
# Run a validation (computes, pins evidence, submits on-chain) — $0.05, x402 or MPP
curl -X POST "https://validator.credprotocol.com/v1/validate/0xADDRESS?chain_id=8453&submit_onchain=true&submit_reputation=true"
# Read the latest stored validation for a wallet (free)
curl "https://validator.credprotocol.com/v1/validate/0xADDRESS/latest?chain_id=8453"
# Read by ERC-8004 agent ID (free)
curl "https://validator.credprotocol.com/v1/validate/agent/42?chain_id=8453"
# Which payment rails are enabled right now
curl https://validator.credprotocol.com/v1/payment-methods
```
Example response:
```json theme={null}
{
"agent_wallet": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"agent_id": 0,
"chain_id": 8453,
"composite_score": 75,
"verified": true,
"trust_level": "high",
"confidence": "partial",
"breakdown": {
"credit": { "raw_score": 772, "normalized": 67.4, "weight": 0.4 },
"sybil": { "raw_score": 16, "normalized": 84, "weight": 0.3 },
"identity": { "raw_attestations": null, "normalized": null, "weight": 0.3 }
},
"evidence_cid": "QmWB3dQsQxDALFhDKc5DzuvL62N4rYRQXMWEvh2rfJrdq4",
"evidence_url": "https://gateway.pinata.cloud/ipfs/QmWB3dQsQxDALFhDKc5DzuvL62N4rYRQXMWEvh2rfJrdq4",
"tx_hash": null,
"tx_status": "pending"
}
```
`POST /v1/validate/{address}` without payment returns **402** with x402 (`X-PAYMENT-REQUIRED`) and MPP (`WWW-Authenticate: Payment …`) challenges — see [Machine Payments](/guides/payments). Everything else above is free.
Full OpenAPI: [validator.credprotocol.com/docs](https://validator.credprotocol.com/docs).
## Related
* [Agents API](/api-reference/agents/agent-count) — discover agents in the ERC-8004 Identity Registry and read/submit reputation from the main API (`/api/v2/agents/*`).
* [MCP Services](/mcp-services/overview) — the same tools for MCP-native agents.
* [ERC-8004 specification](https://eips.ethereum.org/EIPS/eip-8004).
# FAQ
Source: https://docs.credprotocol.com/faq
Frequently asked questions about Cred Protocol
The answers to all your questions, at least the main ones! If you don't see an answer you're looking for, please ask in the [Cred Community Discord Server](https://discord.gg/MtDHUX9mD6). The Cred Protocol team and community members are ready to jump in and help.
***
## General
Cred Protocol uses on-chain analytics to quantify lending risk at scale. We correlate transaction history with the account owner's ability to fulfil obligations, specifically, repay loans.
Our machine learning credit score model is comprised of a set of features that have been selected to capture the holistic view of an account's on-chain risk. When combined, they create a predictive score that quantifies the creditworthiness of an account.
As the web3 ecosystem continues to grow and mature, we are always looking to add features that inform the model and improve the score. This process of continuous development is driven by our search for new data sources as they emerge, including new lending protocols, chains, and broader web3 projects.
Cred Scores range from 300 to 1000, similar to traditional credit scoring systems. The ranges are:
| Score | Range |
| - | - |
| 920-1000 | Excellent |
| 840-919 | Very Good |
| 750-839 | Good |
| 640-749 | Fair |
| 300-639 | Low |
Cred Protocol supports 10 blockchain networks:
* Ethereum
* Base
* Polygon
* Arbitrum
* Optimism
* Avalanche
* BNB Chain
* Celo
* Scroll
* Linea
See [Chains & Protocols](/chains-and-protocols) for full details on coverage.
We track borrowing and lending activity across major DeFi protocols including:
* Aave V2 and V3 (Ethereum, Base)
* Compound V3 (Ethereum, Base)
* Compound V2 (Ethereum)
Historical coverage also includes data from MakerDAO, Liquity, Radiant, Venus, and other protocols. See [Chains & Protocols](/chains-and-protocols) for the complete list.
***
## Credit Factors
Revealing the individual features that contribute to the score would potentially lead to people being able to 'game' the score and improve it without improving their underlying fundamental behaviours. In order to preserve the score's integrity while also providing transparency, the features are grouped into high-level 'Credit Factors'.
| Factor | Description | Impact |
| - | - | - |
| Borrowing History | Features linked to historical loan repayment performance | Most |
| Wallet Composition | Features linked to the asset breakdown within an account | High |
| Wallet Health | Features linked to the size and volume of activity within an account | Medium |
| Interactions | Features linked to the account's involvement in the web3 ecosystem | Medium |
| Trust | Features linked to trust and transparency | Low |
| New Credit | Features linked to recent and open credit history | Low |
To find out more about the credit factors, read [How Does It Work?](/how-it-works)
The easiest way to improve your score is to use lending protocols, take out loans and then repay them successfully. This demonstrates strong creditworthiness that will be reflected in a higher credit score.
However, there are ways to improve your credit score beyond interacting with lending protocols. The Credit Factors represent groups of features that contribute to the score—improving behaviour in any of these areas would have a positive impact on your score:
* **Build borrowing history**: Successfully repay loans on supported lending protocols
* **Maintain healthy positions**: Keep collateralization ratios well above liquidation thresholds
* **Diversify your portfolio**: Hold a mix of assets across different token types
* **Establish identity**: Connect attestations like ENS domains and Gitcoin Passport
* **Stay active**: Consistent, legitimate on-chain activity over time builds credibility
We are able to score any account with on-chain Ethereum mainnet transactions. If your account does not have any Ethereum mainnet transactions, it will not be given a score. Once your account has transactions, it will be possible to score it.
Similarly, rather than giving a brand new account with no transactions a score of 0, we will return 'Unscorable' as there are insufficient transactions to generate a meaningful score.
Scores are calculated in real-time based on current on-chain data. However, responses are cached for 5 minutes to optimize performance. This means your score reflects activity up to 5 minutes old.
***
## Multiple Wallets
We are able to provide a score to a single account on the basis of its transaction history. Similarly, if you have a number of accounts, we are able to amalgamate their combined transaction history to produce a single score for the entire group.
Use the batch scoring endpoint or pass multiple addresses to get an aggregated score across wallets.
Yes. The `/score/` endpoint accepts multiple addresses and returns an aggregated score that considers the combined activity across all provided wallets. This is useful for multi-sig wallets, DAO treasuries, or users who want their complete on-chain history considered.
***
## Security & Gaming Prevention
Our score is designed so that creditworthiness is informed by legitimate account activity. We have layers of on-chain analysis, fraud mitigation techniques, and a suite of Accountability APIs that surface consequences for bad actors. We don't publish exact details of our scoring algorithm to mitigate manipulation.
Using on-chain analytics, we're able to track transactions which pass between different accounts and back to the same account, helping to mitigate "self-dealing" which may inflate transaction volumes and aspects of the score.
Other aspects of the score are focused on Trust and evaluate multiple "proofs of humanity" ranging from verified credentials to fully KYC'd identities, which make it more difficult for an account to be abandoned or transferred.
Where appropriate, we verify identity. We use proprietary on-chain analytics to mitigate fraud and partner with leading identity verification and attestation protocols to support the credit decisioning process.
In addition, we're actively exploring privacy-preserving identity attestation approaches which combine security and pseudonymity.
***
## API & Integration
1. Sign up at [app.credprotocol.com](https://app.credprotocol.com)
2. Navigate to the Dashboard
3. Create a new API key in the Console section
See the [Quickstart guide](/quickstart) for detailed instructions.
**Sandbox endpoints** (`/api/v2/sandbox/...`) return deterministic mock data for testing. They're free to use, don't count against your quota, and respond instantly without making blockchain queries.
**Production endpoints** (`/api/v2/...`) return real credit scores and reports based on live on-chain data. These count against your API quota and take longer to respond as they query multiple data sources.
Use sandbox during development, then switch to production when you're ready to go live.
API usage is measured in Cred Units (CUs) based on your plan:
| Plan | Cred Units/Month | Price |
| - | - | - |
| Free | 1,000 | \$0 |
| Pro | 50,000 | \$249/mo |
| Enterprise | Unlimited | Custom |
Yes. All endpoints that accept an address parameter also accept ENS names (e.g., `vitalik.eth`). The ENS name is automatically resolved to its corresponding Ethereum address.
***
## Privacy & Data
Cred Protocol analyzes publicly available on-chain data. We don't store personal information beyond what's necessary for your account (email for authentication). The blockchain data we analyze is already public—we simply aggregate and analyze it to produce credit scores.
We don't sell or share your personal account information. Credit scores and reports are only accessible via authenticated API requests using your API key. The on-chain data we analyze is already publicly available on the blockchain.
Since scores are calculated from on-chain data, they reflect your actual blockchain activity. If you believe there's an error in how your activity is being interpreted, please reach out to us on [Discord](https://discord.gg/MtDHUX9mD6) or contact support.
***
## Still have questions?
Get help from the Cred Protocol team and community members
# Authentication Guide
Source: https://docs.credprotocol.com/guides/authentication
Complete guide to authenticating with the Cred Protocol API
## Overview
This guide covers everything you need to know about authenticating with the Cred Protocol API, from creating API keys to implementing secure authentication in your applications.
## Authentication Methods
The Cred Protocol API supports three authentication methods:
### 1. API Key Authentication (Recommended)
The standard authentication method using Bearer tokens. Every request includes your API key in the `Authorization` header. Usage is tracked against your subscription's Cred Unit balance.
```bash theme={null}
Authorization: Bearer YOUR_API_KEY
```
### 2. x402 Payment Authentication (No Account Required)
For instant access without creating an account, you can pay per request using USDC stablecoins via the [x402 protocol](https://docs.cdp.coinbase.com/x402/welcome). This enables accountless API access with immediate settlement.
```bash theme={null}
X-PAYMENT:
```
x402 payments support USDC on Base, SKALE and Tempo networks. Facilitators include the Coinbase Developer Platform (CDP) for Base and the dirtroad.dev facilitator for SKALE.
### 3. MPP — Machine Payments Protocol (No Account Required)
Also accountless: the `402` lists [MPP](https://mpp.dev) challenges in `WWW-Authenticate: Payment …` for **Tempo** (USDC), **Stripe** (USDC crypto deposit) and **Cred credit** (reputation-backed, settled later). Answer one and retry with the credential:
```bash theme={null}
Authorization: Payment
```
See the [Machine Payments guide](/guides/payments) for the challenge format, per-method payloads and receipts.
## Creating API Keys
### Step-by-Step Guide
Go to [app.credprotocol.com](https://app.credprotocol.com) and sign in to your account.
Click on **Dashboard** in the navigation menu.
Find the **API Keys** section in your dashboard.
Click **Create API Key** and enter a descriptive name for your key.
Use descriptive names like "Production Server", "Development", or "CI/CD Pipeline" to easily identify keys later.
Copy your API key immediately and store it securely. You won't be able to view the full key again.
Never share your API key or commit it to version control.
## Implementation Examples
### Environment Variables
Always store your API key in environment variables:
```bash .env theme={null}
CRED_API_KEY=your_api_key_here
```
```javascript Node.js theme={null}
// Load from environment
const API_KEY = process.env.CRED_API_KEY;
const response = await fetch('https://api.credprotocol.com/api/v2/score/address/vitalik.eth', {
headers: {
'Authorization': `Bearer ${API_KEY}`
}
});
```
```python Python theme={null}
import os
import requests
API_KEY = os.environ.get('CRED_API_KEY')
response = requests.get(
'https://api.credprotocol.com/api/v2/score/address/vitalik.eth',
headers={'Authorization': f'Bearer {API_KEY}'}
)
```
### Backend Proxy Pattern
For web applications, create a backend proxy to keep your API key secure:
```javascript Next.js API Route theme={null}
// pages/api/credit-score.js
export default async function handler(req, res) {
const { address } = req.query;
const response = await fetch(
`https://api.credprotocol.com/api/v2/score/address/${address}`,
{
headers: {
'Authorization': `Bearer ${process.env.CRED_API_KEY}`
}
}
);
const data = await response.json();
res.status(response.status).json(data);
}
```
```javascript Frontend theme={null}
// Call your backend proxy, not the Cred API directly
const response = await fetch(`/api/credit-score?address=${address}`);
const data = await response.json();
```
### SDK Pattern
Create a reusable client for your application:
```typescript theme={null}
// lib/cred-client.ts
class CredClient {
private apiKey: string;
private baseUrl = 'https://api.credprotocol.com';
constructor(apiKey: string) {
this.apiKey = apiKey;
}
private async request(endpoint: string) {
const response = await fetch(`${this.baseUrl}${endpoint}`, {
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error(`API Error: ${response.status}`);
}
return response.json();
}
async getScore(address: string) {
return this.request(`/api/v2/score/address/${address}`);
}
async getReport(address: string) {
return this.request(`/api/v2/report/address/${address}`);
}
async getIdentity(address: string) {
return this.request(`/api/v2/identity/address/${address}/attestations`);
}
}
// Usage
const cred = new CredClient(process.env.CRED_API_KEY!);
const score = await cred.getScore('vitalik.eth');
```
## Security Best Practices
API keys should never be included in frontend JavaScript, mobile apps, or anywhere they can be viewed by end users.
```javascript theme={null}
// ❌ NEVER do this
const response = await fetch('https://api.credprotocol.com/api/v2/score/address/vitalik.eth', {
headers: { 'Authorization': 'Bearer sk_live_abc123' }
});
// ✅ Call your backend instead
const response = await fetch('/api/credit-score?address=vitalik.eth');
```
Store API keys in environment variables, never in code:
* Use `.env` files for local development
* Use secret management services in production (AWS Secrets Manager, HashiCorp Vault, etc.)
* Never commit `.env` files to version control
Establish a key rotation schedule:
1. Create a new API key
2. Update your application to use the new key
3. Verify the new key works in production
4. Revoke the old key
Create different API keys for:
* Development
* Staging
* Production
This limits the impact if a key is compromised and makes auditing easier.
Regularly review your API usage in the Dashboard to:
* Detect unusual activity patterns
* Identify compromised keys
* Optimize your usage
## Troubleshooting
### Common Errors
```json theme={null}
{ "detail": "Invalid or missing API key" }
```
**Possible causes:**
* API key is missing from the request
* API key is malformed
* API key has been revoked
**Solutions:**
* Verify the `Authorization` header is present
* Check for typos in the API key
* Ensure you're using `Bearer ` prefix (with space)
* Create a new API key if needed
```json theme={null}
{ "detail": "Insufficient permissions" }
```
**Possible causes:**
* Accessing a feature not included in your plan
* Rate limit exceeded
**Solutions:**
* Check your plan limits in the Dashboard
* Upgrade your plan if needed
* Implement rate limiting in your application
### Testing Your API Key
Use this simple test to verify your API key is working:
```bash theme={null}
curl -X GET "https://api.credprotocol.com/users/me" \
-H "Authorization: Bearer YOUR_API_KEY"
```
A successful response confirms your key is valid:
```json theme={null}
{
"id": "uuid",
"email": "you@example.com",
"is_active": true
}
```
## x402 Payment Authentication
The x402 protocol enables instant API access by paying per request with USDC. This is ideal for:
* **Testing** the API before committing to a subscription
* **Low-volume usage** where a subscription isn't cost-effective
* **Programmatic access** from applications that can't store API keys
* **Instant access** without account creation or approval delays
### How It Works
1. Make a request without authentication
2. Receive a `402 Payment Required` response with payment details
3. Sign a USDC transfer authorization using your wallet
4. Retry the request with the signed payment in the `X-PAYMENT` header
5. Receive your API response (payment settles automatically)
### Payment Required Response
When you make a request without authentication, you'll receive:
```json theme={null}
{
"error": "authentication_required",
"message": "This endpoint requires authentication. Choose one of the following methods:",
"cred_units": 1,
"options": [
{
"method": "api_token",
"description": "Use an API token from your dashboard",
"header": "Authorization: Bearer YOUR_API_KEY",
"cost": "1 Cred Units",
"signup_url": "https://app.credprotocol.com/account/register"
},
{
"method": "x402_payment",
"description": "Pay per request with USDC (no account required)",
"header": "X-PAYMENT: ",
"price": "$0.01",
"currency": "USDC",
"network": "base",
"pay_to": "0x..."
}
]
}
```
The response includes an `X-PAYMENT-REQUIRED` header with base64-encoded payment requirements that x402-compatible wallets can process automatically.
### Pricing
x402 payments use the same pricing as Cred Units at **\$0.01 per Cred Unit**:
| Operation | Cred Units | x402 Price |
| - | - | - |
| Credit Score | 1 CU | \$0.01 |
| Full Report | 7 CUs | \$0.07 |
| Enhanced Report | 10 CUs | \$0.10 |
### Supported Networks
| Network | Chain ID | Type | USDC Token |
| - | - | - | - |
| Base | 8453 | Mainnet | USD Coin |
| Base Sepolia | 84532 | Testnet | USD Coin |
| SKALE Base | 1187947933 | Mainnet | Bridged USDC (SKALE Bridge) |
| SKALE Base Sepolia | 324705682 | Testnet | Bridged USDC (SKALE Bridge) |
SKALE offers zero-gas transactions with sub-second finality, making it ideal for high-frequency micropayments.
### Integration
For detailed integration instructions, see the [x402 documentation](https://docs.cdp.coinbase.com/x402/welcome) from Coinbase Developer Platform.
```javascript JavaScript (x402 SDK) theme={null}
import { x402Client } from 'x402';
const client = new x402Client({
wallet: yourWallet,
network: 'base'
});
// The client automatically handles 402 responses
const response = await client.fetch('https://api.credprotocol.com/api/v2/score/address/vitalik.eth');
const data = await response.json();
```
```python Python (Manual) theme={null}
import requests
import base64
# First request - will get 402
response = requests.get('https://api.credprotocol.com/api/v2/score/address/vitalik.eth')
if response.status_code == 402:
# Parse payment requirements from header
payment_required = response.headers.get('X-PAYMENT-REQUIRED')
requirements = base64.b64decode(payment_required)
# Sign payment with your wallet (implementation depends on your wallet)
signed_payment = sign_usdc_transfer(requirements)
# Retry with payment
response = requests.get(
'https://api.credprotocol.com/api/v2/score/address/vitalik.eth',
headers={'X-PAYMENT': signed_payment}
)
```
# Error Handling Guide
Source: https://docs.credprotocol.com/guides/error-handling
How to handle errors from the Cred Protocol API
## Overview
This guide covers how to handle errors from the Cred Protocol API, including common error codes, error response formats, and best practices for building resilient applications.
## Error Response Format
All API errors return a JSON response with a `detail` field:
```json theme={null}
{
"detail": "Error message describing the issue"
}
```
Some errors may include additional fields:
```json theme={null}
{
"detail": "Validation error",
"errors": [
{
"field": "address",
"message": "Invalid Ethereum address format"
}
]
}
```
## HTTP Status Codes
### Client Errors (4xx)
| Status | Name | Description |
| - | - | - |
| 400 | Bad Request | Invalid request parameters |
| 401 | Unauthorized | Missing or invalid API key |
| 402 | Payment Required | Authentication required (API key or x402 payment) |
| 403 | Forbidden | Insufficient permissions |
| 404 | Not Found | Resource not found |
| 422 | Unprocessable Entity | Validation error |
| 429 | Too Many Requests | Rate limit or credit limit exceeded |
### Server Errors (5xx)
| Status | Name | Description |
| - | - | - |
| 500 | Internal Server Error | Unexpected server error |
| 502 | Bad Gateway | Upstream service error |
| 503 | Service Unavailable | Service temporarily unavailable |
| 504 | Gateway Timeout | Request timed out |
## Common Errors and Solutions
```json theme={null}
{ "detail": "Invalid Ethereum address format" }
```
**Causes:**
* Malformed Ethereum address
* Invalid ENS name
* Missing required parameters
**Solutions:**
* Validate addresses before making requests
* Use checksummed addresses when possible
* Verify ENS names resolve correctly
```javascript theme={null}
import { isAddress } from 'viem';
function validateAddress(address) {
// Check if it's a valid address or ENS name
if (isAddress(address)) return true;
if (address.endsWith('.eth')) return true;
return false;
}
```
```json theme={null}
{ "detail": "Invalid or missing API key" }
```
**Causes:**
* Missing `Authorization` header
* Invalid API key format
* Revoked API key
**Solutions:**
* Ensure header format is `Bearer YOUR_API_KEY`
* Check for typos in the API key
* Verify the key hasn't been revoked
* Generate a new key if needed
```javascript theme={null}
// Correct format
headers: {
'Authorization': 'Bearer sk_live_abc123'
}
// Common mistakes
headers: {
'Authorization': 'sk_live_abc123' // Missing "Bearer "
'Api-Key': 'sk_live_abc123' // Wrong header name
}
```
```json theme={null}
{
"error": "authentication_required",
"message": "This endpoint requires authentication. Choose one of the following methods:",
"cred_units": 1,
"options": [
{
"method": "api_token",
"description": "Use an API token from your dashboard",
"header": "Authorization: Bearer YOUR_API_KEY",
"cost": "1 Cred Units"
},
{
"method": "x402_payment",
"description": "Pay per request with USDC (no account required)",
"price": "$0.01",
"currency": "USDC",
"networks": ["base", "base-sepolia", "skale-base", "skale-base-sepolia"]
}
]
}
```
**Causes:**
* No `Authorization` header or `X-PAYMENT` header provided
* This is an informational response, not an error
**Response Headers:**
* `X-PAYMENT-REQUIRED`: Base64-encoded payment requirements for x402-compatible clients (includes options for all enabled networks)
**Solutions:**
* Add an API key: `Authorization: Bearer YOUR_API_KEY`
* Or use x402 payment: Sign a USDC transfer and include in `X-PAYMENT` header
* Supported networks: Base, Base Sepolia, SKALE Base, SKALE Base Sepolia
* See [Authentication Guide](/guides/authentication) for details
```javascript theme={null}
async function handlePaymentRequired(response) {
if (response.status === 402) {
const data = await response.json();
// Option 1: Prompt user to authenticate
console.log('Authentication options:', data.options);
// Option 2: If using x402, process payment header
const paymentRequired = response.headers.get('X-PAYMENT-REQUIRED');
// ... sign and retry with X-PAYMENT header
}
}
```
```json theme={null}
{ "detail": "Insufficient permissions" }
```
**Causes:**
* Accessing a feature not in your plan
* Account restrictions
**Solutions:**
* Check your plan features in the Dashboard
* Upgrade your plan if needed
* Contact support for account issues
```json theme={null}
{ "detail": "Address not found or has no on-chain activity" }
```
**Causes:**
* Address has never been used on-chain
* ENS name doesn't exist
* Incorrect endpoint path
**Solutions:**
* Verify the address exists on Etherscan
* Check ENS name resolution
* Verify the endpoint URL
```javascript theme={null}
async function getScoreWithFallback(address) {
try {
const response = await fetch(`${API_URL}/api/v2/score/address/${address}`, {
headers: { 'Authorization': `Bearer ${API_KEY}` }
});
if (response.status === 404) {
// Address has no activity - return a default or handle gracefully
return { score: null, message: 'No on-chain activity found' };
}
return response.json();
} catch (error) {
throw error;
}
}
```
```json theme={null}
{
"detail": "Rate limit exceeded",
"retry_after": 60
}
```
**Causes:**
* Exceeded requests per minute limit
**Solutions:**
* Implement exponential backoff
* Cache responses where possible
* Wait for the `retry_after` period
See [Rate Limiting](#rate-limiting) below.
```json theme={null}
{
"detail": {
"error": "credit_limit_exceeded",
"message": "You have reached your monthly limit of 1,000 Cred Units. Your usage resets on day 15 of each month.",
"plan": "free",
"monthly_limit": 1000,
"used": 1000,
"remaining": 0,
"period_end": "2024-02-15T00:00:00+00:00",
"upgrade_url": "https://app.credprotocol.com/dashboard/billing"
}
}
```
**Causes:**
* Exceeded monthly Cred Unit allocation
**Response Fields:**
| Field | Description |
| - | - |
| `error` | Machine-readable error code |
| `message` | Human-readable explanation |
| `plan` | Current plan (free, pro, growth, enterprise) |
| `monthly_limit` | Total CUs allowed per month |
| `used` | CUs consumed this billing period |
| `remaining` | CUs remaining (0 when limit reached) |
| `period_end` | When credits reset (ISO 8601) |
| `upgrade_url` | Link to upgrade plan |
**Solutions:**
* Wait until `period_end` for credits to reset
* Upgrade your plan for more Cred Units
* Optimize API usage by caching responses
* Use summary endpoints (lower CU cost) where possible
```javascript theme={null}
async function handleCreditLimitError(response) {
const error = await response.json();
if (error.detail?.error === 'credit_limit_exceeded') {
const resetDate = new Date(error.detail.period_end);
console.log(`Credit limit reached. Resets on ${resetDate.toLocaleDateString()}`);
console.log(`Upgrade at: ${error.detail.upgrade_url}`);
// Optionally notify user or disable API calls until reset
return {
limitReached: true,
resetsAt: resetDate,
upgradeUrl: error.detail.upgrade_url
};
}
throw new Error(error.detail);
}
```
```json theme={null}
{ "detail": "Internal server error" }
```
**Causes:**
* Unexpected server-side error
* Temporary system issue
**Solutions:**
* Retry with exponential backoff
* Contact support if the issue persists
* Check [status page](https://credprotocol.instatus.com) for outages
## Implementing Error Handling
### Basic Error Handling
```javascript theme={null}
async function getScore(address) {
const response = await fetch(
`https://api.credprotocol.com/api/v2/score/address/${address}`,
{
headers: { 'Authorization': `Bearer ${API_KEY}` }
}
);
if (!response.ok) {
const error = await response.json();
switch (response.status) {
case 400:
throw new Error(`Invalid request: ${error.detail}`);
case 401:
throw new Error('Authentication failed. Check your API key.');
case 404:
throw new Error('Address not found or has no activity.');
case 429:
throw new Error('Rate limit exceeded. Please try again later.');
default:
throw new Error(`API error: ${error.detail}`);
}
}
return response.json();
}
```
### With Retry Logic
```javascript theme={null}
async function fetchWithRetry(url, options, maxRetries = 3) {
let lastError;
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await fetch(url, options);
// Don't retry client errors (except 429)
if (response.status >= 400 && response.status < 500 && response.status !== 429) {
const error = await response.json();
throw new Error(error.detail);
}
// Retry on rate limit
if (response.status === 429) {
const retryAfter = response.headers.get('Retry-After') || 60;
await sleep(retryAfter * 1000);
continue;
}
// Retry on server errors
if (response.status >= 500) {
const delay = Math.pow(2, attempt) * 1000; // Exponential backoff
await sleep(delay);
continue;
}
return response.json();
} catch (error) {
lastError = error;
// Only retry on network errors
if (error.name !== 'TypeError') throw error;
const delay = Math.pow(2, attempt) * 1000;
await sleep(delay);
}
}
throw lastError;
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
```
### Python Example
```python theme={null}
import time
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
def create_session():
session = requests.Session()
retries = Retry(
total=3,
backoff_factor=1,
status_forcelist=[500, 502, 503, 504],
allowed_methods=["GET"]
)
adapter = HTTPAdapter(max_retries=retries)
session.mount("https://", adapter)
return session
def get_score(address):
session = create_session()
response = session.get(
f'https://api.credprotocol.com/api/v2/score/address/{address}',
headers={'Authorization': f'Bearer {API_KEY}'}
)
if response.status_code == 429:
retry_after = int(response.headers.get('Retry-After', 60))
time.sleep(retry_after)
return get_score(address) # Retry once
response.raise_for_status()
return response.json()
```
## Rate Limiting
### Understanding Usage Limits
API usage is measured in Cred Units (CUs) based on your plan:
| Plan | Cred Units/Month | Price |
| - | - | - |
| Free | 1,000 | \$0 |
| Pro | 50,000 | \$249/mo |
| Enterprise | Unlimited | Custom |
### Handling Rate Limits
```javascript theme={null}
class RateLimitedClient {
constructor(apiKey, requestsPerMinute = 10) {
this.apiKey = apiKey;
this.requestsPerMinute = requestsPerMinute;
this.requestTimes = [];
}
async request(endpoint) {
// Wait if we've hit the rate limit
await this.waitForRateLimit();
this.requestTimes.push(Date.now());
const response = await fetch(
`https://api.credprotocol.com${endpoint}`,
{
headers: { 'Authorization': `Bearer ${this.apiKey}` }
}
);
if (response.status === 429) {
const retryAfter = parseInt(response.headers.get('Retry-After') || '60');
await this.sleep(retryAfter * 1000);
return this.request(endpoint); // Retry
}
return response.json();
}
async waitForRateLimit() {
const now = Date.now();
const oneMinuteAgo = now - 60000;
// Remove old request times
this.requestTimes = this.requestTimes.filter(t => t > oneMinuteAgo);
if (this.requestTimes.length >= this.requestsPerMinute) {
const oldestRequest = this.requestTimes[0];
const waitTime = oldestRequest + 60000 - now;
await this.sleep(waitTime);
}
}
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
```
## Best Practices
Validate addresses and parameters before making API calls
Implement exponential backoff for transient errors
Cache successful responses to reduce API calls
Log errors with context for debugging
### Logging Example
```javascript theme={null}
async function getScore(address) {
try {
const data = await fetchScore(address);
return data;
} catch (error) {
console.error('Cred API Error:', {
address,
error: error.message,
timestamp: new Date().toISOString()
});
// Re-throw or handle gracefully
throw error;
}
}
```
# Machine Payments (x402 & MPP)
Source: https://docs.credprotocol.com/guides/payments
Pay per request — no account required — with x402 (USDC on Base/SKALE/Tempo) or the Machine Payments Protocol (Tempo, Stripe crypto deposits, or reputation-backed Cred credit)
Every paid Cred Protocol endpoint is **machine payable**. An agent that calls a paid endpoint with no credentials gets back a `402 Payment Required` that advertises three ways to pay; it picks one, attaches the payment to the retry, and gets the data. Nothing to sign up for.
Metered against a plan. `Authorization: Bearer `
USDC on Base, SKALE or Tempo. `X-PAYMENT: `
Tempo, Stripe crypto deposit, or Cred credit. `Authorization: Payment `
## Pricing
Everything is priced in **Cred Units (CU)**, 1 CU = **\$0.01**. The same price applies whether you pay with an API key, x402 or MPP.
| Endpoint | Method | CU | Price |
| - | - | - | - |
| `/api/v2/score/address/{address}` | GET | 1 | \$0.01 |
| `/api/v2/score/address/{address}` (enhanced, off-chain data) | POST | 3 | \$0.03 |
| `/api/v2/score/` (aggregated) · `/api/v2/score/batch/` | GET | 1 per address | \$0.01/addr |
| `/api/v2/report/address/{address}` | GET | 7 | \$0.07 |
| `/api/v2/report/address/{address}` (enhanced) | POST | 10 | \$0.10 |
| `/api/v2/report/` (aggregated) | GET | 7 | \$0.07 |
| `/api/v2/report/address/{address}/summary` | GET | 5 | \$0.05 |
| `/api/v2/report/address/{address}/chain/{chain_id}` | GET | 3 | \$0.03 |
| `/api/v2/report/address/{address}/chain/{chain_id}/summary` | GET | 1 | \$0.01 |
| `/api/v2/report/address/{address}/total/usd` (+ `/aggregate`) | GET | 4 | \$0.04 |
| `/api/v2/report/address/{address}/chain/{chain_id}/total/usd` | GET | 2 | \$0.02 |
| `/api/v2/identity/address/{address}/attestations` | GET | 1 | \$0.01 |
| `/api/v2/identity/address/{address}/sybil` | GET | 3 | \$0.03 |
| `/api/v2/agents/{agent_id}/reputation` (submit on-chain feedback) | POST | 10 | \$0.10 |
| `/api/v2/agents/{agent_id}/reputation/summary` | GET | 1 | \$0.01 |
| **Validator** `https://validator.credprotocol.com/v1/validate/{address}` | POST | — | \$0.05 |
Agent-registry reads (`/api/v2/agents`, `/agents/count`, `/agents/search`, `/agents/{id}`) and `/api/v2/health` are free. The `/mcp/*` REST endpoints and MCP tools use the same prices — see [MCP Services](/mcp-services/overview) and `GET https://api.credprotocol.com/mcp/tools`.
## The 402 response
Call any paid endpoint without credentials:
```bash theme={null}
curl -i https://api.credprotocol.com/api/v2/score/address/vitalik.eth
```
```http theme={null}
HTTP/2 402
X-Payment-Methods: x402,tempo,stripe,cred
X-PAYMENT-REQUIRED:
WWW-Authenticate: Payment id="ch_9a39…", realm="api.credprotocol.com", method="tempo", intent="charge", request="",
Payment id="ch_1f86…", realm="api.credprotocol.com", method="cred", intent="credit", request="",
Payment id="ch_4ca5…", realm="api.credprotocol.com", method="stripe", intent="charge", request=""
```
```json theme={null}
{
"detail": {
"error": "authentication_required",
"cred_units": 1,
"options": [
{ "method": "api_token", "header": "Authorization: Bearer YOUR_API_KEY", "cost": "1 Cred Units" },
{ "method": "x402_payment", "header": "X-PAYMENT: ", "price": "$0.01", "currency": "USDC" },
{ "method": "mpp", "header": "Authorization: Payment ", "price": "$0.01", "spec": "https://mpp.dev" }
]
}
}
```
The body is human/LLM readable; the headers are what payment SDKs consume. Pick whichever rail your agent supports and retry.
## x402
[x402](https://docs.cdp.coinbase.com/x402/welcome) is a one-round-trip USDC micropayment. The `X-PAYMENT-REQUIRED` header carries base64 `PaymentRequirements` (scheme `exact`, price in USDC, `payTo` address, one entry per accepted network). Sign a USDC transfer authorization with your wallet and retry with it in `X-PAYMENT`; the payment settles through the facilitator during the request and the response includes `X-Payment-Transaction` / `X-Payment-Network`.
**Networks:** Base (8453), Base Sepolia (84532), SKALE Base (1187947933), SKALE Base Sepolia (324705682), and Tempo. SKALE is gasless with sub-second finality.
```javascript JavaScript (x402 SDK) theme={null}
import { x402Client } from 'x402';
const client = new x402Client({ wallet, network: 'base' });
// Automatically answers the 402 and retries with X-PAYMENT
const res = await client.fetch(
'https://api.credprotocol.com/api/v2/score/address/vitalik.eth'
);
console.log(await res.json());
```
```python Python (manual) theme={null}
import base64, requests
url = "https://api.credprotocol.com/api/v2/score/address/vitalik.eth"
r = requests.get(url)
if r.status_code == 402:
requirements = base64.b64decode(r.headers["X-PAYMENT-REQUIRED"])
signed = sign_usdc_transfer(requirements) # your wallet
r = requests.get(url, headers={"X-PAYMENT": signed})
print(r.json(), r.headers.get("X-Payment-Transaction"))
```
Full details, including per-network USDC contracts, are in the [x402 section of the Authentication guide](/guides/authentication#x402-payment-authentication). Try it interactively at [credprotocol.com/try](https://credprotocol.com/try).
## MPP (Machine Payments Protocol)
[MPP](https://mpp.dev) uses standard HTTP auth semantics: the server lists **challenges** in `WWW-Authenticate: Payment …`, the client fulfils one and sends the resulting **credential** in `Authorization: Payment `, and the server returns a **receipt** in the `Payment-Receipt` response header.
Each challenge has an `id`, a `method`, an `intent` (`charge` or `credit`) and a base64url `request` describing what to pay:
| method | intent | `request` (decoded) | How you pay |
| - | - | - | - |
| `tempo` | charge | `{"amount":"10000","currency":"","recipient":"0xD750…","methodDetails":{"chainId":4217}}` | Send USDC (6 decimals) on Tempo (chain 4217) to `recipient`. Credential payload: the signed transaction (pull) or the tx hash (push). |
| `stripe` | charge | `{"amount":"0.01","currency":"usd","stripeDetails":{"networkId":"tempo","paymentMethodTypes":["crypto"],"depositAddress":"0x5e8f…","paymentIntentId":"pi_…"}}` | Send USDC on Tempo to the Stripe crypto `depositAddress` (a PaymentIntent is pre-created for you). Credential payload: `{"txHash": "...", "paymentIntentId": "pi_…"}`. |
| `cred` | credit | `{"amount":"0.01","currency":"usd","recipient":"0xD750…","minCredScore":640,"creditTerms":"session"}` | No transfer up front. Prove wallet ownership with an EIP-712 signature; wallets with a Cred Score ≥ 640 get session credit, settled later via an EIP-3009 `transferWithAuthorization` pull. |
The credential you send back is:
```json theme={null}
{
"challenge": { "...the challenge object you are answering, verbatim..." },
"source": "0xYourWallet",
"payload": { "...method-specific, see table..." }
}
```
base64url-encoded into `Authorization: Payment `.
```python Python (Cred credit — reputation-backed, no pre-funding) theme={null}
import base64, json, requests, re
URL = "https://api.credprotocol.com/api/v2/score/address/vitalik.eth"
r = requests.get(URL) # 402
challenges = parse_www_authenticate(r.headers["WWW-Authenticate"])
ch = next(c for c in challenges if c["method"] == "cred")
payload = {
"walletAddress": WALLET,
"walletSignature": sign_eip712_ownership(WALLET, ch), # your wallet
"timestamp": now_iso(),
# optional: "eip3009Authorization": {...} for pull-payment settlement
}
credential = base64.urlsafe_b64encode(json.dumps(
{"challenge": ch, "source": WALLET, "payload": payload}
).encode()).rstrip(b"=").decode()
r = requests.get(URL, headers={"Authorization": f"Payment {credential}"})
print(r.status_code, r.json())
print("receipt:", r.headers.get("Payment-Receipt"))
```
```bash cURL (Tempo push — pay first, then present the tx hash) theme={null}
# 1. Read the tempo challenge from the 402
curl -si https://api.credprotocol.com/api/v2/score/address/vitalik.eth | grep -i www-authenticate
# 2. Send 10000 units of USDC on Tempo (chainId 4217) to the recipient in the challenge
# 3. Retry with the credential (challenge + payload with the tx hash), base64url-encoded
curl https://api.credprotocol.com/api/v2/score/address/vitalik.eth \
-H "Authorization: Payment $CREDENTIAL"
```
**Receipts.** Successful paid responses include `Payment-Receipt: ` decoding to `{"status":"success","challengeId":"ch_…","method":"tempo","reference":"","timestamp":"…"}`.
**MPP over MCP.** The MCP server (`https://api.credprotocol.com/mcp`) speaks the MPP MCP transport: a paid tool called without credentials returns JSON-RPC error `-32042` whose `data` is the challenge; put the credential in `_meta["org.paymentauth/credential"]` on the retried `tools/call` and the receipt comes back in the result's `_meta["org.paymentauth/receipt"]`. See [MCP Services](/mcp-services/overview).
## Validator (ERC-8004 trust assessments)
`POST https://validator.credprotocol.com/v1/validate/{address}` is \$0.05 and accepts x402 (USDC on Base) and Cred credit; `GET /v1/payment-methods` lists what's currently enabled. See [ERC-8004 Validation](/erc-8004-validation).
## Choosing a rail
* **You already have a plan** → API key. Simplest, and usage shows up in the [console](https://app.credprotocol.com/dashboard/console).
* **Autonomous agent with a funded wallet** → x402 (Base/SKALE/Tempo) or MPP `tempo`. One request, settles inline.
* **Agent that can't hold crypto** → MPP `stripe` (USDC deposit on Tempo via a Stripe-managed address).
* **Agent with on-chain reputation but no float** → MPP `cred`: a Cred Score ≥ 640 unlocks session credit, settled afterwards.
Errors: `402` = no/insufficient payment (body explains); `401` = credentials present but invalid; `429` = rate limited. See [Error Handling](/guides/error-handling).
# Sandbox Testing Guide
Source: https://docs.credprotocol.com/guides/sandbox-testing
How to use sandbox endpoints for development and testing
## Overview
The Cred Protocol sandbox provides mock API endpoints for development and testing. Use the sandbox to build and test your integration without consuming your API quota or waiting for real blockchain queries.
## Why Use the Sandbox?
Sandbox requests don't count against your API quota
No blockchain queries means instant responses
Deterministic responses for reliable testing
Test without relying on blockchain data availability
## Sandbox Endpoints
| Sandbox Endpoint | Production Equivalent |
| - | - |
| `/api/v2/sandbox/score/address/{address}` | `/api/v2/score/address/{address}` |
| `/api/v2/sandbox/score/batch/` | `/api/v2/score/batch/` |
| `/api/v2/sandbox/report/address/{address}` | `/api/v2/report/address/{address}` |
## Getting Started
### 1. Use Sandbox During Development
Simply add `/sandbox` before the endpoint path:
```bash cURL theme={null}
# Sandbox (for development)
curl "https://api.credprotocol.com/api/v2/sandbox/score/address/0x123..." \
-H "Authorization: Bearer YOUR_API_KEY"
# Production (for live data)
curl "https://api.credprotocol.com/api/v2/score/address/0x123..." \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const BASE_URL = 'https://api.credprotocol.com';
// Use an environment variable to switch between sandbox and production
const useSandbox = process.env.NODE_ENV === 'development';
async function getScore(address) {
const endpoint = useSandbox
? `/api/v2/sandbox/score/address/${address}`
: `/api/v2/score/address/${address}`;
const response = await fetch(`${BASE_URL}${endpoint}`, {
headers: { 'Authorization': `Bearer ${API_KEY}` }
});
return response.json();
}
```
```python Python theme={null}
import os
import requests
BASE_URL = 'https://api.credprotocol.com'
USE_SANDBOX = os.environ.get('ENVIRONMENT') == 'development'
def get_score(address):
endpoint = f'/api/v2/sandbox/score/address/{address}' if USE_SANDBOX else f'/api/v2/score/address/{address}'
response = requests.get(
f'{BASE_URL}{endpoint}',
headers={'Authorization': f'Bearer {API_KEY}'}
)
return response.json()
```
### 2. Sandbox Response Format
Sandbox responses use the same format as production:
```json theme={null}
{
"address": "0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17",
"score": 726,
"decile": 8,
"range": "good",
"model_version": "andromeda_1.1",
"timestamp": "2024-01-15T10:30:00Z"
}
```
Sandbox responses are deterministic - the same address always returns the same mock score. This makes testing reliable and reproducible.
## Test Scenarios
### Testing Different Score Ranges
Use these test addresses to simulate different credit scores:
| Address | Mock Score | Range |
| - | - | - |
| `0x0000000000000000000000000000000000000001` | 935+ | excellent |
| `0x0000000000000000000000000000000000000002` | 770-858 | good |
| `0x0000000000000000000000000000000000000003` | 655-769 | fair |
| `0x0000000000000000000000000000000000000004` | 300-654 | low |
### Testing Your UI
Use the sandbox to test how your UI handles different scenarios:
```javascript theme={null}
// Test different score ranges
const testAddresses = [
'0x0000000000000000000000000000000000000001', // excellent
'0x0000000000000000000000000000000000000002', // good
'0x0000000000000000000000000000000000000003', // fair
'0x0000000000000000000000000000000000000004', // low
];
for (const address of testAddresses) {
const score = await getScore(address);
console.log(`${address}: ${score.score} (${score.range})`);
}
```
## CI/CD Integration
### Automated Testing
Use the sandbox in your test suite for consistent, fast tests:
```javascript theme={null}
// __tests__/cred-api.test.js
describe('Cred API Integration', () => {
const API_URL = 'https://api.credprotocol.com';
const API_KEY = process.env.CRED_API_KEY;
test('should return credit score for valid address', async () => {
const response = await fetch(
`${API_URL}/api/v2/sandbox/score/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17`,
{ headers: { 'Authorization': `Bearer ${API_KEY}` } }
);
const data = await response.json();
expect(response.status).toBe(200);
expect(data.score).toBeGreaterThanOrEqual(300);
expect(data.score).toBeLessThanOrEqual(1000);
expect(data.decile).toBeGreaterThanOrEqual(1);
expect(data.decile).toBeLessThanOrEqual(10);
});
test('should return valid range', async () => {
const response = await fetch(
`${API_URL}/api/v2/sandbox/score/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17`,
{ headers: { 'Authorization': `Bearer ${API_KEY}` } }
);
const data = await response.json();
expect(['low', 'fair', 'good', 'very_good', 'excellent']).toContain(data.range);
});
});
```
### GitHub Actions Example
```yaml theme={null}
# .github/workflows/test.yml
name: API Integration Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: npm ci
- name: Run tests
env:
CRED_API_KEY: ${{ secrets.CRED_API_KEY }}
run: npm test
```
## Best Practices
Configure your application to automatically use sandbox in development:
```javascript theme={null}
const CRED_BASE_PATH = process.env.NODE_ENV === 'production'
? '/api/v2'
: '/api/v2/sandbox';
```
Add a check to ensure you're using the correct endpoint in production:
```javascript theme={null}
const config = {
useSandbox: process.env.NODE_ENV !== 'production',
baseUrl: 'https://api.credprotocol.com'
};
async function getScore(address) {
const path = config.useSandbox
? `/api/v2/sandbox/score/address/${address}`
: `/api/v2/score/address/${address}`;
const response = await fetch(`${config.baseUrl}${path}`, {
headers: { 'Authorization': `Bearer ${API_KEY}` }
});
return response.json();
}
```
The sandbox returns consistent error responses too:
* Invalid addresses return 400 errors
* Missing auth returns 401 errors
* Use these to test your error handling
Never hardcode `/sandbox/` in production code:
```javascript theme={null}
// ❌ Bad
const url = 'https://api.credprotocol.com/api/v2/sandbox/score/...';
// ✅ Good
const basePath = config.useSandbox ? '/api/v2/sandbox' : '/api/v2';
const url = `https://api.credprotocol.com${basePath}/score/...`;
```
## Transitioning to Production
When you're ready to go live:
Ensure all features work correctly with sandbox data
Set your environment to production mode
Make a few test requests to verify production access
Check your Dashboard to ensure requests are being tracked correctly
# Monitoring Webhooks
Source: https://docs.credprotocol.com/guides/webhooks
Receive signed HTTPS notifications when on-chain activity happens on addresses you watch
## Overview
Monitoring webhooks push signed HTTPS notifications to your endpoint when on-chain activity happens on addresses you watch. Configure them in the [developer console](https://app.credprotocol.com/dashboard/webhooks): choose an endpoint URL, the event types you care about, the chains to watch, and up to 25 addresses per webhook.
Watched addresses are polled roughly every 5 minutes, so expect a delivery within a few minutes of the on-chain event.
## Event Types
| Event | Fires when |
| - | - |
| `transfer` | An ERC20 token moves to or from a watched address |
| `mint` | A token is minted to a watched address (transfer from the zero address) |
| `burn` | A token is burned from a watched address (transfer to the zero address) |
| `transaction` | Native currency (ETH, POL, BNB, ...) moves to or from a watched address |
| `approval` | A watched address grants an ERC20 allowance to a spender |
Protocol-level events (swaps, staking, liquidations) are not yet supported.
## Supported Chains
Ethereum, Base, Optimism, Arbitrum, Polygon, BNB Chain, Avalanche, Scroll, Linea, and Celo. Chain values in payloads use lowercase slugs (`ethereum`, `base`, `bsc`, ...).
## Endpoint Requirements
* **HTTPS only**, on port 443 or 8443, resolving to a public IP address (private and internal hosts are rejected, both at registration and at delivery time).
* Respond with any **2xx status within 10 seconds**. Anything else counts as a failed delivery.
* At most **10 webhooks per user** and **25 addresses per webhook**.
## Delivery Payload
Every delivery is a `POST` with a JSON body:
```json theme={null}
{
"event_type": "transfer",
"blockchain": "base",
"address": "0xab5801a7d398351b8be11c439e05c5b3259aec9b",
"transaction_hash": "0x9f1a...",
"timestamp": "2026-08-20T17:04:11.482919+00:00",
"data": {
"from": "0x1234...",
"to": "0xab58...",
"direction": "in",
"contract_address": "0x8335...",
"token_symbol": "USDC",
"token_decimal": "6",
"value": "25000000",
"block_number": 34118260
}
}
```
The `data` object varies by event type: `transaction` events carry `value_wei`, `approval` events carry `spender` and the raw allowance `value`, and token events carry the fields shown above.
### Headers
| Header | Meaning |
| - | - |
| `X-Webhook-Signature` | `t=,v1=` — see verification below |
| `X-Event-Type` | The event type, e.g. `transfer` |
| `X-Webhook-Id` | The webhook's ID |
| `X-Webhook-Delivery-Id` | Unique per delivery — use it for idempotency (retries reuse the ID) |
| `X-Webhook-Timestamp` | Same unix timestamp as `t` in the signature header |
## Verifying Signatures
Each webhook has a signing secret, shown once when you create it. The signature is HMAC-SHA256 over the string `{t}.{raw_body}`, where `t` is the timestamp from the signature header and `raw_body` is the exact request body bytes. Always verify the signature **and** reject stale timestamps (5 minutes is a reasonable tolerance) to prevent replays.
```python Python theme={null}
import hashlib
import hmac
import time
def verify_webhook(secret: str, signature_header: str, raw_body: bytes,
tolerance_seconds: int = 300) -> bool:
parts = dict(p.split("=", 1) for p in signature_header.split(","))
timestamp, signature = int(parts["t"]), parts["v1"]
if abs(time.time() - timestamp) > tolerance_seconds:
return False # stale — possible replay
expected = hmac.new(
secret.encode(), f"{timestamp}.".encode() + raw_body, hashlib.sha256
).hexdigest()
return hmac.compare_digest(expected, signature)
```
```typescript TypeScript theme={null}
import { createHmac, timingSafeEqual } from "node:crypto";
function verifyWebhook(
secret: string,
signatureHeader: string,
rawBody: string,
toleranceSeconds = 300,
): boolean {
const parts = Object.fromEntries(
signatureHeader.split(",").map((p) => p.split("=", 2) as [string, string]),
);
const timestamp = Number(parts.t);
if (Math.abs(Date.now() / 1000 - timestamp) > toleranceSeconds) return false;
const expected = createHmac("sha256", secret)
.update(`${timestamp}.${rawBody}`)
.digest("hex");
return timingSafeEqual(Buffer.from(expected), Buffer.from(parts.v1));
}
```
Compute the HMAC over the **raw request body bytes**, not a re-serialized copy of the parsed JSON — serialization differences will break verification.
## Retries and Failure Handling
* Failed deliveries are retried up to 4 times with increasing backoff: **1 minute, 5 minutes, 30 minutes, then 2 hours**.
* Every attempt is recorded in the delivery history, visible in the console next to each webhook.
* After **10 consecutive failed attempts** (across deliveries), the webhook is automatically disabled. Re-enable it from the console once your endpoint is healthy — the failure counter resets on the first successful delivery.
## Testing
Use the **test button** in the console to send a synthetic `test` event through the real delivery pipeline. Test deliveries appear in the delivery history but are never retried and don't count toward auto-disable.
When a new address is added to a webhook, monitoring starts from the current chain head — historical activity is not backfilled.
# How Does It Work?
Source: https://docs.credprotocol.com/how-it-works
Understanding how Cred Protocol calculates on-chain credit scores
## Credit Score Methodology
Cred Protocol analyzes on-chain data to generate credit scores that reflect the financial behavior and trustworthiness of blockchain addresses. Our scoring model evaluates multiple dimensions of wallet activity to produce a comprehensive assessment.
Scores range from 300 to 1000, similar to traditional credit scoring systems. Higher scores indicate stronger on-chain financial behavior.
## Credit Factors
Our scoring model considers several key factors when evaluating an address. Each factor contributes to the overall score based on its relevance to creditworthiness.
Track record of borrowing and repayment across DeFi protocols
Diversity and distribution of assets held in the wallet
Current financial standing and risk exposure
Protocol usage patterns and on-chain activity
Identity attestations and reputation signals
Recent borrowing activity and credit utilization changes
***
## Factor Breakdown
### Borrowing History
Your borrowing history reflects how you've managed debt obligations on-chain. This factor examines your track record with lending protocols to understand your repayment behavior.
* Loan repayment patterns across DeFi protocols
* Historical liquidation events
* Duration and consistency of borrowing activity
* Repayment timing relative to loan terms
A strong borrowing history demonstrates responsible credit management. Addresses with consistent repayment behavior and no liquidations signal lower risk to potential lenders.
### Wallet Composition
Wallet composition evaluates the structure and diversity of your on-chain portfolio. A well-balanced portfolio suggests financial sophistication and stability.
* Asset diversity across token types
* Balance distribution between different protocols
* Stablecoin holdings relative to volatile assets
* Long-term holdings versus trading activity
Diversified portfolios indicate thoughtful financial planning. Addresses concentrated in single assets or highly volatile positions may represent higher risk profiles.
### Wallet Health
Wallet health measures your current financial standing and risk exposure across DeFi positions. This provides a real-time view of your creditworthiness.
* Current collateralization ratios
* Health factors across lending protocols
* Distance from liquidation thresholds
* Overall leverage exposure
Healthy positions with conservative collateralization demonstrate prudent risk management. Addresses operating close to liquidation thresholds present higher risk profiles.
### Interactions
Interactions capture your engagement with the broader blockchain ecosystem. Active participation in reputable protocols contributes positively to your score.
* Protocol diversity and usage breadth
* Transaction frequency and patterns
* Smart contract interaction history
* Ecosystem participation across chains
Meaningful on-chain activity demonstrates genuine ecosystem participation. Addresses with rich interaction histories across trusted protocols establish stronger credibility.
### Trust
Trust signals come from identity attestations and reputation mechanisms that verify the legitimacy and standing of an address.
* ENS domain ownership and history
* Gitcoin Passport score and stamps
* POAP attendance tokens
* Other on-chain attestations
Identity attestations provide social proof and verification. Addresses with established on-chain identities and community participation are more trustworthy.
### New Credit
New credit examines recent borrowing activity to identify changes in credit-seeking behavior. Sudden increases in borrowing may indicate changing risk profiles.
* Recent loan originations
* Changes in credit utilization
* New protocol onboarding
* Velocity of borrowing activity
Stable, gradual credit usage indicates consistent financial behavior. Rapid increases in borrowing activity may signal increased risk.
***
## Feature Selection
Our scoring model uses machine learning to identify the most predictive signals from on-chain data. The feature selection process ensures that scores are:
Features are selected based on their statistical correlation with creditworthy behavior, not arbitrary assumptions.
The model considers complex patterns that are difficult to artificially manipulate, ensuring authentic assessment.
Feature weights are regularly updated based on new data and observed outcomes to maintain accuracy.
Attempting to artificially inflate your score through synthetic activity is detectable and may negatively impact your assessment.
***
## Multi-Chain Analysis
Cred Protocol aggregates data across multiple blockchain networks to build a complete picture of on-chain activity.
| Network | Data Sources |
| - | - |
| Ethereum | Lending, DEX, NFTs, Identity |
| Polygon | Lending, DEX activity |
| Arbitrum | DeFi positions |
| Optimism | Protocol interactions |
| Base | Ecosystem activity |
| + More | Additional L2s and sidechains |
***
## Improving Your Score
While we don't reveal specific weights to prevent gaming, genuine positive financial behavior is always rewarded:
Keep collateralization ratios well above minimum thresholds
Consistent activity over time establishes stronger track records
Spread activity across reputable protocols and asset types
Connect identity attestations like ENS and Gitcoin Passport
***
## Next Steps
Request a credit score for any Ethereum address
Generate a comprehensive credit report with detailed breakdowns
# Introduction
Source: https://docs.credprotocol.com/introduction
Build trust in Web3 with on-chain credit intelligence
## Welcome to Cred Protocol
Cred Protocol provides credit scoring and reporting APIs for blockchain addresses. Our APIs enable developers to assess the creditworthiness of Ethereum addresses using on-chain data analysis.
### What You Can Build
Get credit scores (300-1000) for any Ethereum address based on on-chain activity
Generate comprehensive credit reports with asset balances, NFTs, and DeFi positions
Verify identity attestations including ENS, Gitcoin Passport, and POAPs
Test your integration with mock data before going live
## Key Features
Our APIs aggregate data across 10+ blockchain networks including Ethereum, Polygon, Arbitrum, Optimism, Base, and more.
Credit scores are calculated using the Andromeda model with local computation for fast, accurate results.
Access wallet balances, transaction history, DeFi positions, NFT holdings, and identity attestations.
RESTful APIs with clear documentation, sandbox environment, and SDKs for popular languages.
## Score Ranges
Cred Protocol scores range from 300 to 1000, similar to traditional credit scores:
| Score Range | Range |
| - | - |
| 920-1000 | Excellent |
| 840-919 | Very Good |
| 750-839 | Good |
| 640-749 | Fair |
| 300-639 | Low |
## Getting Started
Sign up at [app.credprotocol.com](https://app.credprotocol.com) to create your developer account.
Navigate to the Dashboard and generate an API key for authentication.
Use the [Quickstart Guide](/quickstart) to make your first API call.
Check out the [API Reference](/api-reference/overview) for detailed endpoint documentation.
## Need Help?
Test API endpoints directly in your browser
Check out our open-source repositories
# Agent Skill
Source: https://docs.credprotocol.com/mcp-services/agent-skill
Instructions that AI agents receive when connecting to the Cred Protocol MCP server
# Agent Skill Instructions
When an AI agent connects to the Cred Protocol MCP server, it automatically receives the following instructions during initialization. These guide the agent on tool selection, score interpretation, and best practices.
These instructions are delivered via the MCP `instructions` field — no extra configuration needed. You can also use this page as a reference when building custom agents.
***
## When to Use These Tools
Use Cred Protocol tools when users ask about:
* Wallet creditworthiness, trust, or risk assessment
* Financial health or portfolio analysis of an Ethereum address
* Identity verification or attestation checks
* Sybil detection (is this a real person or a bot?)
* DeFi lending eligibility or underwriting decisions
* Comparing multiple wallets or batch assessments
* Transaction flow and counterparty analysis
* AI agent discovery, reputation, or on-chain registration
## Tool Selection Guide
**Start here — pick the right tool for the job:**
| User Intent | Tool | Notes |
| - | - | - |
| "Is this wallet trustworthy?" | `get_credit_score` | Add `include_factors: true` for detail |
| "Compare these wallets" | `get_credit_scores_batch` | Individual scores, no aggregation |
| "Give me one score for this multi-sig" | `get_aggregate_score` | Single combined score |
| "Tell me everything about this wallet" | `get_financial_summary` | Full report with assets, DeFi, events |
| "Full multi-chain credit report" | `get_comprehensive_report` | Per-chain breakdowns + percentiles |
| "Quick summary, no chain details" | `get_summary_report` | Lighter than comprehensive |
| "What's happening on Ethereum specifically?" | `get_chain_report` | Single-chain deep dive |
| "Quick chain stats" | `get_chain_summary` | Single-chain aggregated metrics |
| "How much is this wallet worth?" | `get_portfolio_value` | Total USD across all chains |
| "What does this wallet hold on Base?" | `get_chain_portfolio_value` | Chain-specific USD value |
| "What's the asset breakdown?" | `get_portfolio_composition` | Tokens, DeFi, stablecoins, debt |
| "What identity does this wallet have?" | `get_identity_attestations` | ENS, Gitcoin Passport, POAPs, etc. |
| "Is this a bot or a real person?" | `get_sybil_score` | Sybil detection with indicators |
| "Show me this wallet's transaction network" | `get_transaction_graph` | Token transfer graph (nodes + edges) |
| "How many agents are registered?" | `get_agent_count` | Total in ERC-8004 registry |
| "List all agents" | `list_agents` | Paginated agent listing |
| "Find agents that do X" | `search_agents` | Search by name or description |
| "Look up agent #42" | `get_agent` | Single agent info by ID |
| "Rate this agent on-chain" | `submit_agent_reputation` | Submits credit/sybil/identity scores |
| "What's this agent's reputation?" | `get_agent_reputation` | Aggregated on-chain feedback |
| "Did my reputation submission go through?" | `get_reputation_status` | Track async submission |
## Escalation Patterns
**Wallet assessment (most common):**
Call `get_credit_score` with `include_factors: true` — this answers 80% of questions.
If the user wants the full picture, call `get_financial_summary` or `get_comprehensive_report`.
Only call `get_identity_attestations`, `get_portfolio_value`, or `get_sybil_score` if the user needs those specific details — the financial summary already includes identity and asset data.
**Deep dive on a wallet:**
1. `get_credit_score` for the headline number
2. `get_comprehensive_report` for the full multi-chain breakdown
3. `get_sybil_score` if trust/humanity is in question
4. `get_transaction_graph` to visualize the wallet's network
**Agent reputation workflow:**
1. `search_agents` or `list_agents` to find the agent
2. `get_agent` to confirm details
3. `get_agent_reputation` to read existing on-chain feedback
4. `submit_agent_reputation` to add new feedback (costs 10 CU, async)
5. `get_reputation_status` to track the on-chain submission
## Authentication
All tools require a `CRED_API_KEY` to access the live Cred Protocol API. All responses include `source: "live"` indicating real on-chain data.
Generate your API key from the [Cred Protocol Dashboard](https://app.credprotocol.com/dashboard).
## Understanding Credit Scores
Scores range from 300 to 1000 (like traditional credit scores):
| Range | Label | Meaning |
| - | - | - |
| 920-1000 | Excellent | Top-tier on-chain reputation. Minimal risk. |
| 840-919 | Very Good | Strong history, diversified activity. |
| 750-839 | Good | Solid track record, moderate experience. |
| 640-749 | Fair | Limited history or some risk signals. |
| 300-639 | Low | New wallet, thin file, or negative events. |
**Score factors** (available with `include_factors: true`):
* **Borrowing History** — Loan repayment track record across DeFi protocols
* **Wallet Composition** — Asset diversity and stablecoin ratio
* **Wallet Health** — Collateralization ratios and liquidation distance
* **Interactions** — Protocol breadth and ecosystem participation
* **Trust** — Identity attestations (ENS, Gitcoin Passport, POAPs)
* **New Credit** — Recent changes in borrowing behavior
## Understanding Sybil Scores
The `get_sybil_score` tool returns a score from 0-100 with a risk level:
| Risk Level | Score | Meaning |
| - | - | - |
| low | 0-25 | Likely a unique human with organic activity |
| medium | 26-50 | Some suspicious indicators, needs context |
| high | 51-75 | Multiple sybil indicators present |
| critical | 76-100 | Very likely a sybil/bot account |
**Key indicators to highlight:**
* `wallet_age_days` — Older wallets are more trustworthy
* `transaction_time_entropy` — Higher entropy = more human-like timing
* `identity_attestations` — More attestations = harder to fake
* `count_unique_counterparties` — Diverse interactions suggest real usage
## Reading Financial Summaries
Key fields in the financial summary report:
| Field | Meaning |
| - | - |
| `net_worth_usd` | Total assets minus total debt |
| `total_asset_usd` / `total_debt_usd` | Gross positions |
| `total_collateral_usd` | Assets locked as collateral in DeFi |
| `count_transactions` | Total on-chain transactions (activity proxy) |
| `count_active_loans` | Current open DeFi loans |
| `count_liquidations` | Historical liquidation events (red flag if > 0) |
| `global_percentiles` | How this wallet compares to the population |
## Identity Attestations
Attestations are verified on-chain identity credentials:
| Attestation | What It Proves |
| - | - |
| ENS Name | Owns an Ethereum Name Service domain |
| Basename | Owns a Base network name (username.base.eth) |
| Gitcoin Passport | Passed humanity verification (score >= 20) |
| POAPs | Attended real-world or virtual events |
| Worldcoin | Verified unique human via biometric proof |
| BrightID | Verified through social graph analysis |
More attestations generally indicate a more established, trustworthy identity.
## Transaction Graphs
The `get_transaction_graph` tool returns a tripartite graph:
* **Nodes** with `group: "wallet"` are Ethereum addresses
* **Nodes** with `group: "token"` are ERC-20 tokens (USDC, WETH, etc.)
* **Edges** with `label: "SENT"` go from wallet to token
* **Edges** with `label: "RECEIVED"` go from token to wallet
This is useful for visualizing money flow, identifying major counterparties, and spotting wash trading patterns.
## Agentic Reputation (ERC-8004)
The agent tools interact with the ERC-8004 Identity and Reputation Registries on Base (chain ID 8453).
**Identity Registry** — where agents are registered as ERC-721 tokens:
* Each agent has an `agent_id` (token ID), `owner` address, and `metadata` (name, description, image)
* Use `get_agent_count`, `list_agents`, `search_agents`, `get_agent` to browse
**Reputation Registry** — where feedback about agents is stored on-chain:
* `submit_agent_reputation` computes credit score, sybil risk, and identity count for a given address, then writes the results on-chain as feedback for the specified agent
* `get_agent_reputation` reads the aggregated feedback summary
* Submissions are async — use `get_reputation_status` to track
You can combine agent tools with wallet tools: look up an agent's owner via `get_agent`, then score the owner with `get_credit_score` to assess the human behind the agent.
## Supported Chains
Data is aggregated across 10 EVM networks:
| Chain | ID | Notes |
| - | - | - |
| Ethereum | 1 | Primary chain, richest data |
| Optimism | 10 | L2 |
| BSC | 56 | Binance Smart Chain |
| Polygon | 137 | L2 |
| Base | 8453 | Coinbase L2, ERC-8004 registry |
| Arbitrum | 42161 | L2 |
| Celo | 42220 | Mobile-first chain |
| Avalanche | 43114 | — |
| Scroll | 534352 | zkEVM L2 |
| Linea | 59144 | Consensys zkEVM L2 |
## Input Format
All address-based tools accept either:
* **Ethereum addresses**: `0x742d35Cc6634C0532925a3b844Bc9e7595f32345` (42 characters, hex)
* **ENS names**: `vitalik.eth`, `username.base.eth`
Agent tools use integer `agent_id` values (starting at 1).
## Best Practices
A single `get_credit_score` with `include_factors: true` answers most questions. Only escalate to `get_comprehensive_report` if the user needs the full breakdown.
Use `get_credit_scores_batch` instead of looping `get_credit_score` for multiple addresses.
Translate scores and data into actionable insights. "This wallet has an Excellent score of 945 with no liquidation history — it's a strong candidate for undercollateralized lending."
Highlight liquidations, high debt-to-asset ratios, low scores, missing identity attestations, or high sybil scores.
A 750 is "Good" — don't call it average. A 640 is "Fair" — don't call it bad. Use the labels.
Credit score + sybil score + identity attestations gives a comprehensive trust picture. Agent lookup + owner credit score assesses the human behind an agent.
After `submit_agent_reputation`, always inform the user the submission is async and provide the `submission_id` for tracking with `get_reputation_status`.
# Examples
Source: https://docs.credprotocol.com/mcp-services/examples
Practical examples of using Cred Protocol MCP services
# MCP Usage Examples
This page provides practical examples of using Cred Protocol MCP services in various scenarios.
## Example 1: Credit Score Check
A common use case is checking the credit score before approving a loan or granting access.
```python Python theme={null}
import httpx
API_KEY = "YOUR_API_KEY"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}
async def check_creditworthiness(address: str, min_score: int = 700) -> dict:
"""
Check if an address meets minimum credit requirements.
Args:
address: Ethereum address or ENS name
min_score: Minimum required credit score
Returns:
Dict with approval status and score details
"""
async with httpx.AsyncClient() as client:
response = await client.get(
f"https://api.credprotocol.com/mcp/score/{address}",
headers=HEADERS,
params={"include_factors": True}
)
data = response.json()
return {
"address": data["address"],
"score": data["score"],
"range": data["range"],
"approved": data["score"] >= min_score,
"factors": data.get("factors", [])
}
# Usage
result = await check_creditworthiness("vitalik.eth", min_score=750)
if result["approved"]:
print(f"Approved! Score: {result['score']} ({result['range']})")
else:
print(f"Not approved. Score: {result['score']} (need 750+)")
```
```typescript TypeScript theme={null}
const API_KEY = "YOUR_API_KEY";
const HEADERS = { Authorization: `Bearer ${API_KEY}` };
interface CreditCheck {
address: string;
score: number;
range: string;
approved: boolean;
factors: Array<{ label: string; rating: string; description: string }>;
}
async function checkCreditworthiness(
address: string,
minScore: number = 700
): Promise {
const response = await fetch(
`https://api.credprotocol.com/mcp/score/${address}?include_factors=true`,
{ headers: HEADERS }
);
const data = await response.json();
return {
address: data.address,
score: data.score,
range: data.range,
approved: data.score >= minScore,
factors: data.factors || []
};
}
// Usage
const result = await checkCreditworthiness("vitalik.eth", 750);
console.log(result.approved ? "Approved!" : "Not approved");
```
```bash cURL theme={null}
# Check score and pipe to jq for analysis
curl -s -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/score/vitalik.eth?include_factors=true" | \
jq '{approved: (.score >= 750), score: .score, range: .range}'
```
***
## Example 2: Batch Risk Assessment
Evaluate multiple addresses at once for portfolio risk analysis.
```python Python theme={null}
import httpx
from typing import List
API_KEY = "YOUR_API_KEY"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}
async def batch_risk_assessment(addresses: List[str]) -> dict:
"""
Assess credit risk across multiple addresses.
Returns summary statistics and individual scores.
"""
async with httpx.AsyncClient() as client:
response = await client.post(
"https://api.credprotocol.com/mcp/score/batch",
headers=HEADERS,
json={"addresses": addresses}
)
data = response.json()
scores = [s["score"] for s in data["scores"]]
return {
"count": data["count"],
"average_score": sum(scores) / len(scores),
"min_score": min(scores),
"max_score": max(scores),
"high_risk_count": sum(1 for s in scores if s < 640),
"scores": data["scores"]
}
# Usage
addresses = [
"vitalik.eth",
"0x742d35Cc6634C0532925a3b844Bc9e7595f32345",
"0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B"
]
risk = await batch_risk_assessment(addresses)
print(f"Portfolio avg score: {risk['average_score']:.0f}")
print(f"High risk addresses: {risk['high_risk_count']}")
```
```typescript TypeScript theme={null}
const API_KEY = "YOUR_API_KEY";
const HEADERS = { Authorization: `Bearer ${API_KEY}` };
interface RiskAssessment {
count: number;
averageScore: number;
minScore: number;
maxScore: number;
highRiskCount: number;
scores: Array<{ address: string; score: number; range: string }>;
}
async function batchRiskAssessment(addresses: string[]): Promise {
const response = await fetch("https://api.credprotocol.com/mcp/score/batch", {
method: "POST",
headers: { ...HEADERS, "Content-Type": "application/json" },
body: JSON.stringify({ addresses })
});
const data = await response.json();
const scores = data.scores.map((s: any) => s.score);
return {
count: data.count,
averageScore: scores.reduce((a: number, b: number) => a + b, 0) / scores.length,
minScore: Math.min(...scores),
maxScore: Math.max(...scores),
highRiskCount: scores.filter((s: number) => s < 640).length,
scores: data.scores
};
}
```
***
## Example 3: Identity Verification Gate
Only allow users with verified identity to access premium features.
```python Python theme={null}
import httpx
API_KEY = "YOUR_API_KEY"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}
REQUIRED_ATTESTATIONS = ["ENS Name", "Gitcoin Passport"]
async def verify_identity(address: str) -> dict:
"""
Check if address has required identity attestations.
"""
async with httpx.AsyncClient() as client:
response = await client.get(
f"https://api.credprotocol.com/mcp/identity/{address}",
headers=HEADERS,
)
data = response.json()
attestations = set(data["attestations"])
required = set(REQUIRED_ATTESTATIONS)
return {
"address": data["address"],
"verified": required.issubset(attestations),
"has": list(attestations),
"missing": list(required - attestations)
}
# Usage
result = await verify_identity("vitalik.eth")
if result["verified"]:
print("Identity verified - access granted")
else:
print(f"Missing: {result['missing']}")
```
```typescript TypeScript theme={null}
const API_KEY = "YOUR_API_KEY";
const HEADERS = { Authorization: `Bearer ${API_KEY}` };
const REQUIRED_ATTESTATIONS = ["ENS Name", "Gitcoin Passport"];
async function verifyIdentity(address: string) {
const response = await fetch(
`https://api.credprotocol.com/mcp/identity/${address}`,
{ headers: HEADERS }
);
const data = await response.json();
const attestations = new Set(data.attestations);
const missing = REQUIRED_ATTESTATIONS.filter(a => !attestations.has(a));
return {
address: data.address,
verified: missing.length === 0,
has: data.attestations,
missing
};
}
```
***
## Example 4: Portfolio Analysis Dashboard
Build a comprehensive view of a wallet's holdings.
```python Python theme={null}
import httpx
import asyncio
API_KEY = "YOUR_API_KEY"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}
CHAINS = {
1: "Ethereum",
10: "Optimism",
137: "Polygon",
8453: "Base",
42161: "Arbitrum"
}
async def get_portfolio_breakdown(address: str) -> dict:
"""
Get portfolio value broken down by chain.
"""
async with httpx.AsyncClient() as client:
# Fetch total and chain-specific values in parallel
tasks = [
client.get(
f"https://api.credprotocol.com/mcp/portfolio/{address}",
headers=HEADERS,
)
]
for chain_id in CHAINS:
tasks.append(
client.get(
f"https://api.credprotocol.com/mcp/portfolio/{address}/chain/{chain_id}",
headers=HEADERS,
)
)
responses = await asyncio.gather(*[t for t in tasks])
total_data = responses[0].json()
chain_data = [r.json() for r in responses[1:]]
return {
"address": total_data["address"],
"total_usd": total_data["total_asset_usd"],
"chains": sorted(
[
{
"chain": c["chain_name"],
"value_usd": c["total_asset_usd"],
"percentage": (c["total_asset_usd"] / total_data["total_asset_usd"]) * 100
}
for c in chain_data
],
key=lambda x: x["value_usd"],
reverse=True
)
}
# Usage
portfolio = await get_portfolio_breakdown("vitalik.eth")
print(f"Total: ${portfolio['total_usd']:,.2f}")
for chain in portfolio["chains"]:
print(f" {chain['chain']}: ${chain['value_usd']:,.2f} ({chain['percentage']:.1f}%)")
```
***
## Example 5: AI Agent Integration
Example prompt for an AI agent using MCP tools:
```markdown theme={null}
**User:** Can you analyze the wallet 0x742d35Cc6634C0532925a3b844Bc9e7595f32345?
**AI Agent Actions:**
1. Call `get_credit_score("0x742d35...")` -> Score: 785 (Good)
2. Call `get_financial_summary("0x742d35...")` -> Net worth: $45,230
3. Call `get_identity_attestations("0x742d35...")` -> ENS, Gitcoin Passport
**AI Agent Response:**
This wallet has a **Good credit score of 785** with:
- Total net worth of **$45,230** across multiple chains
- Active DeFi positions with healthy collateral ratios
- Verified identity through ENS and Gitcoin Passport
- No history of liquidations or defaults
The wallet shows responsible DeFi usage and could qualify for
undercollateralized lending up to $5,000.
```
***
## Example 6: Webhook-Style Monitoring
Set up periodic monitoring of credit scores:
```python theme={null}
import httpx
import asyncio
API_KEY = "YOUR_API_KEY"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}
MONITORED_ADDRESSES = [
"vitalik.eth",
"0x742d35Cc6634C0532925a3b844Bc9e7595f32345"
]
ALERT_THRESHOLD = 700
async def monitor_scores():
"""Monitor credit scores and alert on changes."""
previous_scores = {}
while True:
async with httpx.AsyncClient() as client:
for address in MONITORED_ADDRESSES:
response = await client.get(
f"https://api.credprotocol.com/mcp/score/{address}",
headers=HEADERS,
)
data = response.json()
current_score = data["score"]
# Check for significant changes
if address in previous_scores:
change = current_score - previous_scores[address]
if abs(change) > 50:
print(f"Warning: {address}: Score changed by {change:+d}")
# Check for threshold breach
if current_score < ALERT_THRESHOLD:
print(f"Alert: {address}: Score {current_score} below threshold!")
previous_scores[address] = current_score
# Check every 5 minutes
await asyncio.sleep(300)
# Run monitor
asyncio.run(monitor_scores())
```
***
## Example 7: Agent Discovery with ERC-8004
Search the on-chain agent registry to find and verify AI agents before interacting with them.
```python Python theme={null}
import httpx
API_KEY = "YOUR_API_KEY"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}
async def discover_agents(capability: str, min_results: int = 1) -> dict:
"""
Search the ERC-8004 Identity Registry for agents matching a capability.
Args:
capability: What the agent should be able to do (e.g., "lending", "risk")
min_results: Minimum number of results expected
Returns:
Dict with matching agents and discovery metadata
"""
async with httpx.AsyncClient() as client:
response = await client.get(
"https://api.credprotocol.com/mcp/agents/search",
headers=HEADERS,
params={"q": capability, "limit": 10}
)
data = response.json()
return {
"query": capability,
"found": data["total_results"],
"sufficient": data["total_results"] >= min_results,
"agents": [
{
"id": agent["agent_id"],
"name": agent["metadata"]["name"] if agent["metadata"] else None,
"owner": agent["owner"],
}
for agent in data["agents"]
]
}
# Usage
results = await discover_agents("credit scoring")
for agent in results["agents"]:
print(f"Agent #{agent['id']}: {agent['name']} (owner: {agent['owner'][:10]}...)")
```
```typescript TypeScript theme={null}
const API_KEY = "YOUR_API_KEY";
const HEADERS = { Authorization: `Bearer ${API_KEY}` };
interface AgentResult {
id: number;
name: string | null;
owner: string;
}
async function discoverAgents(capability: string): Promise {
const response = await fetch(
`https://api.credprotocol.com/mcp/agents/search?q=${encodeURIComponent(capability)}&limit=10`,
{ headers: HEADERS }
);
const data = await response.json();
return data.agents.map((agent: any) => ({
id: agent.agent_id,
name: agent.metadata?.name ?? null,
owner: agent.owner,
}));
}
// Usage
const agents = await discoverAgents("risk analysis");
agents.forEach(a => console.log(`Agent #${a.id}: ${a.name}`));
```
```bash cURL theme={null}
# Search for lending-related agents
curl -s -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/agents/search?q=lending&limit=5" | \
jq '.agents[] | {id: .agent_id, name: .metadata.name, owner: .owner}'
```
***
## Example 8: AI Agent Integration with Agent Discovery
Example prompt for an AI agent combining wallet analysis with agent discovery:
```markdown theme={null}
**User:** Find me agents that do risk analysis, and check if their owners have good credit.
**AI Agent Actions:**
1. Call `search_agents("risk analysis")` -> Found 3 agents
2. Call `get_credit_scores_batch(["0x742d...", "0xAb58...", "0x1234..."])` -> Scores for agent owners
**AI Agent Response:**
I found **3 registered risk analysis agents** in the ERC-8004 registry:
1. **Risk Analyzer Pro** (Agent #42) - Owner score: 891 (Very Good)
2. **DeFi Risk Scout** (Agent #87) - Owner score: 745 (Good)
3. **Credit Risk Bot** (Agent #156) - Owner score: 623 (Low)
Agents #42 and #87 have owners with strong credit profiles, suggesting
established on-chain participants. Agent #156's owner has a low score,
which may warrant additional verification before relying on its outputs.
```
***
## Next Steps
Complete API reference for all tools
Use the REST API directly
# Getting Started
Source: https://docs.credprotocol.com/mcp-services/getting-started
Connect your AI agent or application to Cred Protocol MCP services
# Getting Started with MCP Services
This guide shows you how to connect to Cred Protocol's MCP services using different methods.
## Prerequisites
Paid MCP tools need credentials: an API key from the [Cred Protocol Dashboard](https://app.credprotocol.com/dashboard), or a per-request [x402 / MPP payment](/guides/payments) if you'd rather not create an account. Agent-registry reads (`get_agent_count`, `list_agents`, `search_agents`, `get_agent`, `get_reputation_status`) are free.
## Method 1: HTTP Endpoints (Simplest)
The easiest way to use MCP services is through the HTTP endpoints.
### Base URL
```
https://api.credprotocol.com/mcp
```
### Quick Test
```bash theme={null}
# Get a credit score
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/score/vitalik.eth"
# List available tools
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/tools"
```
### Response
```json theme={null}
{
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"score": 774,
"decile": 5,
"range": "good",
"model_version": "andromeda_1.1",
"timestamp": "2026-03-31T06:21:16.423948Z",
"source": "live"
}
```
## Method 2: Cursor IDE Integration
If you're using [Cursor](https://cursor.sh), you can integrate Cred Protocol as an MCP server.
### Step 1: Configure Cursor
Add to your `.cursor/mcp.json` file:
```json theme={null}
{
"mcpServers": {
"cred-protocol": {
"url": "https://api.credprotocol.com/mcp",
"headers": {
"Authorization": "Bearer YOUR_API_KEY"
}
}
}
}
```
### Step 2: Use in Cursor
Once configured, you can ask Cursor's AI:
> "What's the credit score for vitalik.eth?"
The AI will automatically call the MCP tool and respond with the result.
## Method 3: Claude Code
For [Claude Code](https://claude.ai/code) (CLI, desktop app, or IDE extensions), add to your project's `.mcp.json`:
```json theme={null}
{
"mcpServers": {
"cred-protocol": {
"type": "url",
"url": "https://api.credprotocol.com/mcp",
"headers": {
"Authorization": "Bearer YOUR_API_KEY"
}
}
}
}
```
Once configured, you can ask Claude Code directly:
> "What's the credit score for vitalik.eth?"
## Method 4: Claude Desktop
For [Claude Desktop](https://claude.ai/download), add to your MCP configuration:
```json theme={null}
{
"mcpServers": {
"cred-protocol": {
"url": "https://api.credprotocol.com/mcp",
"headers": {
"Authorization": "Bearer YOUR_API_KEY"
}
}
}
}
```
## Method 5: Custom HTTP Client
Build your own client using standard HTTP requests:
### Python
```python theme={null}
import httpx
API_KEY = "YOUR_API_KEY"
BASE_URL = "https://api.credprotocol.com/mcp"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}
async def get_credit_score(address: str) -> dict:
"""Get credit score via MCP HTTP endpoint."""
async with httpx.AsyncClient() as client:
response = await client.get(
f"{BASE_URL}/score/{address}",
headers=HEADERS,
)
return response.json()
# Usage
score = await get_credit_score("vitalik.eth")
print(f"Score: {score['score']} ({score['range']})")
```
### JavaScript/TypeScript
```typescript theme={null}
const API_KEY = "YOUR_API_KEY";
const BASE_URL = "https://api.credprotocol.com/mcp";
async function getCreditScore(address: string): Promise {
const response = await fetch(`${BASE_URL}/score/${address}`, {
headers: { Authorization: `Bearer ${API_KEY}` },
});
return response.json();
}
// Usage
const score = await getCreditScore("vitalik.eth");
console.log(`Score: ${score.score} (${score.range})`);
```
## Available Endpoints
All endpoints require `Authorization: Bearer YOUR_API_KEY` header.
**Score & Reports:**
| Endpoint | Method | Description |
| - | - | - |
| `/mcp/score/{address}` | GET | Get credit score |
| `/mcp/score/batch` | POST | Batch score multiple addresses |
| `/mcp/score/aggregate?addresses=...` | GET | Aggregated score for multiple addresses |
| `/mcp/summary/{address}` | GET | Get financial summary |
| `/mcp/report/{address}` | GET | Comprehensive multi-chain credit report |
| `/mcp/report/{address}/summary` | GET | Summary report (no per-chain details) |
| `/mcp/report/{address}/chain/{chain_id}` | GET | Single-chain detailed report |
| `/mcp/report/{address}/chain/{chain_id}/summary` | GET | Single-chain summary |
**Portfolio:**
| Endpoint | Method | Description |
| - | - | - |
| `/mcp/portfolio/{address}` | GET | Get total portfolio value |
| `/mcp/portfolio/{address}/chain/{chain_id}` | GET | Get chain-specific portfolio |
| `/mcp/portfolio/{address}/composition` | GET | Portfolio breakdown by asset type |
**Identity & Graph:**
| Endpoint | Method | Description |
| - | - | - |
| `/mcp/identity/{address}` | GET | Get identity attestations |
| `/mcp/identity/{address}/sybil` | GET | Sybil detection score |
| `/mcp/graph/{address}?chain_id=1` | GET | Transaction graph visualization |
**Agents (ERC-8004):**
| Endpoint | Method | Description |
| - | - | - |
| `/mcp/agents/count` | GET | Total registered agents |
| `/mcp/agents` | GET | Paginated agent list |
| `/mcp/agents/search?q={query}` | GET | Search agents by name/description |
| `/mcp/agents/{agent_id}` | GET | Get agent info by ID |
| `/mcp/agents/{agent_id}/reputation` | POST | Submit reputation feedback (10 CU) |
| `/mcp/agents/{agent_id}/reputation` | GET | Read reputation summary (1 CU) |
| `/mcp/agents/{agent_id}/reputation/status/{id}` | GET | Track submission status |
| `/mcp/tools` | GET | List all available tools |
## Next Steps
Learn about each available tool
Practical usage examples
# MCP Services Overview
Source: https://docs.credprotocol.com/mcp-services/overview
Access Cred Protocol credit scoring and agentic reputation through the Model Context Protocol for AI agents
# MCP Services
Cred Protocol provides **Model Context Protocol (MCP)** services that enable AI agents and assistants to access on-chain credit scoring, financial reporting, identity attestation, and agentic reputation data.
MCP is an open protocol that allows AI systems to securely interact with external tools and data sources.
[Learn more about MCP →](https://modelcontextprotocol.io)
## What is MCP?
The Model Context Protocol (MCP) is a standardized way for AI agents (like Claude, GPT, or custom LLM applications) to:
* **Discover** available tools and their capabilities
* **Call** tools with structured parameters
* **Receive** structured responses
Unlike traditional REST APIs that require manual integration, MCP allows AI agents to automatically understand and use your tools through natural language.
## Why Use MCP Services?
AI agents can discover and use Cred Protocol tools without custom code
Users can ask "What's this wallet's credit score?" and the agent handles it
Real blockchain data from 10+ EVM networks — credit scores, reports, identity, and more
Comprehensive coverage: scoring, reports, identity, sybil detection, agent reputation
## Available Tools (21 Total)
All tools return **live on-chain data** and require an API key (`Authorization: Bearer `).
| Tool | Description |
| - | - |
| **Credit Scoring** | |
| `get_credit_score` | Get credit score (300-1000) for an Ethereum address |
| `get_credit_scores_batch` | Get scores for multiple addresses at once |
| `get_aggregate_score` | Single aggregated score across multiple addresses |
| **Reports** | |
| `get_financial_summary` | Comprehensive financial report with assets, DeFi positions, and activity |
| `get_comprehensive_report` | Full multi-chain credit report with per-chain breakdowns |
| `get_summary_report` | Aggregated metrics without per-chain details |
| `get_chain_report` | Detailed report for a single blockchain |
| `get_chain_summary` | Summary metrics for a single blockchain |
| **Portfolio** | |
| `get_portfolio_value` | Total portfolio value in USD across all chains |
| `get_chain_portfolio_value` | Portfolio value on a specific blockchain |
| `get_portfolio_composition` | Portfolio breakdown by asset type (tokens, DeFi, stablecoins, debt) |
| **Identity** | |
| `get_identity_attestations` | Verified identity credentials (ENS, Gitcoin Passport, POAPs) |
| `get_sybil_score` | Sybil detection score with behavioral indicators |
| **Graph** | |
| `get_transaction_graph` | Token transfer graph visualization (nodes + edges) |
| **Agents (ERC-8004)** | |
| `get_agent_count` | Total registered agents in the Identity Registry |
| `list_agents` | Paginated list of all registered agents |
| `get_agent` | Get info for a specific agent by ID |
| `search_agents` | Search agents by name or description |
| `submit_agent_reputation` | Submit on-chain reputation feedback (10 CU) |
| `get_agent_reputation` | Read on-chain reputation summary (1 CU) |
| `get_reputation_status` | Track status of a reputation submission |
All tools require an API key. Generate one from the [Cred Protocol Dashboard](https://app.credprotocol.com/dashboard).
## Agentic Reputation (ERC-8004)
In addition to wallet credit scoring, Cred Protocol MCP services provide full access to the **ERC-8004 Identity and Reputation Registries** on Base — enabling AI agents to discover, assess, and rate other agents on-chain.
**7 agent tools** cover the complete lifecycle:
* **Discovery** — `get_agent_count`, `list_agents`, `search_agents`, `get_agent`
* **Reputation scoring** — `submit_agent_reputation` computes credit score, sybil risk, and identity attestations, then writes the results on-chain
* **Reputation reading** — `get_agent_reputation` reads aggregated feedback from the Reputation Registry
* **Tracking** — `get_reputation_status` tracks asynchronous on-chain submissions
ERC-8004 defines a standard for registering AI agent identities on-chain as ERC-721 tokens. Each agent has an owner address and metadata (name, description, image) stored via tokenURI. The registry lives on Base (chain ID 8453).
Unlike credit scoring tools which assess *wallet* reputation, the agent tools operate on the *agent* layer — helping AI systems discover, evaluate, and provide feedback on other AI agents in the ecosystem.
## Access Methods
Cred Protocol MCP services can be accessed two ways:
### 1. HTTP/REST Endpoints
Standard HTTP endpoints at `https://api.credprotocol.com/mcp/*` — works with any HTTP client:
```bash theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/score/vitalik.eth"
```
Each `/mcp/*` route is a pass-through to the equivalent `/api/v2/*` endpoint, so it accepts the same credentials — an API key, an x402 `X-PAYMENT`, or an MPP `Authorization: Payment …` — and returns the same `402` challenge when none is supplied. Prices are listed at `GET /mcp/tools`; see [Machine Payments](/guides/payments).
### 2. MCP Protocol
Native MCP protocol for AI agents like Cursor, Claude Code, Claude Desktop, or custom MCP clients. Uses streamable-http transport — a single endpoint that handles both request/response and streaming:
```json theme={null}
{
"mcpServers": {
"cred-protocol": {
"url": "https://api.credprotocol.com/mcp",
"headers": {
"Authorization": "Bearer YOUR_API_KEY"
}
}
}
}
```
## Agent Skill Instructions
When an AI agent connects via MCP, the server automatically provides skill instructions that guide the agent on:
* **Which tool to use** for different user intents
* **How to interpret** credit scores, financial summaries, and attestations
* **When to escalate** from a quick score check to a full financial report
* **Best practices** like batching requests and flagging red flags
These instructions are delivered to agents during MCP initialization — no extra configuration needed. See the full [Agent Skill reference](/mcp-services/agent-skill).
## MCP vs REST API
| Feature | MCP Services | REST API |
| - | - | - |
| **Data** | Live on-chain data | Live on-chain data |
| **Authentication** | API key required | API key required |
| **Purpose** | AI agents and assistants | Production applications |
| **Protocol** | MCP (streamable-http) + HTTP | HTTP |
| **Billing** | Consumes Cred Units | Consumes Cred Units |
## Next Steps
Connect your AI agent to Cred Protocol MCP
Explore all available MCP tools
See practical usage examples
Use the REST API directly
# Available Tools
Source: https://docs.credprotocol.com/mcp-services/tools
Complete reference for all 21 Cred Protocol MCP tools
# MCP Tools Reference
This page documents all available MCP tools for credit scoring, financial reporting, identity verification, portfolio analysis, transaction graphs, and agentic reputation.
All tools return **live on-chain data** and require an API key. Pass your key via the `Authorization: Bearer YOUR_API_KEY` header.
***
## Credit Scoring
### get\_credit\_score
Get the Cred Protocol credit score for an Ethereum address or ENS name.
Ethereum address (0x...) or ENS name (e.g., vitalik.eth)
Include detailed score factors explaining the score
**Score Ranges:**
* 920-1000: Excellent
* 840-919: Very Good
* 750-839: Good
* 640-749: Fair
* 300-639: Low
```bash cURL theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/score/vitalik.eth?include_factors=true"
```
```python Python theme={null}
import httpx
response = httpx.get(
"https://api.credprotocol.com/mcp/score/vitalik.eth",
headers={"Authorization": "Bearer YOUR_API_KEY"},
params={"include_factors": True}
)
score_data = response.json()
```
```typescript TypeScript theme={null}
const response = await fetch(
"https://api.credprotocol.com/mcp/score/vitalik.eth?include_factors=true",
{ headers: { Authorization: "Bearer YOUR_API_KEY" } }
);
const scoreData = await response.json();
```
**Response:**
```json theme={null}
{
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"score": 774,
"decile": 5,
"range": "good",
"model_version": "andromeda_1.1",
"timestamp": "2026-03-31T06:21:16.423948Z",
"factors": [
{
"label": "Borrowing History",
"rating": "good",
"description": "You have a good track record of using lending products."
},
{
"label": "Wallet Composition",
"rating": "very_good",
"description": "You have a very_good breakdown of tokens in your account."
}
],
"source": "live"
}
```
***
### get\_credit\_scores\_batch
Get individual credit scores for multiple Ethereum addresses at once.
List of Ethereum addresses or ENS names
```bash cURL theme={null}
curl -X POST "https://api.credprotocol.com/mcp/score/batch" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"addresses": ["vitalik.eth", "0x1234..."]}'
```
```python Python theme={null}
response = httpx.post(
"https://api.credprotocol.com/mcp/score/batch",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={"addresses": ["vitalik.eth", "0x1234..."]}
)
```
**Response:**
```json theme={null}
{
"scores": [
{
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"score": 774,
"decile": 5,
"range": "good"
},
{
"address": "0x1234...",
"score": 650,
"decile": 6,
"range": "fair"
}
],
"count": 2,
"source": "live"
}
```
***
### get\_aggregate\_score
Get a single aggregated credit score across multiple Ethereum addresses. Useful for multi-sig wallets or portfolio-level assessments.
Comma-separated Ethereum addresses or ENS names
```bash cURL theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/score/aggregate?addresses=vitalik.eth,0x1234..."
```
```python Python theme={null}
response = httpx.get(
"https://api.credprotocol.com/mcp/score/aggregate",
headers={"Authorization": "Bearer YOUR_API_KEY"},
params={"addresses": "vitalik.eth,0x1234..."}
)
```
**Response:**
```json theme={null}
{
"address": "0xd8da6bf2...,0x1234...",
"score": 760,
"model_version": "andromeda_1.1",
"source": "live"
}
```
***
## Financial Reporting
### get\_financial\_summary
Get a comprehensive financial summary for an Ethereum address. Includes assets, DeFi positions, credit events, and global percentile rankings.
Ethereum address or ENS name
**Includes:**
* Asset values (total assets, collateral, debt, stablecoins)
* Activity metrics (transactions, transfers, NFTs)
* DeFi positions (loans, collateral deposits)
* Credit events (liquidations, defaults, repayments)
* Identity attestations
```bash cURL theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/summary/vitalik.eth"
```
```python Python theme={null}
response = httpx.get(
"https://api.credprotocol.com/mcp/summary/vitalik.eth",
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
summary = response.json()
```
**Response:**
```json theme={null}
{
"report": {
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"timestamp": "2026-03-31T06:21:16Z",
"first_transaction": {
"timestamp": "2015-08-07T00:00:00Z",
"age_human": "10 years ago"
},
"summary": {
"net_worth_usd": 2450000.50,
"total_asset_usd": 2500000.00,
"total_collateral_usd": 500000.00,
"total_debt_usd": 50000.00,
"count_transactions": 15230,
"count_nfts": 142,
"count_active_loans": 2,
"count_liquidations": 0
}
},
"source": "live"
}
```
***
### get\_comprehensive\_report
Get the most detailed multi-chain credit report, including per-chain breakdowns with balances, transactions, NFTs, DeFi positions, and credit events.
Ethereum address or ENS name
```bash cURL theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/report/vitalik.eth"
```
```python Python theme={null}
response = httpx.get(
"https://api.credprotocol.com/mcp/report/vitalik.eth",
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
report = response.json()
```
**Response:**
```json theme={null}
{
"report": {
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"timestamp": "2026-03-31T06:21:16Z",
"first_transaction": {
"timestamp": "2015-08-07T00:00:00Z",
"age_human": "10 years ago"
},
"summary": {
"net_worth_usd": 2450000.50,
"total_asset_usd": 2500000.00,
"total_collateral_usd": 500000.00,
"total_debt_usd": 50000.00,
"count_transactions": 15230,
"count_nfts": 142,
"count_active_loans": 2,
"count_liquidations": 0
},
"global_summary_stats": { "..." : "..." },
"global_percentiles": {
"net_worth_percentile": 99,
"transaction_count_percentile": 98,
"nft_count_percentile": 95
}
},
"source": "live"
}
```
**Performance:** Response time 5-10 seconds (aggregates data across multiple chains). Results cached for 5 minutes.
***
### get\_summary\_report
Get aggregated metrics across all chains without per-chain breakdowns. Lighter than the comprehensive report.
Ethereum address or ENS name
```bash cURL theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/report/vitalik.eth/summary"
```
```python Python theme={null}
response = httpx.get(
"https://api.credprotocol.com/mcp/report/vitalik.eth/summary",
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
```
**Response:**
```json theme={null}
{
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"summary": {
"net_worth_usd": 2450000.50,
"total_asset_usd": 2500000.00,
"count_transactions": 15230,
"count_nfts": 142
},
"source": "live"
}
```
***
### get\_chain\_report
Get a detailed credit report for a single blockchain including balances, transactions, NFTs, DeFi positions, and credit events.
Ethereum address or ENS name
Blockchain network ID (see [Supported Chains](#supported-chains))
```bash cURL theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/report/vitalik.eth/chain/1"
```
```python Python theme={null}
response = httpx.get(
"https://api.credprotocol.com/mcp/report/vitalik.eth/chain/1",
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
```
***
### get\_chain\_summary
Get aggregated metrics for a single blockchain without detailed balance/transaction lists.
Ethereum address or ENS name
Blockchain network ID (see [Supported Chains](#supported-chains))
```bash cURL theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/report/vitalik.eth/chain/8453/summary"
```
```python Python theme={null}
response = httpx.get(
"https://api.credprotocol.com/mcp/report/vitalik.eth/chain/8453/summary",
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
```
***
## Portfolio Value
### get\_portfolio\_value
Get the total USD value of all assets across all supported blockchains.
Ethereum address or ENS name
```bash cURL theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/portfolio/vitalik.eth"
```
```python Python theme={null}
response = httpx.get(
"https://api.credprotocol.com/mcp/portfolio/vitalik.eth",
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
portfolio = response.json()
```
**Response:**
```json theme={null}
{
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"total_asset_usd": 2500000.00,
"timestamp": "2026-03-31T06:21:16Z",
"source": "live"
}
```
***
### get\_chain\_portfolio\_value
Get the portfolio value on a specific blockchain.
Ethereum address or ENS name
Blockchain network ID (see [Supported Chains](#supported-chains))
```bash cURL theme={null}
# Get Ethereum portfolio
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/portfolio/vitalik.eth/chain/1"
# Get Base portfolio
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/portfolio/vitalik.eth/chain/8453"
```
```python Python theme={null}
response = httpx.get(
"https://api.credprotocol.com/mcp/portfolio/vitalik.eth/chain/1",
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
eth_portfolio = response.json()
```
**Response:**
```json theme={null}
{
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"chain_id": 1,
"chain_name": "Ethereum",
"total_asset_usd": 1950000.25,
"timestamp": "2026-03-31T06:21:16Z",
"source": "live"
}
```
***
### get\_portfolio\_composition
Get portfolio value broken down by asset type (tokens, DeFi positions, stablecoins, collateral, debt).
Ethereum address or ENS name
```bash cURL theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/portfolio/vitalik.eth/composition"
```
```python Python theme={null}
response = httpx.get(
"https://api.credprotocol.com/mcp/portfolio/vitalik.eth/composition",
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
```
**Response:**
```json theme={null}
{
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"total_asset_usd": 2500000.00,
"breakdown": {
"tokens": 1800000.00,
"stablecoins": 400000.00,
"defi_positions": 250000.00,
"collateral": 500000.00,
"debt": -50000.00
},
"source": "live"
}
```
***
## Identity Verification
### get\_identity\_attestations
Get verified identity attestations for an Ethereum address.
Ethereum address or ENS name
**Attestation Types:**
* ENS Name - Ethereum Name Service domain ownership
* Basename - Base network name service (username.base.eth)
* Gitcoin Passport - Humanity verification (score ≥ 20)
* POAPs - Proof of Attendance Protocol tokens
* Worldcoin - Verified human
* BrightID - Social verification
```bash cURL theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/identity/vitalik.eth"
```
```python Python theme={null}
response = httpx.get(
"https://api.credprotocol.com/mcp/identity/vitalik.eth",
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
identity = response.json()
```
**Response:**
```json theme={null}
{
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"attestations": [
"ENS Name",
"Gitcoin Passport",
"Proof of Humanity"
],
"count": 3,
"source": "live"
}
```
***
### get\_sybil\_score
Get a sybil detection score evaluating whether an address is a unique human or a sybil (duplicate/bot) account.
Ethereum address or ENS name
```bash cURL theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/identity/vitalik.eth/sybil"
```
```python Python theme={null}
response = httpx.get(
"https://api.credprotocol.com/mcp/identity/vitalik.eth/sybil",
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
sybil = response.json()
```
**Response:**
```json theme={null}
{
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"timestamp": "2026-03-31T06:21:16Z",
"sybil_score": 12,
"risk_level": "low",
"indicators": {
"count_unique_counterparties": 245,
"count_unique_contracts_interacted": 89,
"total_gas_spent_eth": 3.45,
"funding_source_address": "0x...",
"transaction_time_entropy": 0.92,
"identity_attestations": 5,
"wallet_age_days": 3200,
"transaction_count": 15230
},
"source": "live"
}
```
**Risk Levels:**
* `low` (0-25): Likely a unique human
* `medium` (26-50): Some suspicious indicators
* `high` (51-75): Multiple sybil indicators
* `critical` (76-100): Very likely a sybil/bot
***
## Transaction Graph
### get\_transaction\_graph
Get a transaction graph showing ERC-20 token transfer relationships as nodes and edges. Useful for visualizing transaction flow, identifying counterparties, and analyzing wallet activity patterns.
Ethereum address or ENS name
Blockchain network ID (default: Ethereum)
```bash cURL theme={null}
# Ethereum transaction graph
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/graph/vitalik.eth?chain_id=1"
# Base transaction graph
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/graph/vitalik.eth?chain_id=8453"
```
```python Python theme={null}
response = httpx.get(
"https://api.credprotocol.com/mcp/graph/vitalik.eth",
headers={"Authorization": "Bearer YOUR_API_KEY"},
params={"chain_id": 1}
)
graph = response.json()
```
```typescript TypeScript theme={null}
const response = await fetch(
"https://api.credprotocol.com/mcp/graph/vitalik.eth?chain_id=1",
{ headers: { Authorization: "Bearer YOUR_API_KEY" } }
);
const graph = await response.json();
```
**Response:**
```json theme={null}
{
"nodes": [
{"id": "0xd8dA6BF2...", "label": "0xd8dA6BF2...", "group": "wallet"},
{"id": "USDC", "label": "USDC", "group": "token"},
{"id": "0xAb5801a7...", "label": "0xAb5801a7...", "group": "wallet"}
],
"edges": [
{"from": "0xd8dA6BF2...", "to": "USDC", "label": "SENT"},
{"from": "USDC", "to": "0xAb5801a7...", "label": "RECEIVED"}
],
"total_transactions": 150,
"chain_id": 1,
"chain_name": "Ethereum Mainnet",
"address": "0xd8dA6BF2...",
"source": "live"
}
```
**Graph structure:** Tripartite graph (wallet → token → wallet) built from historical ERC-20 transfers.
**Performance:** Response time 2-5 seconds on first request, \~50-100ms on cached requests. Cached for 10 minutes.
***
## Agentic Reputation (ERC-8004)
[ERC-8004](https://github.com/credprotocol/ERCs/blob/master/ERCS/erc-8004.md) defines a standard for registering AI agent identities on-chain as ERC-721 tokens. Each agent has an owner address and metadata (name, description, image) resolved from its tokenURI. The registry lives on Base (chain ID 8453).
### get\_agent\_count
Get the total number of AI agents registered in the ERC-8004 Identity Registry on Base.
```bash cURL theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/agents/count"
```
```python Python theme={null}
response = httpx.get(
"https://api.credprotocol.com/mcp/agents/count",
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
```
**Response:**
```json theme={null}
{
"total": 42,
"source": "live"
}
```
***
### list\_agents
Get a paginated list of AI agents from the ERC-8004 Identity Registry.
Page number for pagination
Results per page (max: 100)
```bash cURL theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/agents?page=1&limit=10"
```
```python Python theme={null}
response = httpx.get(
"https://api.credprotocol.com/mcp/agents",
headers={"Authorization": "Bearer YOUR_API_KEY"},
params={"page": 1, "limit": 10}
)
```
**Response:**
```json theme={null}
{
"agents": [
{
"agent_id": 1,
"owner": "0xc38947DA1EB4466D17d5C6c34a0f26Dbe803d107",
"metadata": {
"name": "Cred Protocol Validator",
"description": "ERC-8004 reputation validator for on-chain credit scoring",
"image": "ipfs://QmExample..."
}
}
],
"total": 42,
"page": 1,
"limit": 10,
"source": "live"
}
```
***
### search\_agents
Search for AI agents by name or description using case-insensitive substring matching.
Search query — matches against agent name or description
Page number for pagination
Results per page (max: 100)
```bash cURL theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/agents/search?q=lending&limit=5"
```
```python Python theme={null}
response = httpx.get(
"https://api.credprotocol.com/mcp/agents/search",
headers={"Authorization": "Bearer YOUR_API_KEY"},
params={"q": "lending", "page": 1, "limit": 5}
)
agents = response.json()
```
```typescript TypeScript theme={null}
const response = await fetch(
"https://api.credprotocol.com/mcp/agents/search?q=lending&limit=5",
{ headers: { Authorization: "Bearer YOUR_API_KEY" } }
);
const agents = await response.json();
```
**Response:**
```json theme={null}
{
"agents": [
{
"agent_id": 42,
"owner": "0x742d35Cc6634C0532925a3b844Bc9e7595f32345",
"metadata": {
"name": "DeFi Lending Advisor",
"description": "An AI agent that evaluates lending opportunities across DeFi protocols",
"image": "ipfs://QmExample..."
}
}
],
"total_results": 1,
"query": "lending",
"page": 1,
"limit": 5,
"source": "live"
}
```
**Performance:** Results served from a cached agent index (refreshed every 12 hours). Response time typically under 1 second.
***
### get\_agent
Get info for a specific AI agent by its ERC-8004 ID.
ERC-8004 agent ID (starts at 1)
```bash cURL theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/agents/1"
```
```python Python theme={null}
response = httpx.get(
"https://api.credprotocol.com/mcp/agents/1",
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
```
**Response:**
```json theme={null}
{
"agent_id": 1,
"owner": "0xc38947DA1EB4466D17d5C6c34a0f26Dbe803d107",
"metadata": {
"name": "Cred Protocol Validator",
"description": "ERC-8004 reputation validator for on-chain credit scoring",
"image": "ipfs://QmExample..."
},
"source": "live"
}
```
***
### submit\_agent\_reputation
Submit ERC-8004 reputation feedback for an AI agent. Computes credit score, sybil risk, and identity attestations, then submits results as on-chain feedback to the Reputation Registry on Base.
ERC-8004 agent ID from Identity Registry (>= 1)
Ethereum address to score for this agent
Feedback tags to submit. Options: `creditScore`, `sybilRisk`, `identityCount`. Default: all three.
**Costs 10 Cred Units.**
The submission is asynchronous. This endpoint returns immediately with a tracking ID. Use `get_reputation_status` to poll for completion.
```bash cURL theme={null}
curl -X POST -H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
"https://api.credprotocol.com/mcp/agents/1/reputation" \
-d '{"address": "0x742d35Cc6634C0532925a3b844Bc9e7595f2bD1e"}'
```
```python Python theme={null}
response = httpx.post(
"https://api.credprotocol.com/mcp/agents/1/reputation",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"address": "0x742d35Cc6634C0532925a3b844Bc9e7595f2bD1e",
"tags": ["creditScore", "sybilRisk"]
}
)
```
**Response (202 Accepted):**
```json theme={null}
{
"submission_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"agent_id": 1,
"status": "pending",
"estimated_completion_seconds": 45,
"status_url": "/api/v2/agents/1/reputation/status/a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"tags": ["creditScore", "sybilRisk", "identityCount"],
"source": "live"
}
```
***
### get\_agent\_reputation
Read the on-chain reputation summary for an AI agent from the ERC-8004 Reputation Registry.
ERC-8004 agent ID (>= 1)
**Costs 1 Cred Unit.**
```bash cURL theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/agents/1/reputation"
```
```python Python theme={null}
response = httpx.get(
"https://api.credprotocol.com/mcp/agents/1/reputation",
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
```
**Response:**
```json theme={null}
{
"agent_id": 1,
"summaries": [
{
"tag1": "credprotocol.com",
"tag2": "creditScore",
"count": 15,
"summary_value": 745.5,
"summary_value_decimals": 1
},
{
"tag1": "credprotocol.com",
"tag2": "sybilRisk",
"count": 15,
"summary_value": 28.3,
"summary_value_decimals": 1
}
],
"source": "live"
}
```
***
### get\_reputation\_status
Check the status of an on-chain reputation submission.
ERC-8004 agent ID
Submission UUID returned by `submit_agent_reputation`
**Status values:** `pending` → `computing` → `submitting` → `confirmed` (or `failed`)
```bash cURL theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.credprotocol.com/mcp/agents/1/reputation/status/a1b2c3d4-e5f6-7890-abcd-ef1234567890"
```
```python Python theme={null}
response = httpx.get(
"https://api.credprotocol.com/mcp/agents/1/reputation/status/a1b2c3d4-e5f6-7890-abcd-ef1234567890",
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
```
**Response:**
```json theme={null}
{
"submission_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"agent_id": 1,
"status": "confirmed",
"scores": {
"credit_score": 780,
"sybil_score": 22,
"identity_count": 4
},
"transactions": [
{
"tag1": "credprotocol.com",
"transaction_hash": "0xabc123...",
"block_number": 12345678,
"gas_used": 145000
}
],
"feedback_uri": "https://api.credprotocol.com/api/v2/agents/1/reputation/feedback/a1b2c3d4...",
"source": "live"
}
```
***
## Supported Chains
| Chain | ID |
| - | - |
| Ethereum | 1 |
| Optimism | 10 |
| BSC | 56 |
| Polygon | 137 |
| Base | 8453 |
| Arbitrum | 42161 |
| Celo | 42220 |
| Avalanche | 43114 |
| Scroll | 534352 |
| Linea | 59144 |
***
## Error Handling
All endpoints return consistent error responses:
```json theme={null}
{
"error": "Invalid Ethereum address format: abc123",
"status_code": 400
}
```
Common error codes:
* `400` - Invalid request (bad address format, missing parameters)
* `401` - Authentication required (missing or invalid API key)
* `404` - Resource not found (agent doesn't exist)
* `503` - API connection failed
* `504` - Request timeout
# Model Release Notes
Source: https://docs.credprotocol.com/model-release-notes
Version history and updates for the Cred Score model
Cred Protocol is continually ingesting on-chain data to train and test our credit models. This page contains the main highlights of each model version update.
***
### Andromeda 1.2
**September 2026**
Andromeda 1.2 extends borrowing history to Compound.
**What changed:**
* Repayment and liquidation history on Compound V3 (Comet) on Ethereum and Base, and on Compound V2 on Ethereum, now contributes to the **Borrowing History** and **Wallet Health** factors in the same way as Aave
* Compound V3 has no explicit borrow or repay events: a base-asset withdrawal beyond the supplied balance is recorded as a `borrow` and a base-asset supply against open debt as a `repay`
* Compound V2 liquidations are recorded once, as liquidations; the repayment the protocol books internally during a liquidation is not counted as a voluntary repayment
* `credit_events.pools[]` gains `market` and `feeds_score`
**What did not change:**
* The model's weights and score range are the same as Andromeda 1.1
* Addresses with no Compound borrowing history receive the same score as before
Responses report `model_version: "andromeda_1.2"`.
***
### Andromeda 1.1
**September 2026**
Andromeda 1.1 adds borrowing behaviour read directly from lending-protocol events. Scores now reflect what an address has done with its loans, in addition to what it currently holds.
**What changed:**
* Repayment and liquidation history on Aave V2 and V3 (Ethereum) and Aave V3 (Base) now contribute to the **Borrowing History** and **Wallet Health** factors
* Addresses that borrowed and repaid in the past are recognised as having credit history, even if they hold no open positions today
* Liquidations lower the score; each additional liquidation lowers it further
* Repayments raise the score, with diminishing effect, so a large number of repayments cannot inflate it
* Reports include a new `credit_events` section with per-pool event counts and coverage
**What did not change:**
* The model's weights and score range (300-1000) are the same as Andromeda 1.0
* Addresses with no Aave borrowing history receive the same score as before
Responses report `model_version: "andromeda_1.1"`.
***
### Andromeda 1.0
**December 2024**
We are excited to announce the release of Andromeda 1.0, a major new generation of the Cred Score model. This release represents a significant advancement in on-chain credit scoring with improved accuracy and expanded coverage.
**Key improvements:**
* Enhanced multi-chain analysis across 10 supported networks
* Improved scoring factors: Borrowing History, Wallet Composition, Wallet Health, Interactions, Trust, and New Credit
* Better detection of identity attestations including ENS, Gitcoin Passport, and POAPs
* Expanded lending protocol coverage for Aave V3 on Base
* More accurate evaluation of stablecoin holdings and portfolio diversity
* Refined time-weighting algorithms for more current score assessments
***
### v1.5.1
**28 Dec 2023**
The latest model has been updated to better reward accounts with stable token composition in their wallets. We have also addressed a small bug for accounts on the Celo blockchain.
### v1.5.0
**09 Sept 2023**
The Cred Score, Report and Summary API now have complete coverage of non-lending behaviour on Celo. Accounts with activity on Celo will now have this taken into account in their score and report.
### v1.4.6
**30 Aug 2023**
The Cred Score now includes data from Impact Market and Good Dollar on the Celo blockchain. These universal basic income (UBI) protocols enable users to build a financial history, which can then be scored by Cred Protocol.
### v1.4.5
**29 June 2023**
The Cred Score, Report and Summary API now have complete coverage of borrowing behaviour on Radiant V2 on Arbitrum and Binance Smart Chain.
### v1.4.4
**6 June 2023**
The latest model release considers limited or no-borrowing history more conservatively resulting in declines in Cred Score for these accounts. Overall, the score is slightly more conservative for the majority of accounts.
### v1.4.3
**24 May 2023**
We have adjusted the time-weighting of Cred Scores. This feature applies a decay factor to events based on their recency, resulting in more up-to-date scores. By reducing the weight of past events, we provide you with more relevant and contextually accurate scores.
### v1.4.2
**17 May 2023**
The Cred Score, Report and Summary API now have complete coverage of borrowing behaviour on Banker Joe on Avalanche.
### v1.4.1
**11 May 2023**
The Cred Score, Report and Summary API now have complete coverage of borrowing behaviour on Geist Finance on Fantom.
### v1.4.0
**9 May 2023**
We are happy to announce that the Cred Score, Report and Summary APIs are now cross-chain for all accounts with activity on Polygon! To do this, we have integrated new non-lending features on Polygon.
### v1.3.4
**13 April 2023**
The Cred Score, Report and Summary API now have complete coverage of borrowing behaviour on Iron Bank Protocol on Avalanche, Ethereum and Fantom.
### v1.3.3
**6 April 2023**
The Cred Score, Report and Summary API now have complete coverage of borrowing behaviour on Iron Bank Protocol on Avalanche.
### v1.3.2
**30 March 2023**
The Cred Score, Report and Summary API now have complete coverage of borrowing behaviour on Venus Protocol.
### v1.3.1
**28 March 2023**
The latest model considers limited- or no- borrowing history more conservatively resulting in \~5-10 point decline in Cred Score. We have also introduced a new non-lending feature that rewards accounts with substantial cross-chain activity.
### v1.3.0
**27 March 2023**
The Cred Score, Report and Summary API now have complete coverage of non-lending behaviour on Optimism. Accounts with activity on Optimism will now have this taken into account in their score and report.
### v1.2.1
**24 March 2023**
The Cred Score, Report and Summary API now have complete coverage of borrowing behaviour on Vesta Finance.
### v1.2.0
**22 March 2023**
We are happy to announce that the Cred Score model is now cross-chain for all of its non-lending features. Accounts with transactions on Arbitrum will now have this activity reflected in the score.
To do this, we have integrated new non-lending features on these chains to enable a cred score for any account regardless of whether they have borrowing history or not.
### v1.1.5
**20 March 2023**
The Cred Score model now has coverage of borrowing behaviour on Radiant v1 on Arbitrum.
### v1.1.4
**17 March 2023**
The Cred Score model has been updated to greater reward borrowers that have made multiple regular repayments on their loans. This change underlines our commitment to incentivise and reward borrowers who are active custodians of creditworthiness.
### v1.1.3
**9 March 2023**
The Cred Score model now has coverage of borrowing behaviour on Liquity.
### v1.1.2
**2 March 2023**
The Score model now has complete coverage of borrowing behaviour across all chains for Aave v3 (Arbitrum, Avalanche, Fantom, Optimism, Polygon & Ethereum).
### v1.1.1
**22 February 2023**
The Score is now informed by borrowing history on the recently launched Aave V3 on Ethereum. In addition, the score now also assesses the liquidity of tokens in a wallet.
A more conservative approach has been taken to users with limited or no borrowing history resulting in a \~25 point decline in the Cred Score.
### v1.1.0
**14 February 2023**
The latest upgrade to our crypto credit score model now features support for MakerDAO protocol.
As one of the earliest and most prominent protocols in the cryptocurrency space, we recognise its significance in shaping the industry. With this addition, our credit scoring system ingests data from MakerDAO, Aave V2, Compound V2 and Teller V2, providing a more comprehensive score.
### v1.0.6
**10 February 2023**
The latest model considers limited- or no- borrowing history more conservatively resulting in \~25 point decline in Cred Score. Informed by transaction and borrowing activity associated with capital-efficient and under-collateralized lending, the consequence of loan "default" now has an even greater effect on creditworthiness.
### v1.0.5
**3 January 2023**
Enhanced evaluation of loan liquidations, delinquencies and defaults, resulting in lower scores for accounts associated with these events.
### v1.0.4
**16 December 2022**
Update in model parameters to slightly boost the Cred scores of those with strong lending history and significantly reduce scores of those with limited lending history and/or sequential liquidations.
Fix on errors for accounts with both Aave V2 Ethereum and Teller V2 Ethereum / Polygon history.
### v1.0.3
**2 December 2022**
Inclusion of new features related to the quality of tokens within the wallet.
A tweak in how we assess accounts with no borrowing history. The new model places more emphasis on previous borrowing history and so those accounts without borrowing history have seen their scores fall 10-14%.
### v1.0.2
**8 November 2022**
Significant upgrades to the universal feature set which is greatly expanded to improve wallet creditworthiness evaluation and increase accuracy. The model now takes into account attributes covering a wide variety of factors.
### v1.0.1
**9 September 2022**
Merging of the previous multi-track model into the universal Cred Score model which retains the strong predictive power for borrowing-related outcomes but also capitalizes on the flexibility offered by the universal feature set.
### v1.0.0
**7 July 2022**
Initial release of the Cred Score model.
# Quickstart
Source: https://docs.credprotocol.com/quickstart
Get started with Cred Protocol API in under 5 minutes
## Prerequisites
Before you begin, you'll need:
* A Cred Protocol account ([sign up here](https://app.credprotocol.com))
* An API key from your [Dashboard](https://app.credprotocol.com/dashboard)
## Get Your API Key
Go to [app.credprotocol.com](https://app.credprotocol.com) and log in to your account.
Click on **API Keys** in the sidebar to access your API key management.
Click **Create API Key**, give it a name, and copy your new API key.
Store your API key securely. You won't be able to see it again after creation.
## Make Your First Request
### Get a Credit Score
Use the following request to get a credit score for an Ethereum address:
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/score/address/vitalik.eth" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const response = await fetch('https://api.credprotocol.com/api/v2/score/address/vitalik.eth', {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const data = await response.json();
console.log(data);
```
```python Python theme={null}
import requests
response = requests.get(
'https://api.credprotocol.com/api/v2/score/address/vitalik.eth',
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
data = response.json()
print(data)
```
### Example Response
```json theme={null}
{
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"score": 847,
"decile": 7,
"range": "very_good",
"model_version": "andromeda_1.1",
"timestamp": "2024-01-15T10:30:00Z"
}
```
## Or Use an SDK
If you're gating access to a product rather than pulling raw scores, the SDKs wrap the trust-evaluation API (`/v1/evaluate`) — one call returns a 0–100 trust score, a tier, and pass/fail against a policy template. Framework middleware for Express, Hono, Next.js and FastAPI turns that into a one-line guard.
```typescript TypeScript theme={null}
// npm install @cred-protocol/sdk
import { CredClient } from '@cred-protocol/sdk'
const cred = new CredClient({ apiKey: process.env.CRED_API_KEY })
const result = await cred.evaluate({
walletAddress: 'vitalik.eth',
policy: 'standard',
})
console.log(result.trustScore, result.trustTier, result.allPassed)
```
```python Python theme={null}
# pip install cred-protocol
from cred_protocol import CredClient
async with CredClient(api_key="cred_sk_...") as cred:
result = await cred.evaluate(wallet_address="vitalik.eth", policy="standard")
print(result.trust_score, result.trust_tier, result.all_passed)
```
See the [SDK overview](/sdks/overview) for the adapters and policy templates.
## Understanding the Response
| Field | Description |
| - | - |
| `address` | The resolved Ethereum address |
| `score` | Credit score between 300-1000 |
| `decile` | Score decile (1-10) |
| `range` | Score range (low, fair, good, very\_good, excellent) |
| `model_version` | Scoring model version (currently "andromeda\_1.1") |
| `timestamp` | When the score was calculated |
## Test with Sandbox
Before integrating with production data, use our sandbox endpoints to test your integration:
```bash cURL theme={null}
curl -X GET "https://api.credprotocol.com/api/v2/sandbox/score/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://api.credprotocol.com/api/v2/sandbox/score/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17',
{
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
const data = await response.json();
```
```python Python theme={null}
import requests
response = requests.get(
'https://api.credprotocol.com/api/v2/sandbox/score/address/0x742d35Cc6634C0532925a3b844Bc9e7595f0Ab17',
headers={'Authorization': 'Bearer YOUR_API_KEY'}
)
```
Sandbox endpoints return deterministic mock data and don't count against your API quota.
## Next Steps
Generate comprehensive credit reports
Verify on-chain identity attestations
Learn how to handle API errors
Deep dive into API authentication
TypeScript, Python, and framework middleware
Pay per request with x402 or MPP — no account needed
# Express Middleware
Source: https://docs.credprotocol.com/sdks/express
Trust-gating middleware for Express.js APIs
## Installation
```bash theme={null}
npm install @cred-protocol/express @cred-protocol/sdk
```
## Quick Start
```typescript theme={null}
import express from 'express'
import { credGates } from '@cred-protocol/express'
const app = express()
app.use('/api', credGates({
apiKey: process.env.CRED_API_KEY,
policy: 'standard',
}))
app.get('/api/resource', (req, res) => {
const trust = req.credTrust!
res.json({ data: '...', tier: trust.trustTier })
})
app.listen(3000)
```
## Configuration
```typescript theme={null}
credGates({
// Required
apiKey: process.env.CRED_API_KEY,
// Policy (pick one)
policy: 'standard', // Named template
// gates: ['human', 'verified'], // Or custom gates
// operator: 'AND',
// Dynamic pricing
pricing: {
enabled: true,
curve: 'step',
basePriceUsdc: 0.01,
},
// Failure handling
on402: 'challenge', // 'challenge' (402), 'deny' (403), 'pass'
// Response headers
headers: true, // X-Cred-Trust-Score, X-Cred-Trust-Tier
// Custom wallet extraction
extractWallet: (req) => req.headers['x-agent-wallet'] as string,
})
```
## Wallet Address Extraction
By default the middleware checks:
1. `X-Wallet-Address` request header
2. `?wallet=` query parameter
Override with `extractWallet`:
```typescript theme={null}
credGates({
apiKey: process.env.CRED_API_KEY,
policy: 'standard',
extractWallet: (req) => {
// From a JWT, session, or custom header
return req.headers['x-agent-wallet'] as string || null
},
})
```
## Accessing Trust Data
The middleware attaches the result to `req.credTrust`:
```typescript theme={null}
app.get('/api/profile', (req, res) => {
const trust = req.credTrust!
res.json({
wallet: trust.walletAddress,
score: trust.trustScore,
tier: trust.trustTier,
confidence: trust.confidence,
gates: trust.gateResults,
})
})
```
## Response Headers
When `headers: true` (default), every response includes:
| Header | Example | Description |
| - | - | - |
| `X-Cred-Trust-Score` | `75` | 0–100 composite score |
| `X-Cred-Trust-Tier` | `verified` | Trust tier classification |
| `X-Cred-Request-Id` | `a1b2c3d4-...` | Request ID for debugging |
| `X-Cred-Price-Multiplier` | `0.25` | Price multiplier (if pricing enabled) |
## Error Handling
The middleware catches errors and passes them to Express error handling:
```typescript theme={null}
// Errors from the Cred API are forwarded via next(err)
app.use((err, req, res, next) => {
console.error('Trust evaluation error:', err)
res.status(500).json({ error: 'Internal server error' })
})
```
| Response | When |
| - | - |
| `400` | No wallet address found on the request |
| `402` | Gates failed, `on402: 'challenge'` — includes challenge body |
| `403` | Gates failed with `on402: 'deny'`, or wallet is `blocked` |
| `429` | Cred API rate limit exceeded |
| `502` | Upstream gate provider error |
# Hono Middleware
Source: https://docs.credprotocol.com/sdks/hono
Drop-in trust-gating middleware for Hono
## Installation
```bash theme={null}
npm install @cred-protocol/hono @cred-protocol/sdk
```
## Quick Start
```typescript theme={null}
import { Hono } from 'hono'
import { credGates } from '@cred-protocol/hono'
const app = new Hono()
app.use('/api/*', credGates({
apiKey: process.env.CRED_API_KEY,
policy: 'standard',
}))
app.get('/api/resource', (c) => {
const trust = c.get('credTrust')
return c.json({ data: '...', trustTier: trust.trustTier })
})
```
Every request to `/api/*` is evaluated. Wallets that fail the `standard` policy get a 402 challenge response. Wallets that pass get the trust result on `c.get('credTrust')`.
## Configuration
```typescript theme={null}
credGates({
// Required
apiKey: process.env.CRED_API_KEY,
// Policy (pick one)
policy: 'standard', // Named template
// gates: ['human', 'verified'], // Or custom gates
// operator: 'AND',
// Dynamic pricing
pricing: {
enabled: true,
curve: 'step', // 'linear', 'exponential', 'step'
basePriceUsdc: 0.01,
},
// Failure handling
on402: 'challenge', // 'challenge' (402), 'deny' (403), 'pass' (allow)
onBlocked: 'deny', // 'deny' (403), 'challenge' (402), 'pass'
// Response headers
headers: true, // Set X-Cred-Trust-Score, X-Cred-Trust-Tier
// Custom wallet extraction
extractWallet: (c) => c.req.header('X-Agent-Wallet'),
// Callback for logging/analytics
onEvaluation: (result, c) => {
console.log(`${result.walletAddress}: ${result.trustTier} (${result.trustScore})`)
},
})
```
## Wallet Address Extraction
By default the middleware checks (in order):
1. `X-Wallet-Address` request header
2. `?wallet=` query parameter
If neither is present, it returns a `400`. Override with `extractWallet`:
```typescript theme={null}
credGates({
apiKey: process.env.CRED_API_KEY,
policy: 'standard',
extractWallet: (c) => {
// Extract from JWT, session, or custom header
return c.req.header('X-Agent-Wallet') || c.req.query('address')
},
})
```
## Response Headers
When `headers: true` (default), every response includes:
| Header | Example | Description |
| - | - | - |
| `X-Cred-Trust-Score` | `75` | 0–100 composite score |
| `X-Cred-Trust-Tier` | `verified` | Trust tier classification |
| `X-Cred-Request-Id` | `a1b2c3d4-...` | Request ID for debugging |
| `X-Cred-Price-Multiplier` | `0.25` | Dynamic price multiplier (if pricing enabled) |
## Failure Modes
### on402: 'challenge' (default)
When gates fail, returns a 402 with a machine-readable challenge body:
```json theme={null}
{
"type": "trust_challenge",
"trust_score": 25,
"trust_tier": "untrusted",
"failed_gates": [
{ "gate_id": "verified", "gate_name": "Identity Verification", "passed": false }
],
"message": "Wallet did not pass required trust checks"
}
```
### on402: 'deny'
Returns a simple 403:
```json theme={null}
{
"error": "Trust requirements not met",
"trustTier": "untrusted",
"trustScore": 25,
"failedGates": ["verified"]
}
```
### on402: 'pass'
Allows the request through with trust headers set. Use this for logging/monitoring without blocking.
## Dynamic Pricing Example
Gate your API with trust-based pricing — trusted wallets pay less:
```typescript theme={null}
app.use('/api/*', credGates({
apiKey: process.env.CRED_API_KEY,
policy: 'reputation',
pricing: { enabled: true, curve: 'step', basePriceUsdc: 0.01 },
on402: 'challenge',
headers: true,
}))
app.post('/api/generate', (c) => {
const trust = c.get('credTrust')
// trust.priceMultiplier:
// trusted (80+) → 0.0 (free)
// verified (60-79) → 0.25 ($0.0025)
// limited (30-59) → 0.5 ($0.005)
// untrusted (1-29) → 1.0 ($0.01)
return c.json({
result: '...',
price: trust.suggestedPriceUsdc,
})
})
```
## Accessing Trust Data in Handlers
The trust result is stored via `c.set('credTrust', result)` and accessible in any downstream handler:
```typescript theme={null}
app.get('/api/profile', (c) => {
const trust = c.get('credTrust')
return c.json({
wallet: trust.walletAddress,
score: trust.trustScore,
tier: trust.trustTier,
gates: trust.gateResults.map(g => ({
gate: g.gateId,
passed: g.passed,
score: g.score,
})),
})
})
```
# Next.js Middleware
Source: https://docs.credprotocol.com/sdks/nextjs
Trust-gating middleware for Next.js edge runtime
## Installation
```bash theme={null}
npm install @cred-protocol/nextjs @cred-protocol/sdk
```
## Quick Start
Create `middleware.ts` in your project root:
```typescript theme={null}
// middleware.ts
import { credGates } from '@cred-protocol/nextjs'
export const middleware = credGates({
apiKey: process.env.CRED_API_KEY!,
policy: 'standard',
matcher: ['/api/:path*'],
})
export const config = {
matcher: ['/api/:path*'],
}
```
Every request to `/api/*` is evaluated before reaching your route handler. Wallets that fail the trust check receive a 402 or 403 response at the edge — your API handlers only see trusted traffic.
## Configuration
```typescript theme={null}
credGates({
// Required
apiKey: process.env.CRED_API_KEY!,
// Policy (pick one)
policy: 'standard',
// gates: ['human', 'verified'],
// operator: 'AND',
// Route matching
matcher: ['/api/:path*'], // Only gate these routes
// Dynamic pricing
pricing: {
enabled: true,
curve: 'step',
basePriceUsdc: 0.01,
},
// Failure handling
on402: 'challenge', // 'challenge' (402), 'deny' (403), 'pass'
// Custom wallet extraction
extractWallet: (req) => req.headers.get('x-agent-wallet'),
})
```
## Wallet Address Extraction
By default the middleware checks:
1. `X-Wallet-Address` request header
2. `?wallet=` query parameter
Override with `extractWallet`:
```typescript theme={null}
credGates({
apiKey: process.env.CRED_API_KEY!,
policy: 'standard',
matcher: ['/api/:path*'],
extractWallet: (req) => {
return req.headers.get('x-agent-wallet')
|| req.nextUrl.searchParams.get('address')
},
})
```
## Response Headers
Requests that pass trust checks get these headers set on the response:
| Header | Example | Description |
| - | - | - |
| `X-Cred-Trust-Score` | `75` | 0–100 composite score |
| `X-Cred-Trust-Tier` | `verified` | Trust tier classification |
| `X-Cred-Request-Id` | `a1b2c3d4-...` | Request ID for debugging |
| `X-Cred-Price-Multiplier` | `0.25` | Price multiplier (if pricing enabled) |
Read these in your API route handlers:
```typescript theme={null}
// app/api/resource/route.ts
import { NextRequest, NextResponse } from 'next/server'
export async function GET(req: NextRequest) {
const trustScore = req.headers.get('x-cred-trust-score')
const trustTier = req.headers.get('x-cred-trust-tier')
return NextResponse.json({
data: '...',
trustScore,
trustTier,
})
}
```
## Route Matching
The `matcher` option controls which routes are trust-gated. Routes that don't match pass through without evaluation.
```typescript theme={null}
credGates({
apiKey: process.env.CRED_API_KEY!,
policy: 'standard',
matcher: [
'/api/:path*', // All API routes
'/protected/:path*', // Protected pages
],
})
```
Also set `config.matcher` in your `middleware.ts` export so Next.js only runs the middleware on matching routes. This avoids unnecessary edge function invocations.
## Failure Responses
| Response | When |
| - | - |
| `400` | No wallet address found on the request |
| `402` | Gates failed, `on402: 'challenge'` — includes challenge body |
| `403` | Gates failed with `on402: 'deny'`, or wallet is `blocked` |
| `429` | Cred API rate limit exceeded |
| `502` | Upstream gate provider error |
# SDK Overview
Source: https://docs.credprotocol.com/sdks/overview
Drop-in trust evaluation for any framework — TypeScript, Python, and middleware for Hono, Express, Next.js, and FastAPI
## Why Use an SDK?
The Cred Evaluation API returns a trust score, trust tier, per-gate breakdown, and optional dynamic pricing for any wallet address. You can call it directly with `fetch` or `httpx`, but the SDK packages give you:
* **Typed responses** — full TypeScript types and Python dataclasses, no parsing raw JSON
* **Framework middleware** — one line to gate every route with trust checks
* **Automatic 402/403 handling** — challenges and denials built in
* **Trust headers** — `X-Cred-Trust-Score` and `X-Cred-Trust-Tier` set on every response
* **Dynamic pricing** — trust-score-based price multipliers computed server-side
## Available Packages
Core client for Node.js, Deno, Bun, and edge runtimes. Zero dependencies beyond `fetch`.
Drop-in middleware for Hono. One line to trust-gate your API.
Express middleware with `req.credTrust` for downstream handlers.
Next.js edge middleware with route matching.
Async client and FastAPI `Depends()` integration.
## How It Works
Every SDK package calls the same backend endpoint:
```
POST https://validator.credprotocol.com/v1/evaluate
Authorization: Bearer cred_sk_...
```
The response includes:
| Field | Description |
| - | - |
| `trust_score` | 0–100 normalized composite score |
| `trust_tier` | `trusted`, `verified`, `limited`, `untrusted`, or `blocked` |
| `gate_results` | Per-gate pass/fail with scores |
| `confidence` | 0.0–1.0 based on data availability |
| `price_multiplier` | Dynamic pricing multiplier (if enabled) |
| `reputation` | Behavioral history from ERC-8004 feedback |
| `challenge` | Pre-built 402 challenge body (if gates failed) |
The middleware packages wrap this into framework-native patterns — Hono `c.set()`, Express `req.credTrust`, Next.js response headers, FastAPI `Depends()`.
## Trust Tiers
| Tier | Score | Meaning |
| - | - | - |
| **Trusted** | 80–100 | Full access, lowest pricing. Proven track record. |
| **Verified** | 60–79 | Standard access, standard pricing. |
| **Limited** | 30–59 | Restricted access, elevated pricing. |
| **Untrusted** | 1–29 | Minimal access, maximum pricing. |
| **Blocked** | 0 | Access denied. Critical gate failure. |
## Policy Templates
Instead of configuring individual gates, use a named policy template:
| Template | Gates | Best For |
| - | - | - |
| `basic` | Human check only | Bot filtering, basic API protection |
| `standard` | Human + identity verification | General API protection (recommended default) |
| `strict` | Human + identity + established wallet | Financial services, sensitive data |
| `financial` | All gates, tight thresholds | Lending, payments, credit |
| `reputation` | Weighted composite, dynamic pricing | Tiered access, trust-to-earn |
| `quick` | Human check, relaxed threshold | Low-stakes endpoints |
## Getting Your API Key
The same API key works for both the Credit Scoring API (`api.credprotocol.com`) and the Trust Evaluation API (`validator.credprotocol.com`). One key, every Cred service.
Go to [app.credprotocol.com](https://app.credprotocol.com) and create an account.
Navigate to **API Keys** in the dashboard and click **Create API Key**. Copy the key — it is shown exactly once.
```bash theme={null}
export CRED_API_KEY=your_api_key_here
```
Your API key works across all Cred endpoints — credit scores, reports, identity attestations, and trust evaluation. No separate keys needed.
## Next Steps
Pick the package that matches your stack and follow the integration guide:
* [TypeScript SDK](/sdks/typescript) — if you want full control
* [Hono Middleware](/sdks/hono) — fastest path for Hono/Cloudflare Workers
* [Express Middleware](/sdks/express) — for Express/Node.js APIs
* [Next.js Middleware](/sdks/nextjs) — for Next.js edge middleware
* [Python SDK](/sdks/python) — for Python/FastAPI services
# Python SDK
Source: https://docs.credprotocol.com/sdks/python
Async Python client and FastAPI middleware for Cred Protocol
## Installation
```bash theme={null}
# Core client
pip install cred-protocol
# With FastAPI integration
pip install cred-protocol[fastapi]
```
## Quick Start
```python theme={null}
import asyncio
from cred_protocol import CredClient
async def main():
async with CredClient(api_key="cred_sk_...") as cred:
result = await cred.evaluate(
wallet_address="0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
policy="standard",
)
print(result.trust_score) # 75
print(result.trust_tier) # TrustTier.VERIFIED
print(result.all_passed) # True
asyncio.run(main())
```
## Evaluate Options
### Using a Policy Template
```python theme={null}
result = await cred.evaluate(
wallet_address="0x...",
policy="standard",
)
```
### Using Custom Gates
```python theme={null}
result = await cred.evaluate(
wallet_address="0x...",
gates=["human", "verified", "established"],
operator="WEIGHTED",
weights={"human": 0.4, "verified": 0.35, "established": 0.25},
composite_threshold=60,
)
```
### With Dynamic Pricing
```python theme={null}
result = await cred.evaluate(
wallet_address="0x...",
policy="reputation",
include_pricing=True,
base_price_usdc=0.01,
)
print(result.price_multiplier) # 0.25
print(result.suggested_price_usdc) # 0.0025
```
## TrustResult Fields
| Field | Type | Description |
| - | - | - |
| `wallet_address` | `str` | The evaluated wallet |
| `trust_score` | `int` | 0–100 composite score |
| `trust_tier` | `TrustTier` | `TRUSTED`, `VERIFIED`, `LIMITED`, `UNTRUSTED`, `BLOCKED` |
| `confidence` | `float` | 0.0–1.0 data confidence |
| `all_passed` | `bool` | Whether all gates passed |
| `gate_results` | `list[GateScoreBreakdown]` | Per-gate breakdown |
| `price_multiplier` | `float \| None` | Dynamic pricing multiplier |
| `suggested_price_usdc` | `float \| None` | Computed price |
| `reputation` | `WalletReputation \| None` | Behavioral history |
| `cached` | `bool` | Whether this was a cache hit |
| `request_id` | `str` | Unique request ID |
| `challenge` | `dict \| None` | 402 challenge body (if gates failed) |
## Error Handling
```python theme={null}
from cred_protocol import CredClient, CredAPIError
try:
result = await cred.evaluate(wallet_address="0x...", policy="standard")
except CredAPIError as e:
print(e.status) # 401, 429, etc.
print(e.body) # Error details
```
## FastAPI Integration
The `require_trust()` dependency gates endpoints with a single line:
```python theme={null}
import os
from fastapi import Depends, FastAPI
from cred_protocol.fastapi import require_trust
from cred_protocol import TrustResult
app = FastAPI()
@app.get("/resource")
async def get_resource(
trust: TrustResult = Depends(require_trust(
api_key=os.environ["CRED_API_KEY"],
policy="standard",
)),
):
return {
"data": "...",
"wallet": trust.wallet_address,
"score": trust.trust_score,
"tier": trust.trust_tier.value,
}
```
### FastAPI Configuration
```python theme={null}
require_trust(
api_key="cred_sk_...", # Or set CRED_API_KEY env var
base_url="https://...", # Defaults to production
policy="standard", # Named template
# gates=["human", "verified"], # Or custom gates
# operator="AND",
include_pricing=False,
base_price_usdc=None,
on_fail="deny", # "deny" (403), "challenge" (402), "pass"
)
```
### Wallet Extraction
The FastAPI dependency checks (in order):
1. `X-Wallet-Address` request header
2. `?wallet=` query parameter
Override with a custom extractor:
```python theme={null}
from fastapi import Request
from cred_protocol.fastapi import CredTrustDependency
trust_dep = CredTrustDependency(
api_key=os.environ["CRED_API_KEY"],
policy="standard",
extract_wallet=lambda req: req.headers.get("x-agent-wallet"),
)
@app.get("/resource")
async def get_resource(trust: TrustResult = Depends(trust_dep)):
...
```
### Failure Responses
| Response | When |
| - | - |
| `400` | No wallet address found on the request |
| `402` | Gates failed, `on_fail="challenge"` |
| `403` | Gates failed with `on_fail="deny"`, or wallet is `blocked` |
| `429` | Cred API rate limit exceeded |
| `502` | Upstream gate provider error |
## Using Without FastAPI
The core `CredClient` works with any async Python code:
```python theme={null}
from cred_protocol import CredClient
# As async context manager (recommended)
async with CredClient(api_key="cred_sk_...") as cred:
result = await cred.evaluate(wallet_address="0x...", policy="standard")
# Or manage lifecycle manually
cred = CredClient(api_key="cred_sk_...")
result = await cred.evaluate(wallet_address="0x...", policy="standard")
await cred.close()
```
# TypeScript SDK
Source: https://docs.credprotocol.com/sdks/typescript
Core TypeScript client for the Cred Protocol evaluation API
## Installation
```bash theme={null}
npm install @cred-protocol/sdk
```
## Quick Start
```typescript theme={null}
import { CredClient } from '@cred-protocol/sdk'
const cred = new CredClient({ apiKey: process.env.CRED_API_KEY })
const result = await cred.evaluate({
walletAddress: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045',
policy: 'standard',
})
console.log(result.trustScore) // 75
console.log(result.trustTier) // "verified"
console.log(result.allPassed) // true
```
## Configuration
```typescript theme={null}
const cred = new CredClient({
apiKey: 'cred_sk_...', // Required
baseUrl: 'https://...', // Optional, defaults to production
})
```
## Evaluate Options
### Using a Policy Template
The simplest way to evaluate — pick a template that matches your use case:
```typescript theme={null}
const result = await cred.evaluate({
walletAddress: '0x...',
policy: 'standard', // "basic", "standard", "strict", "financial", "reputation", "quick"
})
```
### Using Custom Gates
For full control, specify individual gates:
```typescript theme={null}
const result = await cred.evaluate({
walletAddress: '0x...',
gates: ['human', 'verified', 'established'],
operator: 'WEIGHTED',
weights: { human: 0.4, verified: 0.35, established: 0.25 },
compositeThreshold: 60,
})
```
### With Dynamic Pricing
Compute trust-based pricing for your API:
```typescript theme={null}
const result = await cred.evaluate({
walletAddress: '0x...',
policy: 'reputation',
includePricing: true,
basePriceUsdc: 0.01, // Your full price
})
console.log(result.priceMultiplier) // 0.25 (verified tier)
console.log(result.suggestedPriceUsdc) // 0.0025
```
### With Reputation Data
```typescript theme={null}
const result = await cred.evaluate({
walletAddress: '0x...',
policy: 'standard',
includeReputation: true, // Enabled by default
})
if (result.reputation) {
console.log(result.reputation.settlementRate) // 0.95
console.log(result.reputation.totalEvaluations) // 47
console.log(result.reputation.riskFlags) // []
}
```
## Response Types
### TrustResult
The `evaluate()` method returns a `TrustResult`:
| Field | Type | Description |
| - | - | - |
| `walletAddress` | `string` | The evaluated wallet |
| `trustScore` | `number` | 0–100 composite score |
| `trustTier` | `TrustTier` | `trusted`, `verified`, `limited`, `untrusted`, `blocked` |
| `confidence` | `number` | 0.0–1.0 data confidence |
| `allPassed` | `boolean` | Whether all gates passed |
| `gateResults` | `GateScoreBreakdown[]` | Per-gate breakdown |
| `priceMultiplier` | `number \| null` | Dynamic pricing multiplier |
| `suggestedPriceUsdc` | `number \| null` | Computed price |
| `reputation` | `WalletReputation \| null` | Behavioral history |
| `cached` | `boolean` | Whether this was a cache hit |
| `requestId` | `string` | Unique request ID for debugging |
| `challenge` | `object \| null` | 402 challenge body (if gates failed) |
| `raw` | `EvaluationResponse` | Full API response |
### GateScoreBreakdown
| Field | Type | Description |
| - | - | - |
| `gateId` | `string` | Gate identifier (e.g., `"human"`) |
| `gateName` | `string` | Human-readable name |
| `passed` | `boolean` | Whether this gate passed |
| `score` | `number \| null` | 0–100 gate score |
| `provider` | `string` | `"cred"` or third-party name |
## Error Handling
```typescript theme={null}
import { CredClient, CredAPIError } from '@cred-protocol/sdk'
try {
const result = await cred.evaluate({ walletAddress: '0x...', policy: 'standard' })
} catch (err) {
if (err instanceof CredAPIError) {
console.log(err.status) // 401, 429, etc.
console.log(err.body) // Error details
}
}
```
| Status | Meaning |
| - | - |
| `400` | Bad request — unknown policy or missing fields |
| `401` | Invalid or missing API key |
| `429` | Rate limit exceeded |
| `502` | Upstream gate provider error |
## Framework Middleware
The core SDK is used by all framework middleware packages. If you're using Hono, Express, Next.js, or FastAPI, see the dedicated middleware guides — they handle wallet extraction, 402 challenges, and trust headers automatically.
Drop-in Hono middleware
Express middleware
Next.js edge middleware
Python + FastAPI
# Capital-Efficient Lending
Source: https://docs.credprotocol.com/use-cases/capital-efficient-lending
Reduce collateral requirements based on creditworthiness while maintaining safety
Capital-efficient lending uses credit scores and reports to lower collateral requirements for qualified borrowers—while still remaining over-collateralized. This approach unlocks significant value for borrowers and lenders alike, serving as a practical stepping stone toward full under-collateralized lending.
## The Problem with Fixed Collateral Ratios
Most DeFi lending protocols use fixed collateral requirements regardless of borrower creditworthiness:
| Protocol | Typical Collateral Ratio | Borrowing Power |
| - | - | - |
| Aave | 150-200% | Borrow $50-66 per $100 deposited |
| Compound | 150-175% | Borrow $57-66 per $100 deposited |
| MakerDAO | 150-170% | Borrow $58-66 per $100 deposited |
**The issue**: A first-time DeFi user with no history receives the same terms as a veteran with years of successful repayments. This one-size-fits-all approach:
* Penalizes responsible borrowers
* Limits capital efficiency for qualified users
* Provides no incentive to build good credit behavior
* Leaves value on the table for lenders
***
## The Solution: Risk-Adjusted Collateral
By integrating credit scoring, protocols can offer **tiered collateral requirements** that reward creditworthy borrowers while maintaining protocol safety:
### Capital-Efficient Tiers (Over-Collateralized)
| Tier | Min Score | Collateral | vs Standard (150%) | Identity Required |
| - | - | - | - | - |
| Excellent | 920+ | 110% | -40 points | No |
| Very Good | 840+ | 120% | -30 points | No |
| Good | 750+ | 130% | -20 points | No |
| Fair | 640+ | 140% | -10 points | No |
| Building | Below 640 | 150% | Standard | No |
Even at reduced collateral ratios, loans remain **over-collateralized** (above 100%)—the protocol is always protected. The difference is that trusted borrowers aren't unnecessarily penalized.
Ready for even better terms? Users with scores 750+ and verified identity may qualify for [Under-Collateralized Lending](/use-cases/undercollateralized-lending) with collateral below 100%.
***
## Benefits
### For Borrowers
| Credit Tier | Standard Terms | With Credit Scoring | Improvement |
| - | - | - | - |
| Excellent | Borrow $66 per $100 | Borrow $90 per $100 | **+36% capital efficiency** |
| Very Good | Borrow $66 per $100 | Borrow $80 per $100 | **+21% capital efficiency** |
| Good | Borrow $66 per $100 | Borrow $71 per $100 | **+8% capital efficiency** |
### For Lenders & Protocols
* **Increased utilization**: Better terms attract more borrowing activity
* **Competitive advantage**: Differentiate from protocols with fixed ratios
* **User retention**: Borrowers stay where they're rewarded for good behavior
* **Maintained safety**: All loans remain over-collateralized
***
## Implementation
### Basic Collateral Adjustment
```javascript theme={null}
async function getCollateralRequirement(borrowerAddress, asset) {
// Fetch credit score
const response = await fetch(
`https://api.credprotocol.com/api/v2/score/address/${borrowerAddress}`,
{ headers: { 'Authorization': `Bearer ${API_KEY}` } }
);
const { score, range } = await response.json();
// Base collateral ratio for the asset (e.g., 150% for ETH)
const baseRatio = getAssetBaseRatio(asset);
// Credit-based discount
const discount = getCollateralDiscount(score);
// Calculate adjusted ratio (never below safety minimum)
const adjustedRatio = Math.max(
baseRatio - discount,
getMinimumSafeRatio(asset)
);
return {
baseRatio,
adjustedRatio,
discount,
creditScore: score,
creditRange: range,
};
}
function getCollateralDiscount(score) {
// Discount in percentage points based on credit score
if (score >= 920) return 0.40; // 40 percentage points off (150% → 110%)
if (score >= 840) return 0.30; // 30 points off (150% → 120%)
if (score >= 750) return 0.20; // 20 points off (150% → 130%)
if (score >= 640) return 0.10; // 10 points off (150% → 140%)
return 0; // No discount
}
function getMinimumSafeRatio(asset) {
// Minimum collateral ratio regardless of credit score
// Based on asset volatility
const minimums = {
'ETH': 1.10,
'WBTC': 1.10,
'stablecoins': 1.05,
'default': 1.15,
};
return minimums[asset] || minimums.default;
}
```
### Enhanced Risk Assessment
For more sophisticated implementations, incorporate the full credit report:
```javascript theme={null}
async function calculateRiskAdjustedTerms(borrowerAddress, loanRequest) {
// Fetch comprehensive credit data
const [scoreRes, reportRes] = await Promise.all([
fetch(`https://api.credprotocol.com/api/v2/score/address/${borrowerAddress}?include_factors=true`, {
headers: { 'Authorization': `Bearer ${API_KEY}` }
}),
fetch(`https://api.credprotocol.com/api/v2/report/address/${borrowerAddress}`, {
headers: { 'Authorization': `Bearer ${API_KEY}` }
})
]);
const { score, factors } = await scoreRes.json();
const { report } = await reportRes.json();
// Start with base collateral ratio
let collateralRatio = 1.50;
// Apply credit score adjustment
collateralRatio -= getCollateralDiscount(score);
// Additional adjustments based on report data
// Reward strong repayment history
if (report.summary.count_repayments >= 10 && report.summary.count_liquidations === 0) {
collateralRatio -= 0.05;
}
// Reward identity verification
if (report.summary.count_identity_attestations >= 2) {
collateralRatio -= 0.05;
}
// Penalize recent liquidations
if (report.summary.count_liquidations > 0) {
collateralRatio += 0.10;
}
// Adjust for loan size relative to net worth
const loanToNetWorth = loanRequest.amount / report.summary.net_worth_usd;
if (loanToNetWorth > 0.5) {
collateralRatio += 0.10; // Higher ratio for large loans relative to net worth
}
// Ensure minimum safety
collateralRatio = Math.max(collateralRatio, 1.10);
return {
collateralRatio,
requiredCollateral: loanRequest.amount * collateralRatio,
maxBorrow: loanRequest.collateralValue / collateralRatio,
creditScore: score,
factors: {
repaymentBonus: report.summary.count_repayments >= 10,
identityBonus: report.summary.count_identity_attestations >= 2,
liquidationPenalty: report.summary.count_liquidations > 0,
largeLoanPenalty: loanToNetWorth > 0.5,
},
};
}
```
***
## User Experience
### Displaying Terms to Borrowers
```javascript theme={null}
function renderBorrowingTerms(terms, baseTerms) {
const improvement = ((baseTerms.maxBorrow - terms.maxBorrow) / baseTerms.maxBorrow * -100).toFixed(0);
return {
headline: terms.collateralRatio < baseTerms.collateralRatio
? `Your credit score qualifies you for better terms!`
: `Build your credit history to unlock better rates`,
comparison: {
standard: {
label: 'Standard Terms',
collateralRatio: `${(baseTerms.collateralRatio * 100).toFixed(0)}%`,
maxBorrow: formatCurrency(baseTerms.maxBorrow),
},
yours: {
label: 'Your Terms',
collateralRatio: `${(terms.collateralRatio * 100).toFixed(0)}%`,
maxBorrow: formatCurrency(terms.maxBorrow),
highlight: terms.collateralRatio < baseTerms.collateralRatio,
},
},
improvement: terms.collateralRatio < baseTerms.collateralRatio
? `+${Math.abs(improvement)}% more borrowing power`
: null,
factors: terms.factors,
};
}
```
### Incentivizing Credit Building
Show users how improving their score translates to better terms:
```javascript theme={null}
function showImprovementPath(currentScore, currentRatio) {
const tiers = [
{ minScore: 920, ratio: 1.10, label: 'Excellent' },
{ minScore: 840, ratio: 1.20, label: 'Very Good' },
{ minScore: 750, ratio: 1.30, label: 'Good' },
{ minScore: 640, ratio: 1.40, label: 'Fair' },
];
const currentTier = tiers.find(t => currentScore >= t.minScore) || { label: 'Building' };
const nextTier = tiers.find(t => t.minScore > currentScore);
return {
current: {
tier: currentTier.label,
ratio: currentRatio,
score: currentScore,
},
next: nextTier ? {
tier: nextTier.label,
ratio: nextTier.ratio,
scoreNeeded: nextTier.minScore,
pointsAway: nextTier.minScore - currentScore,
benefitDescription: `Unlock ${((currentRatio - nextTier.ratio) * 100).toFixed(0)}% lower collateral requirements`,
} : null,
tips: [
'Make consistent loan repayments',
'Maintain healthy collateral ratios',
'Add identity attestations (ENS, Gitcoin Passport)',
'Avoid liquidations',
],
};
}
```
***
## Safety Considerations
Capital-efficient lending must balance improved terms with protocol safety:
Never reduce collateral below asset-specific minimums. Even the most creditworthy borrowers should maintain at least 105-110% collateral to account for rapid price movements.
Apply different minimum ratios based on asset volatility. Stablecoins can have lower floors than volatile assets like ETH or WBTC.
Reduced collateral means less buffer before liquidation. Implement robust monitoring and alert systems.
Credit scores are cached for 5 minutes. For collateral calculations, this is usually sufficient, but consider the trade-off between freshness and API costs.
If the credit API is unavailable, fall back to standard collateral requirements rather than denying service.
### Fallback Strategy
```javascript theme={null}
async function getCollateralRequirementWithFallback(borrowerAddress, asset) {
try {
const terms = await getCollateralRequirement(borrowerAddress, asset);
return terms;
} catch (error) {
console.error('Credit score unavailable, using standard terms:', error);
// Fall back to standard collateral requirements
return {
baseRatio: getAssetBaseRatio(asset),
adjustedRatio: getAssetBaseRatio(asset),
discount: 0,
creditScore: null,
creditRange: null,
fallback: true,
};
}
}
```
***
## The Path Forward
Capital-efficient lending is a **stepping stone** toward full under-collateralized lending:
150%+ collateral for everyone, regardless of creditworthiness
110-150% collateral based on credit score—**you are here**
50-100% collateral for highly qualified borrowers with verified identity
Unsecured loans based on on-chain reputation and credit history
By implementing capital-efficient lending today, protocols can:
* Build infrastructure for credit-based risk assessment
* Establish user credit histories
* Create incentives for good financial behavior
* Prepare for the transition to under-collateralized products
***
## Related
The next step: lending with less than 100% collateral
Gate access to lending products by credit tier
API reference for fetching credit scores
Detailed borrower financial profiles
# Engaging and Educating Users
Source: https://docs.credprotocol.com/use-cases/engaging-users
Help users understand and improve their on-chain financial behavior
Engaging and educating users is an important aspect of expanding access to DeFi products. By measuring and communicating on-chain financial behavior, protocols, wallets, and partners can help their users to better understand the products and services they're using and how they can benefit from them—leading to increased customer satisfaction and engagement, which can ultimately result in increased revenue.
## Why Engage and Educate?
Engaged users stay longer and interact more with your product
Education builds confidence and trust in your platform
Guidance leads to better financial decisions and outcomes
Stand out by providing value beyond basic functionality
***
## The Power of Credit Scores
As soon as people have a credit score, they often want to know how they can improve it. Users recognize that creditworthiness enables them to access financial products on beneficial terms, and they are looking for guidance on healthy behavior that can help them improve their credit scores.
This creates a natural engagement opportunity: provide users with their score, explain what it means, and guide them on how to improve it.
***
## Implementation Example
### Credit Score Dashboard
```javascript theme={null}
async function renderCreditDashboard(address) {
const response = await fetch(
`https://api.credprotocol.com/api/v2/score/address/${address}?include_factors=true`,
{ headers: { 'Authorization': `Bearer ${API_KEY}` } }
);
const { score, range, decile, factors } = await response.json();
return {
// Core score display
score: {
value: score,
range: formatRange(range),
percentile: `Top ${(10 - decile + 1) * 10}%`,
},
// Factor breakdown for education
factors: factors.map(factor => ({
name: factor.label,
rating: factor.rating,
description: factor.description,
tips: getImprovementTips(factor.label, factor.rating),
})),
// Personalized recommendations
recommendations: getRecommendations(factors),
// Educational content
education: getEducationalContent(range, factors),
};
}
function formatRange(range) {
const labels = {
excellent: 'Excellent',
very_good: 'Very Good',
good: 'Good',
fair: 'Fair',
low: 'Needs Improvement',
};
return labels[range] || range;
}
```
### Improvement Tips by Factor
```javascript theme={null}
function getImprovementTips(factorLabel, rating) {
const tips = {
'Borrowing History': {
low: [
'Start with a small loan on a reputable lending protocol',
'Make consistent, on-time repayments',
'Avoid liquidations by monitoring your positions',
],
medium: [
'Continue your strong repayment history',
'Consider diversifying across lending protocols',
'Maintain positions well above liquidation thresholds',
],
high: [
'Your borrowing history is excellent—keep it up!',
'Consider helping others learn responsible borrowing',
],
},
'Wallet Composition': {
low: [
'Diversify your holdings across different asset types',
'Consider adding stablecoins to reduce volatility',
'Avoid concentration in single tokens',
],
medium: [
'Good diversification—consider adding more stable assets',
'Review your portfolio balance periodically',
],
high: [
'Excellent portfolio composition',
'Your diversification strategy is working well',
],
},
'Wallet Health': {
low: [
'Increase your collateral ratios on open positions',
'Reduce leverage to safer levels',
'Monitor positions more frequently',
],
medium: [
'Consider adding buffer to your collateral',
'Set up alerts for position health',
],
high: [
'Your positions are well-managed',
'Great job maintaining healthy collateral ratios',
],
},
'Trust': {
low: [
'Register an ENS name to establish identity',
'Complete Gitcoin Passport verification',
'Participate in community events to earn POAPs',
],
medium: [
'Add more identity attestations',
'Participate in governance to build reputation',
],
high: [
'Strong identity verification',
'Your on-chain reputation is well-established',
],
},
'Interactions': {
low: [
'Explore reputable DeFi protocols',
'Engage with established smart contracts',
'Build transaction history over time',
],
medium: [
'Continue engaging with the ecosystem',
'Try new protocols to broaden your activity',
],
high: [
'Excellent ecosystem engagement',
'Your activity demonstrates strong participation',
],
},
'New Credit': {
low: [
'Avoid opening too many new positions at once',
'Space out new borrowing activity',
'Let recent positions mature before taking new ones',
],
medium: [
'Your recent credit activity is balanced',
'Continue measured approach to new borrowing',
],
high: [
'Well-managed new credit activity',
'Your approach to new positions is prudent',
],
},
};
const factorTips = tips[factorLabel] || {};
if (rating === 'Excellent' || rating === 'Very Good') return factorTips.high || [];
if (rating === 'Good' || rating === 'Fair') return factorTips.medium || [];
return factorTips.low || [];
}
```
***
## Educational Content
### Score Explainer Component
```javascript theme={null}
function getScoreExplainer(score) {
if (score >= 920) {
return {
title: 'Excellent Credit',
description: 'Your on-chain activity demonstrates exceptional financial responsibility. You have access to the best terms and products.',
icon: 'trophy',
color: 'green',
};
}
if (score >= 840) {
return {
title: 'Very Good Credit',
description: 'You have a strong credit profile with consistent positive behavior. Most products and favorable terms are available to you.',
icon: 'star',
color: 'blue',
};
}
if (score >= 750) {
return {
title: 'Good Credit',
description: 'Your credit profile is solid. You qualify for most standard products. Focus on the tips below to reach the next level.',
icon: 'check-circle',
color: 'teal',
};
}
if (score >= 640) {
return {
title: 'Fair Credit',
description: 'You\'re building your credit history. Follow the recommendations below to improve your score and unlock more opportunities.',
icon: 'trending-up',
color: 'yellow',
};
}
return {
title: 'Building Credit',
description: 'Everyone starts somewhere. Follow our guidance to build a strong on-chain credit history and unlock DeFi opportunities.',
icon: 'seedling',
color: 'orange',
};
}
```
### Educational Resources by Level
```javascript theme={null}
function getEducationalContent(range, factors) {
const content = {
excellent: {
articles: [
{ title: 'Advanced Yield Strategies', url: '/learn/advanced-yield' },
{ title: 'Managing Large Positions', url: '/learn/large-positions' },
{ title: 'Cross-Chain Opportunities', url: '/learn/cross-chain' },
],
tips: [
'Consider sharing your knowledge with newer users',
'Explore governance participation',
'Look into advanced DeFi strategies',
],
},
very_good: {
articles: [
{ title: 'Optimizing Your Portfolio', url: '/learn/portfolio-optimization' },
{ title: 'Understanding Liquidation Risk', url: '/learn/liquidation-risk' },
{ title: 'Earning with LP Positions', url: '/learn/liquidity-provision' },
],
tips: [
'Focus on maintaining your strong history',
'Consider diversifying protocol exposure',
'Monitor positions to avoid liquidations',
],
},
good: {
articles: [
{ title: 'How Credit Scores Work', url: '/learn/credit-scores' },
{ title: 'Safe Borrowing Practices', url: '/learn/safe-borrowing' },
{ title: 'Building Trust On-Chain', url: '/learn/on-chain-trust' },
],
tips: getWeakestFactorTips(factors),
},
fair: {
articles: [
{ title: 'Getting Started with DeFi Lending', url: '/learn/defi-lending' },
{ title: 'Understanding Collateral', url: '/learn/collateral-basics' },
{ title: 'Your First Loan', url: '/learn/first-loan' },
],
tips: getWeakestFactorTips(factors),
},
low: {
articles: [
{ title: 'DeFi 101: The Basics', url: '/learn/defi-basics' },
{ title: 'Wallet Security Best Practices', url: '/learn/wallet-security' },
{ title: 'How to Build Credit On-Chain', url: '/learn/build-credit' },
],
tips: [
'Start with small, manageable positions',
'Focus on learning before taking risks',
'Build transaction history gradually',
],
},
};
return content[range] || content.low;
}
function getWeakestFactorTips(factors) {
// Find the weakest factor and return targeted tips
const weakest = factors.reduce((min, factor) =>
getRatingScore(factor.rating) < getRatingScore(min.rating) ? factor : min
);
return getImprovementTips(weakest.label, weakest.rating);
}
function getRatingScore(rating) {
const scores = { 'Excellent': 5, 'Very Good': 4, 'Good': 3, 'Fair': 2, 'Low': 1 };
return scores[rating] || 0;
}
```
***
## Engagement Features
### Progress Tracking
```javascript theme={null}
async function trackScoreProgress(address) {
// Store historical scores (you'd implement your own storage)
const history = await getScoreHistory(address);
const currentScore = await getCurrentScore(address);
const thirtyDaysAgo = history.find(h =>
h.date >= Date.now() - 30 * 24 * 60 * 60 * 1000
);
return {
current: currentScore,
change30d: thirtyDaysAgo ? currentScore - thirtyDaysAgo.score : null,
trend: calculateTrend(history),
milestones: getMilestones(currentScore, history),
};
}
function getMilestones(currentScore, history) {
const milestones = [];
const thresholds = [640, 750, 840, 920];
for (const threshold of thresholds) {
if (currentScore >= threshold) {
const achievedDate = history.find(h => h.score >= threshold)?.date;
milestones.push({
threshold,
label: getThresholdLabel(threshold),
achieved: true,
date: achievedDate,
});
} else {
milestones.push({
threshold,
label: getThresholdLabel(threshold),
achieved: false,
pointsNeeded: threshold - currentScore,
});
}
}
return milestones;
}
```
### Gamification Elements
```javascript theme={null}
function getAchievements(score, report) {
const achievements = [];
// Score-based achievements
if (score >= 920) achievements.push({ id: 'excellent', name: 'Credit Elite', icon: '🏆' });
if (score >= 840) achievements.push({ id: 'very_good', name: 'Rising Star', icon: '⭐' });
if (score >= 750) achievements.push({ id: 'good', name: 'On Track', icon: '✅' });
// Activity-based achievements
if (report.summary.count_repayments >= 10) {
achievements.push({ id: 'repayer', name: 'Consistent Repayer', icon: '💪' });
}
if (report.summary.count_chains_with_activity >= 3) {
achievements.push({ id: 'multichain', name: 'Chain Explorer', icon: '🌐' });
}
if (report.summary.count_identity_attestations >= 2) {
achievements.push({ id: 'verified', name: 'Verified Identity', icon: '🔐' });
}
if (report.summary.count_liquidations === 0 && report.summary.count_active_loans > 0) {
achievements.push({ id: 'safe', name: 'Safe Borrower', icon: '🛡️' });
}
return achievements;
}
```
***
## Safety and Risk Education
As the web3 and DeFi space is relatively new, guidance on how to engage with these products safely is important:
* Never invest more than you can afford to lose
* Understand liquidation thresholds before borrowing
* Use stop-losses and position alerts
* Diversify across protocols and chains
* Check if protocols have been audited
* Review TVL (Total Value Locked) as a trust signal
* Look for established track records
* Research the team and governance structure
* Use hardware wallets for significant holdings
* Never share your seed phrase
* Verify contract addresses before interacting
* Be wary of too-good-to-be-true yields
***
## Best Practices
Don't just show a score—provide specific, actionable steps users can take to improve.
Acknowledge improvements and milestones to keep users engaged and motivated.
If a user's score is low, be supportive rather than discouraging. Everyone can improve.
As DeFi evolves, keep educational content current with new protocols and best practices.
***
## Related
Learn about credit factors and scoring methodology
Tailor product experiences based on creditworthiness
# Personalization
Source: https://docs.credprotocol.com/use-cases/personalizing-experiences
Tailor DeFi experiences based on creditworthiness and financial profile
Personalizing product experiences is a way to tailor the user experience to the account owner's specific needs and preferences. By doing so, the product or service can be made more relevant and useful to the user. This can be achieved by using data and analytics to understand the account's asset level and creditworthiness, and then using that information to customize the user experience.
## Why Personalize?
Show users products and features that match their financial profile
Increase interaction by surfacing the most appropriate options first
Improve conversion rates by presenting suitable products to qualified users
Reduce friction by hiding irrelevant or inaccessible options
***
## Aligning with Creditworthiness
One way to personalize product experiences is to align the user experience with a user's asset level and creditworthiness.
### High Creditworthiness Users
If a user has a high asset level and creditworthiness, they may be offered more complex and advanced financial products such as high risk/reward yield strategies:
* Leveraged yield farming
* Delta-neutral strategies
* Under-collateralized lending options
* Premium liquidity pools
* Advanced trading features
### Lower Creditworthiness Users
If a user has a lower asset level and creditworthiness, they may be offered lower risk financial products:
* Liquid staking derivatives
* Stable yield pools
* Over-collateralized lending
* Beginner-friendly interfaces
* Educational content and guides
***
## Implementation Example
```javascript theme={null}
async function getPersonalizedDashboard(address) {
const response = await fetch(
`https://api.credprotocol.com/api/v2/score/address/${address}?include_factors=true`,
{ headers: { 'Authorization': `Bearer ${API_KEY}` } }
);
const { score, range, factors } = await response.json();
// Determine user tier based on creditworthiness
const userTier = getUserTier(score);
// Get personalized product recommendations
const recommendations = getRecommendations(userTier, factors);
// Customize UI elements
const dashboardConfig = {
tier: userTier,
featuredProducts: recommendations.featured,
availableStrategies: recommendations.strategies,
promotedFeatures: recommendations.features,
riskLevel: recommendations.maxRisk,
showAdvancedOptions: score >= 840,
showLeveragedProducts: score >= 920,
};
return dashboardConfig;
}
function getUserTier(score) {
if (score >= 920) return 'premium';
if (score >= 840) return 'advanced';
if (score >= 750) return 'standard';
if (score >= 640) return 'basic';
return 'starter';
}
function getRecommendations(tier, factors) {
const recommendations = {
premium: {
featured: ['leveraged-farming', 'delta-neutral', 'undercollateralized-loans'],
strategies: ['aggressive', 'balanced', 'conservative'],
features: ['advanced-analytics', 'api-access', 'priority-support'],
maxRisk: 'high',
},
advanced: {
featured: ['yield-optimizer', 'lending-pools', 'staking'],
strategies: ['balanced', 'conservative'],
features: ['portfolio-tracking', 'alerts'],
maxRisk: 'medium-high',
},
standard: {
featured: ['staking', 'stable-pools', 'lending'],
strategies: ['balanced', 'conservative'],
features: ['basic-analytics'],
maxRisk: 'medium',
},
basic: {
featured: ['liquid-staking', 'stable-yields'],
strategies: ['conservative'],
features: ['tutorials', 'guides'],
maxRisk: 'low',
},
starter: {
featured: ['learn-and-earn', 'stable-savings'],
strategies: ['conservative'],
features: ['onboarding', 'education'],
maxRisk: 'minimal',
},
};
return recommendations[tier];
}
```
***
## Personalization Patterns
### Dynamic Feature Promotion
Promote capabilities that are popular with account owners with similar levels of creditworthiness:
```javascript theme={null}
async function getPopularFeatures(userScore) {
// Define score bands
const scoreBand = Math.floor(userScore / 100) * 100;
// Features popular with users in similar score ranges
const popularByBand = {
900: ['leveraged-positions', 'cross-chain-strategies', 'governance'],
800: ['yield-optimization', 'liquidity-provision', 'staking'],
700: ['lending', 'borrowing', 'stable-yields'],
600: ['savings', 'staking', 'swaps'],
default: ['tutorials', 'stable-savings', 'small-swaps'],
};
return popularByBand[scoreBand] || popularByBand.default;
}
```
### Adaptive UI Components
Adjust the interface based on user profile:
```javascript theme={null}
function renderProductCard(product, userScore) {
const isAccessible = userScore >= product.minScore;
const isRecommended = userScore >= product.recommendedScore;
return {
...product,
// Visual treatment
highlighted: isRecommended,
dimmed: !isAccessible,
// Call-to-action
ctaText: isAccessible ? 'Get Started' : `Requires ${product.minScore}+ score`,
ctaEnabled: isAccessible,
// Additional context
badge: isRecommended ? 'Recommended for you' : null,
tooltip: !isAccessible
? `Improve your score to ${product.minScore} to unlock this product`
: null,
};
}
```
### Personalized Messaging
Tailor communication based on creditworthiness:
```javascript theme={null}
function getWelcomeMessage(range) {
const messages = {
excellent: {
headline: 'Welcome back, valued member',
subtitle: 'Explore our premium strategies designed for experienced DeFi users',
cta: 'View Premium Options',
},
very_good: {
headline: 'Great to see you',
subtitle: 'Your strong credit profile unlocks advanced features',
cta: 'Explore Advanced Features',
},
good: {
headline: 'Welcome',
subtitle: 'Discover yield opportunities matched to your profile',
cta: 'Browse Opportunities',
},
fair: {
headline: 'Welcome',
subtitle: 'Start building your DeFi portfolio with these curated options',
cta: 'Get Started',
},
low: {
headline: 'Welcome to DeFi',
subtitle: 'Begin your journey with beginner-friendly products',
cta: 'Start Learning',
},
};
return messages[range] || messages.low;
}
```
***
## Using Credit Reports for Deeper Personalization
For more granular personalization, use the full credit report:
```javascript theme={null}
async function getDetailedPersonalization(address) {
const response = await fetch(
`https://api.credprotocol.com/api/v2/report/address/${address}`,
{ headers: { 'Authorization': `Bearer ${API_KEY}` } }
);
const { report } = await response.json();
const { summary } = report;
return {
// Asset-based personalization
assetTier: getAssetTier(summary.total_asset_usd),
// Activity-based personalization
experienceLevel: getExperienceLevel(summary.count_transactions),
// DeFi experience
hasLendingHistory: summary.count_active_loans > 0 || summary.count_repayments > 0,
hasNFTs: summary.count_nfts > 0,
// Multi-chain activity
isMultiChain: summary.count_chains_with_activity > 1,
// Identity verification
hasVerifiedIdentity: summary.count_identity_attestations > 0,
attestations: summary.list_identity_attestations,
};
}
function getAssetTier(totalAssetUsd) {
if (totalAssetUsd >= 100000) return 'whale';
if (totalAssetUsd >= 10000) return 'dolphin';
if (totalAssetUsd >= 1000) return 'fish';
return 'shrimp';
}
function getExperienceLevel(transactionCount) {
if (transactionCount >= 1000) return 'veteran';
if (transactionCount >= 100) return 'experienced';
if (transactionCount >= 10) return 'intermediate';
return 'beginner';
}
```
***
## Best Practices
Rather than hiding products entirely from lower-score users, show them what's available and what they need to do to qualify. This creates aspiration and engagement.
Let users know their experience is personalized based on their on-chain activity. Transparency builds trust.
Even if you recommend certain products, allow users to browse all options. Some users may have legitimate reasons to choose different products.
Re-fetch credit data periodically to ensure personalization reflects the user's current status, not stale information.
***
## Benefits
| Benefit | Description |
| - | - |
| Increased Engagement | Users see relevant products, leading to more interaction |
| Higher Conversion | Presenting appropriate products improves conversion rates |
| Reduced Friction | Users aren't overwhelmed with unsuitable options |
| Better Risk Management | Users are guided toward products matching their profile |
| Customer Satisfaction | Tailored experiences feel more valuable to users |
***
## Related
API reference for detailed credit reports
Gate access to products based on creditworthiness
# Qualifying Access to Products
Source: https://docs.credprotocol.com/use-cases/qualifying-access
Use credit scores to gate access to DeFi products and services
Qualifying access to products is a way to ensure that eligible individuals and entities are able to access appropriate products or services. This can be done for a variety of reasons, such as to protect the interests of the provider, to ensure that the product is being used by the intended audience, or to mitigate risk.
## Why Qualify Access?
Reduce exposure to defaults and bad actors by limiting access to creditworthy participants
Offer improved rates or conditions to users who demonstrate financial responsibility
Safeguard liquidity providers by ensuring borrowers meet minimum creditworthiness standards
Meet compliance requirements by implementing risk-based access controls
***
## Example: Lending Pool Access
A lending pool may only be accessed by accounts with an "Excellent" credit score. This is because the provider of the lending pool may want to minimize the risk of default on loans, and therefore only wants to provide loans to individuals or entities that have a proven track record of responsibly managing credit.
```javascript theme={null}
const { score, range } = await getCredScore(userAddress);
if (range === 'excellent') {
// Grant access to premium lending pool
await grantPoolAccess(userAddress, 'premium-pool');
} else if (range === 'very_good' || range === 'good') {
// Grant access to standard pool with higher collateral requirements
await grantPoolAccess(userAddress, 'standard-pool');
} else {
// Require additional collateral or deny access
showMessage('Credit score too low for this pool');
}
```
***
## Example: Yield Aggregation Tiers
A yield aggregation protocol may only offer specific pools to accounts with credit scores over 800. This is because the provider may want to ensure that only the most financially stable individuals or entities are able to access higher-risk, higher-reward pools.
```javascript theme={null}
const { score } = await getCredScore(userAddress);
const availablePools = [];
// Base pools available to everyone
availablePools.push('stable-yield-pool');
if (score >= 750) {
// Medium-risk pools for good credit
availablePools.push('balanced-yield-pool');
}
if (score >= 840) {
// Higher-yield pools for very good credit
availablePools.push('growth-yield-pool');
}
if (score >= 920) {
// Premium pools for excellent credit
availablePools.push('premium-yield-pool');
availablePools.push('leveraged-strategies-pool');
}
return availablePools;
```
***
## Implementation Patterns
### Gate by Score Range
Use the `range` field for simple tier-based access:
```javascript theme={null}
async function checkAccess(address) {
const response = await fetch(
`https://api.credprotocol.com/api/v2/score/address/${address}`,
{ headers: { 'Authorization': `Bearer ${API_KEY}` } }
);
const { range } = await response.json();
switch (range) {
case 'excellent':
return { tier: 'premium', collateralRatio: 1.1 };
case 'very_good':
return { tier: 'standard', collateralRatio: 1.25 };
case 'good':
return { tier: 'basic', collateralRatio: 1.5 };
default:
return { tier: 'restricted', collateralRatio: 2.0 };
}
}
```
### Gate by Minimum Score
Use the numeric `score` for precise thresholds:
```javascript theme={null}
const MIN_SCORE_FOR_ACCESS = 750;
async function canAccessProduct(address) {
const response = await fetch(
`https://api.credprotocol.com/api/v2/score/address/${address}`,
{ headers: { 'Authorization': `Bearer ${API_KEY}` } }
);
const { score } = await response.json();
return score >= MIN_SCORE_FOR_ACCESS;
}
```
### On-Chain Integration
For smart contract integration, you can verify scores off-chain and pass the result on-chain, or use an oracle pattern:
```solidity theme={null}
// Simplified example - verify score off-chain, gate on-chain
contract CreditGatedPool {
mapping(address => bool) public approvedBorrowers;
function approveBorrower(address borrower) external onlyOracle {
approvedBorrowers[borrower] = true;
}
function borrow(uint256 amount) external {
require(approvedBorrowers[msg.sender], "Not approved");
// ... borrowing logic
}
}
```
***
## Best Practices
Credit scores are cached for 5 minutes. For access control decisions, consider caching the approval status rather than re-checking on every interaction.
When denying access, tell users why and what score they need. This transparency helps users understand the requirements and potentially improve their creditworthiness.
Rather than binary access control, consider tiered access where lower scores get higher collateral requirements or lower limits, rather than complete denial.
Test your access control logic using sandbox endpoints before deploying to production. Sandbox returns deterministic scores based on address, making testing predictable.
***
## Related
API reference for fetching credit scores
Understanding score classifications
# Under-Collateralized Lending
Source: https://docs.credprotocol.com/use-cases/undercollateralized-lending
Unlock true leverage for creditworthy borrowers with less than 100% collateral
In traditional finance, consumer lending is a **\$4.5 trillion market** that's enabled by credit reporting bureaus and credit scoring agencies. In DeFi, accounts are assumed to be "unscorable," requiring lenders to over-collateralize loans—limiting access and utility.
Cred Protocol quantifies on-chain lending risk at scale by building one of the first decentralized credit scores. We're on a mission to expand access to DeFi lending to regular people and underserved communities, helping them access financial resources that make a meaningful difference to their lives.
**New to credit-based lending?** Start with [Capital-Efficient Lending](/use-cases/capital-efficient-lending), which covers reducing collateral requirements while remaining over-collateralized (100%+). This page covers the next step: lending with **less than 100% collateral**.
***
## What is Under-Collateralized Lending?
Under-collateralized lending allows borrowers to access more capital than they deposit as collateral. This is how most traditional consumer lending works—and it's the next frontier for DeFi.
**Collateral > Loan**
Deposit $150 to borrow $100. Safe but capital inefficient.
**Collateral \< Loan**
Deposit $50 to borrow $100. Requires trust—enabled by credit scoring.
| Approach | Collateral Ratio | Example | Risk Level |
| - | - | - | - |
| Over-collateralized | 110-150% | $150 collateral → $100 loan | Low (trustless) |
| Fully collateralized | 100% | $100 collateral → $100 loan | Low |
| Under-collateralized | 50-99% | $50 collateral → $100 loan | Medium (requires credit assessment) |
| Unsecured | 0% | $0 collateral → $100 loan | High (requires strong identity + credit) |
***
## The Market Opportunity
**Happening today** through protocols such as Maple Finance and TrueFi. However, loans are approved by governance token-holders, so risk underwriting is fundamentally "human powered" and limited in scale.
Consumer lending in traditional finance is a \*\*$4.5T market**—almost three times larger than the $1.5T institutional lending market. However, DeFi-powered under-collateralized consumer loans aren't happening yet.
To enable consumer lending, we need to **quantify risk at scale**, which requires an algorithmic approach: a credit score. That's what we're building at Cred Protocol.
***
## How Cred Protocol Enables Under-Collateralized Lending
### Risk Quantification at Scale
```javascript theme={null}
async function assessLoanRisk(borrowerAddress, requestedAmount) {
// Get comprehensive credit data
const [scoreResponse, reportResponse] = await Promise.all([
fetch(`https://api.credprotocol.com/api/v2/score/address/${borrowerAddress}?include_factors=true`, {
headers: { 'Authorization': `Bearer ${API_KEY}` }
}),
fetch(`https://api.credprotocol.com/api/v2/report/address/${borrowerAddress}`, {
headers: { 'Authorization': `Bearer ${API_KEY}` }
})
]);
const { score, range, factors } = await scoreResponse.json();
const { report } = await reportResponse.json();
// Assess borrower profile
const riskAssessment = {
creditScore: score,
creditRange: range,
// Historical behavior
hasLiquidations: report.summary.count_liquidations > 0,
hasDefaults: report.summary.count_defaults > 0,
repaymentCount: report.summary.count_repayments,
// Financial position
netWorth: report.summary.net_worth_usd,
totalAssets: report.summary.total_asset_usd,
currentDebt: report.summary.total_debt_usd,
// Identity verification
identityAttestations: report.summary.list_identity_attestations,
isVerified: report.summary.count_identity_attestations > 0,
// Calculate risk metrics
debtToAssetRatio: report.summary.total_debt_usd / report.summary.total_asset_usd,
requestedToNetWorth: requestedAmount / report.summary.net_worth_usd,
};
return riskAssessment;
}
```
### Dynamic Collateral Requirements
Under-collateralized lending requires collateral ratios **below 100%**. Only the most creditworthy borrowers with verified identity qualify:
```javascript theme={null}
function calculateCollateralRequirement(score, loanAmount, riskAssessment) {
// Base collateral ratios by credit tier (under-collateralized product)
// Note: Only excellent/very_good tiers qualify for under-collateralized loans
const baseRatios = {
excellent: 0.50, // 50% collateral (2x leverage)
very_good: 0.75, // 75% collateral (1.33x leverage)
good: 0.90, // 90% collateral (1.1x leverage) - barely under-collateralized
fair: null, // Not eligible for under-collateralized
low: null, // Not eligible for under-collateralized
};
// Check eligibility
if (!baseRatios[riskAssessment.creditRange]) {
return {
eligible: false,
reason: 'Credit score too low for under-collateralized lending',
suggestion: 'See Capital-Efficient Lending for over-collateralized options with reduced requirements',
alternativeProduct: 'capital-efficient',
};
}
// Identity verification required for under-collateralized loans
if (!riskAssessment.isVerified) {
return {
eligible: false,
reason: 'Identity verification required for under-collateralized loans',
suggestion: 'Add ENS, Gitcoin Passport, or other identity attestations',
};
}
let collateralRatio = baseRatios[riskAssessment.creditRange];
// Adjust for risk factors
if (riskAssessment.hasLiquidations) collateralRatio += 0.15;
if (riskAssessment.hasDefaults) return { eligible: false, reason: 'Previous defaults disqualify from under-collateralized lending' };
// Adjust for loan size relative to net worth
if (riskAssessment.requestedToNetWorth > 0.5) collateralRatio += 0.10;
// Reward strong repayment history
if (riskAssessment.repaymentCount >= 10) collateralRatio -= 0.05;
// Ensure minimum collateral (never below 30%)
collateralRatio = Math.max(0.30, collateralRatio);
return {
eligible: true,
ratio: collateralRatio,
requiredCollateral: loanAmount * collateralRatio,
leverage: 1 / collateralRatio,
};
}
```
***
## Loan Eligibility Framework
### Under-Collateralized Tiers
Under-collateralized lending is a premium product requiring excellent credit **and** verified identity:
| Tier | Min Score | Collateral | Max Leverage | Identity Required |
| - | - | - | - | - |
| Excellent | 920+ | 50% | 2.0x | Yes |
| Very Good | 840+ | 75% | 1.33x | Yes |
| Good | 750+ | 90% | 1.1x | Yes |
Users with scores below 750, previous defaults, or no identity verification should use [Capital-Efficient Lending](/use-cases/capital-efficient-lending) instead, which offers reduced collateral requirements while remaining over-collateralized.
### Tiered Access Model
```javascript theme={null}
function determineLoanEligibility(riskAssessment) {
const { creditScore, netWorth, isVerified, hasDefaults } = riskAssessment;
// Disqualifying factors for under-collateralized lending
if (hasDefaults) {
return {
eligible: false,
reason: 'Previous defaults disqualify from under-collateralized lending',
suggestion: 'Build positive repayment history, then try Capital-Efficient Lending first',
alternativeProduct: 'capital-efficient',
};
}
if (!isVerified) {
return {
eligible: false,
reason: 'Identity verification required for under-collateralized loans',
suggestion: 'Add ENS, Gitcoin Passport, or other identity attestations',
};
}
// Under-collateralized tier definitions (all require identity verification)
const tiers = [
{
name: 'Excellent',
minScore: 920,
maxLoanToNetWorth: 2.0, // Can borrow 2x net worth
collateralRatio: 0.50, // 50% collateral
leverage: 2.0,
features: ['Lowest collateral', 'Highest limits', 'Best rates'],
},
{
name: 'Very Good',
minScore: 840,
maxLoanToNetWorth: 1.5,
collateralRatio: 0.75, // 75% collateral
leverage: 1.33,
features: ['Low collateral', 'High limits', 'Competitive rates'],
},
{
name: 'Good',
minScore: 750,
maxLoanToNetWorth: 1.2,
collateralRatio: 0.90, // 90% collateral
leverage: 1.1,
features: ['Reduced collateral', 'Standard limits'],
},
];
// Find eligible tier
for (const tier of tiers) {
if (creditScore >= tier.minScore) {
return {
eligible: true,
product: 'under-collateralized',
tier: tier.name,
maxLoan: netWorth * tier.maxLoanToNetWorth,
collateralRatio: tier.collateralRatio,
leverage: tier.leverage,
features: tier.features,
};
}
}
// Not eligible for under-collateralized, suggest alternative
return {
eligible: false,
reason: 'Credit score below 750 required for under-collateralized lending',
suggestion: 'Try Capital-Efficient Lending for better terms than standard DeFi',
alternativeProduct: 'capital-efficient',
currentScore: creditScore,
requiredScore: 750,
};
}
```
***
## Risk Mitigation Strategies
### For Lenders
Spread risk across many borrowers with varying credit profiles. A well-diversified pool can absorb individual defaults while remaining profitable.
Start borrowers with small limits and increase over time based on repayment behavior. This limits exposure while building track record.
Require identity attestations (ENS, Gitcoin Passport) for under-collateralized loans. This adds accountability and reduces sybil attacks.
Monitor borrower positions and credit scores continuously. Early warning systems can trigger margin calls or reduced limits before defaults occur.
### Implementation Example
```javascript theme={null}
async function monitorLoanHealth(loanId) {
const loan = await getLoan(loanId);
const currentScore = await getCredScore(loan.borrower);
const currentReport = await getCredReport(loan.borrower);
const healthMetrics = {
// Score degradation
scoreChange: currentScore.score - loan.originalScore,
scoreDegraded: currentScore.score < loan.originalScore - 50,
// Position health
currentCollateralRatio: loan.collateralValue / loan.outstandingAmount,
belowMinimum: loan.collateralValue / loan.outstandingAmount < loan.requiredRatio,
// Borrower financial health
netWorthChange: currentReport.summary.net_worth_usd - loan.originalNetWorth,
debtIncreased: currentReport.summary.total_debt_usd > loan.originalDebt * 1.5,
};
// Trigger alerts or actions
if (healthMetrics.scoreDegraded || healthMetrics.belowMinimum) {
await triggerMarginCall(loanId, healthMetrics);
}
return healthMetrics;
}
```
***
## The Vision: Democratizing Credit
Under-collateralized lending isn't just about capital efficiency—it's about **financial inclusion**. Billions of people worldwide lack access to credit because they don't have traditional credit history. On-chain activity can provide an alternative path to creditworthiness.
### Who Benefits
| User Type | Current Situation | With Under-Collateralized Lending |
| - | - | - |
| DeFi power users | Lock up 150%+ collateral | Access 2x+ leverage with proven track record |
| Emerging market users | No access to credit | Build creditworthiness through on-chain activity |
| Small businesses | Limited capital efficiency | Grow faster with working capital loans |
| DAO contributors | Reputation but no credit | Leverage on-chain reputation for loans |
***
## Getting Started
Start here: reduced collateral while staying over-collateralized
Assess borrower creditworthiness
Deep dive into borrower financial profile
Discuss integration for your lending protocol