The cryptocurrency landscape is rife with opportunity, but also with significant risk. Rug pulls and poorly designed tokens can lead to substantial losses. Rugcheck.xyz provides a critical service by analyzing crypto projects for potential red flags. Its API allows developers, traders, and analysts to programmatically access these insights, automating and scaling their due diligence efforts. This guide will focus heavily on how to use the Rugcheck.xyz API, equipping you with practical Python examples.
Want an integrated, All-in-One platform for your Developer Team to work together with maximum productivity?
Apidog delivers all your demans, and replaces Postman at a much more affordable price!
A Brief Overview of Rugcheck.xyz and its API
What is Rugcheck.xyz?
Rugcheck.xyz is a platform designed to scrutinize cryptocurrency tokens and smart contracts for signs of malicious intent (like rug pulls or honeypots) or inherent risks. It examines contract code, liquidity, tokenomics, developer wallets, and more, providing risk assessments and detailed reports.
Why the API?
The API grants programmatic access to Rugcheck.xyz's analytical engine, enabling:
- Automation: Integrate checks into trading bots or new token alert systems.
- Scalability: Analyze numerous tokens far faster than manual checks.
- Customization: Build bespoke dashboards and risk models using raw API data.
Getting Your Rugcheck.xyz API Key – The Essentials
To use the API, you need an API key. The Rugcheck.xyz API documentation (https://api.rugcheck.xyz/swagger/index.html
) implies a user account system for key management through endpoints like /user/api-keys
.
- Register/Login: Visit the main Rugcheck.xyz website and create an account or sign in.
- Find API Settings: Look for an "API," "Developer," or "API Keys" section in your user dashboard.
- Generate Key: Create a new API key. You might be able to name it for easier identification.
- Secure Your Key: Copy the generated key and store it securely (e.g., password manager, environment variable). Never expose it in public code repositories or client-side applications.
All API requests require this key to be sent in the X-API-KEY
header.
Before diving into code, here are some primary endpoints we'll be working with (refer to the Swagger docs for exhaustive details):
GET /tokens/scan/{chain}/{contractAddress}
: Performs a real-time scan of a token. Returns risk levels, warnings, contract details, liquidity info, etc.GET /tokens/source-code/{chain}/{contractAddress}
: Retrieves a token's verified smart contract source code and ABI.GET /wallets/risk-rating/{chain}/{walletAddress}
: Assesses the risk profile of a given wallet address.GET /tokens/search
: Searches for tokens by name or symbol.GET /utils/chains
: Lists all blockchain networks supported by the API.
The Base URL for all requests is: https://api.rugcheck.xyz
How to Use the Rugcheck.xyz API: In-Depth Python Examples
This is where we get practical. We'll use Python with the requests
library.
Prerequisites:
- Python 3.x installed.
requests
library:pip install requests
- Your Rugcheck.xyz API key.
1. Setup and Core API Call Function
First, let's set up our environment and create a reusable function to handle API calls. It's best practice to store your API key as an environment variable.Python
import requests
import json
import os
# Load API key from environment variable for security
API_KEY = os.getenv('RUGCHECK_API_KEY')
BASE_URL = "https://api.rugcheck.xyz"
if not API_KEY:
print("Error: RUGCHECK_API_KEY environment variable not set.")
# You might want to exit or raise an exception here in a real application
# For demonstration, we'll allow it to proceed but calls will fail.
# API_KEY = "YOUR_FALLBACK_API_KEY_FOR_TESTING_ONLY" # Not recommended for actual use
HEADERS = {
"X-API-KEY": API_KEY,
"Accept": "application/json" # Good practice to specify accepted response type
}
def make_api_request(endpoint, params=None):
"""
Makes a GET request to the Rugcheck.xyz API.
Args:
endpoint (str): The API endpoint path (e.g., "/utils/chains").
params (dict, optional): Query parameters for the request.
Returns:
dict or None: The JSON response as a Python dictionary, or None if an error occurs.
"""
if not API_KEY or API_KEY == "YOUR_FALLBACK_API_KEY_FOR_TESTING_ONLY":
print("Error: API Key is not properly configured.")
return None
url = f"{BASE_URL}{endpoint}"
try:
response = requests.get(url, headers=HEADERS, params=params, timeout=30) # 30-second timeout
response.raise_for_status() # Raises HTTPError for bad responses (4xx or 5xx)
return response.json()
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
print(f"Status Code: {response.status_code}")
try:
# Try to print error details from API if available in JSON
print(f"Error Response: {response.json()}")
except json.JSONDecodeError:
print(f"Error Response (not JSON): {response.text}")
except requests.exceptions.ConnectionError as conn_err:
print(f"Connection error occurred: {conn_err}")
except requests.exceptions.Timeout as timeout_err:
print(f"Timeout error occurred: {timeout_err}")
except requests.exceptions.RequestException as req_err:
print(f"An unexpected error occurred with the request: {req_err}")
except json.JSONDecodeError: # If response.json() fails for non-HTTPError cases
print("Failed to decode JSON response from API.")
print(f"Response content: {response.text if 'response' in locals() else 'No response object'}")
return None
Important: For the following examples to run, ensure RUGCHECK_API_KEY
is set in your environment. You'll also need valid contract addresses and wallet addresses for the respective chains.
2. Example 1: Deep Dive into Token Scan (/tokens/scan/{chain}/{contractAddress}
)
This is one of the most powerful endpoints. Let's scan a token and dissect the response.Python
def get_token_scan_details(chain, contract_address, include_dex=True, include_events=False):
"""
Scans a token and prints detailed information.
"""
print(f"\n--- Scanning Token: {contract_address} on {chain} ---")
endpoint = f"/tokens/scan/{chain}/{contract_address}"
params = {
"includeDexScreenerData": str(include_dex).lower(), # API expects string "true" or "false"
"includeSignificantEvents": str(include_events).lower()
}
data = make_api_request(endpoint, params=params)
if data:
print(f"Scan ID: {data.get('id')}")
print(f"Risk Level: {data.get('riskLevel')}")
trust_score_data = data.get('trustScore', {})
print(f"Trust Score: {trust_score_data.get('value')} ({trust_score_data.get('rating')})")
print("\nScams Found:")
scams = data.get('scams', [])
if scams:
for scam in scams:
print(f" - Type: {scam.get('type')}, Severity: {scam.get('severity')}, Message: {scam.get('message')}")
else:
print(" No specific scam indicators found by this scan.")
print("\nWarnings:")
warnings = data.get('warnings', [])
if warnings:
for warning in warnings:
print(f" - Type: {warning.get('type')}, Severity: {warning.get('severity')}, Message: {warning.get('message')}")
else:
print(" No warnings found by this scan.")
contract_details = data.get('contractDetails', {})
print("\nContract Details:")
print(f" Name: {contract_details.get('name')}")
print(f" Symbol: {contract_details.get('symbol')}")
print(f" Decimals: {contract_details.get('decimals')}")
print(f" Owner: {contract_details.get('ownerAddress')}")
print(f" Creator: {contract_details.get('creatorAddress')}")
print(f" Verified: {contract_details.get('isVerified')}")
if contract_details.get('isProxy'):
print(f" Proxy Implementation: {contract_details.get('proxyImplementationAddress')}")
taxes = data.get('taxes', {})
print("\nTaxes:")
print(f" Buy Tax: {taxes.get('buyTax')}%")
print(f" Sell Tax: {taxes.get('sellTax')}%")
print(f" Transfer Tax: {taxes.get('transferTax')}%")
if taxes.get('isBuyTaxModifiable') or taxes.get('isSellTaxModifiable') or taxes.get('isTransferTaxModifiable'):
print(" Warning: One or more taxes may be modifiable.")
liquidity = data.get('liquidityDetails', {})
print("\nLiquidity Details:")
if liquidity.get('dexes'):
for dex in liquidity['dexes']:
print(f" DEX: {dex.get('name')} ({dex.get('pairAddress')})")
print(f" Liquidity: {dex.get('liquidityAmountInUsd')} USD")
print(f" Total LP Supply: {dex.get('totalSupply')}")
if dex.get('locks'):
for lock in dex['locks']:
print(f" Lock: Amount {lock.get('amountLocked')} until {lock.get('unlockDate')}, Vendor: {lock.get('vendorName')}")
else:
print(" No explicit LP locks found for this DEX.")
else:
print(" No DEX liquidity information found.")
holder_analysis = data.get('holderAnalysis', {})
print("\nHolder Analysis:")
print(f" Holder Count: {holder_analysis.get('holderCount')}")
if holder_analysis.get('topHolders'):
print(" Top Holders:")
for i, holder in enumerate(holder_analysis['topHolders'][:3]): # Display top 3 for brevity
print(f" {i+1}. Address: {holder.get('address')}, Balance: {holder.get('balance')}, % Supply: {holder.get('percentage')}%")
if include_dex and 'dexScreenerData' in data and data['dexScreenerData']:
dex_data = data['dexScreenerData']
print("\nDEX Screener Data:")
print(f" Price (USD): {dex_data.get('priceUsd')}")
print(f" FDV (USD): {dex_data.get('fdv')}")
print(f" Volume (24h USD): {dex_data.get('volume', {}).get('h24')}")
# Add more fields as needed
# You can similarly process 'significantEvents' if include_events was True
# print(json.dumps(data, indent=2)) # To print the full raw response for exploration
else:
print("Failed to retrieve token scan details.")
# --- Usage Example for Token Scan ---
# Replace with a valid contract address and chain from the supported list (e.g., 'bsc', 'ethereum')
# For BSC (BEP-20 tokens): e.g., WBNB contract "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"
# For Ethereum (ERC-20 tokens): e.g., USDC contract "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
# test_chain = "bsc"
# test_contract = "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c" # WBNB on BSC (example)
# get_token_scan_details(test_chain, test_contract, include_dex=True)
Interpretation of Scan Results:
riskLevel
: Gives an immediate sense of potential danger. "CRITICAL" or "HIGH" warrant extreme caution.trustScore
: A numerical score that can be tracked or benchmarked.scams
andwarnings
: These arrays are crucial. They detail specific issues likeHONEYPOT
,PROXY_CONTRACT
,HIGH_TAXES
,OWNERSHIP_NOT_RENOUNCED
,BLACKLIST_FUNCTIONS
, etc. Always review these messages carefully.taxes
: High or modifiable taxes are red flags.liquidityDetails
: Look for significant unlocked liquidity or a large portion held by the deployer. Locked liquidity is a good sign, but verify lock duration and vendor.holderAnalysis
: High concentration of tokens in a few wallets (especially the deployer or team wallets if not vested) can be risky.
3. Example 2: Retrieving Source Code (/tokens/source-code/{chain}/{contractAddress}
)
Knowing if a contract is verified and being able to inspect its source code is vital.Python
def get_token_source_code(chain, contract_address):
"""
Retrieves and displays information about a token's source code.
"""
print(f"\n--- Retrieving Source Code for: {contract_address} on {chain} ---")
endpoint = f"/tokens/source-code/{chain}/{contract_address}"
data = make_api_request(endpoint)
if data:
print(f"Contract Name: {data.get('contractName')}")
print(f"Is Verified: {data.get('isVerified')}")
if data.get('isVerified'):
# The ABI can be very long, so just print a snippet or its presence
print(f"ABI: {'Present' if data.get('abi') else 'Not available'}")
source_code = data.get('sourceCode')
if isinstance(source_code, str):
print(f"Source Code Snippet (first 500 chars):\n{source_code[:500]}...")
# In a real app, you might save this to a file:
# with open(f"{contract_address}_source.sol", "w") as f:
# f.write(source_code)
# print(f"Full source code saved to {contract_address}_source.sol")
elif isinstance(source_code, dict): # For multi-file sources
print("Source Code (multiple files):")
for filename, content in source_code.items():
print(f" File: {filename}, Snippet (first 200 chars): {content.get('content', '')[:200]}...")
else:
print("Source Code: Not available or unexpected format.")
else:
print("Contract source code is not verified or not available.")
else:
print("Failed to retrieve source code information.")
# --- Usage Example for Source Code ---
# test_chain_eth = "ethereum"
# usdc_contract_eth = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" # USDC on Ethereum (verified)
# get_token_source_code(test_chain_eth, usdc_contract_eth)
4. Example 3: Wallet Risk Rating (/wallets/risk-rating/{chain}/{walletAddress}
)
Analyzing wallets associated with a project (e.g., deployer, team wallets) can reveal risks.Python
def get_wallet_risk_rating(chain, wallet_address):
"""
Retrieves and displays the risk rating for a wallet.
"""
print(f"\n--- Getting Risk Rating for Wallet: {wallet_address} on {chain} ---")
endpoint = f"/wallets/risk-rating/{chain}/{wallet_address}"
data = make_api_request(endpoint)
if data:
print(f"Overall Wallet Risk Level: {data.get('riskLevel')}")
print(f"Summary: {data.get('summary')}")
print("\nAssociated Tokens with Risk:")
associated_tokens = data.get('associatedTokens', [])
if associated_tokens:
for token_info in associated_tokens:
print(f" - Token: {token_info.get('symbol')} ({token_info.get('contractAddress')})")
print(f" Chain: {token_info.get('chain')}")
print(f" Risk Level: {token_info.get('riskLevel')}")
print(f" Role: {token_info.get('roleInTokenContext')} (e.g., Deployer, Owner)")
else:
print(" No associated tokens with notable risk found linked to this wallet by the scan.")
# Other fields like 'activitySummary', 'knownAssociations' could also be parsed.
# print(json.dumps(data, indent=2)) # For full response
else:
print("Failed to retrieve wallet risk rating.")
# --- Usage Example for Wallet Risk Rating ---
# Replace with a real wallet address and chain
# Example: A deployer wallet address you are investigating
# test_wallet_chain = "bsc"
# test_wallet_address = "0x000000000000000000000000000000000000dead" # Example, use a real one
# get_wallet_risk_rating(test_wallet_chain, test_wallet_address)
5. Example 4: Searching for Tokens (/tokens/search
)
If you only have a token name or symbol, you can try to find its contract address.Python
def search_for_token(query, chain=None, page_size=5):
"""
Searches for tokens and displays results.
"""
print(f"\n--- Searching for tokens with query: '{query}' ---")
endpoint = "/tokens/search"
params = {
"query": query,
"pageSize": page_size
}
if chain:
params["chain"] = chain
print(f"Filtering by chain: {chain}")
data = make_api_request(endpoint, params=params)
if data and 'items' in data:
tokens_found = data['items']
print(f"Found {len(tokens_found)} token(s) (showing up to {page_size}):")
if tokens_found:
for token in tokens_found:
print(f" Name: {token.get('name')} ({token.get('symbol')})")
print(f" Contract: {token.get('contractAddress')}")
print(f" Chain: {token.get('chain')}")
print(f" Risk Level: {token.get('riskLevel')}")
print(f" DEX Screener Link: {token.get('dexScreenerLink')}")
print("-" * 20)
else:
print("No tokens found matching your query.")
# Pagination details are also available if you want to implement full pagination
# print(f"Total Items: {data.get('totalItems')}, Page: {data.get('pageNumber')}, Total Pages: {data.get('totalPages')}")
else:
print("Failed to perform token search or no items found.")
# --- Usage Example for Token Search ---
# search_for_token("CAKE", chain="bsc")
# search_for_token("Shiba Inu") # Broad search across chains
6. Example 5: Listing Supported Chains (/utils/chains
)
A simple utility call to get a list of chains the API supports. This can be useful for validating user input or populating dropdowns in an application.Python
def list_supported_chains():
"""
Lists all chains supported by the Rugcheck.xyz API.
"""
print("\n--- Supported Blockchains by Rugcheck.xyz API ---")
endpoint = "/utils/chains"
data = make_api_request(endpoint)
if data:
for chain_info in data:
print(f" ID: {chain_info.get('id'):<15} Name: {chain_info.get('name'):<20} Native: {chain_info.get('nativeCurrencySymbol')}")
else:
print("Failed to retrieve supported chains.")
# --- Usage Example for Listing Chains ---
# list_supported_chains()
Running the Examples:
To run these examples:
- Save the code as a Python file (e.g.,
rugcheck_user.py
). - Set your API key:
export RUGCHECK_API_KEY="YOUR_ACTUAL_API_KEY"
(on Linux/macOS) or set it in your system's environment variables (Windows). - Uncomment the usage example lines at the end of each function block you want to test.
- Run from your terminal:
python rugcheck_user.py
Part 5: Best Practices and Advanced Tips
- API Key Security: Reiterate: Use environment variables or a secrets management service. Never hardcode keys.
- Rate Limiting: Be mindful of API rate limits. If you get
429 Too Many Requests
errors, slow down your requests. Implement exponential backoff for retries. The API documentation or your plan details should specify limits. - Error Handling: The
make_api_request
function includes basic error handling. Expand on this as needed for your application (e.g., logging errors to a file, specific retry logic for certain error codes). - Refer to Swagger: The Swagger UI (
https://api.rugcheck.xyz/swagger/index.html
) is your definitive source for all endpoints, parameters, request bodies, and response schemas. Check it often for updates. - Caching: For data that doesn't change frequently (like source code of a deployed contract or a scan result unless
forceRescan
is used), consider caching API responses to improve performance and reduce API call volume. - Understand Limitations: Automated tools like Rugcheck.xyz are incredibly valuable but not infallible. They identify known patterns and potential risks. Sophisticated scammers may devise new techniques. Always combine API data with your own research (DYOR) and critical thinking.
- Data Interpretation: The API provides data; you provide the interpretation. Understand what each field means (e.g., a "warning" about
OWNERSHIP_NOT_RENOUNCED
is a significant risk factor).
Conclusion
The Rugcheck.xyz API offers a robust and detailed way to programmatically assess the risks associated with cryptocurrency projects. By mastering its usage through practical coding, as demonstrated in this guide, you can significantly enhance your due diligence process, build safer automated trading systems, and contribute to a more transparent DeFi ecosystem. Remember to always use such tools responsibly and in conjunction with comprehensive research. The power of the API lies in your ability to effectively query, parse, and interpret the wealth of data it provides.
Want an integrated, All-in-One platform for your Developer Team to work together with maximum productivity?
Apidog delivers all your demans, and replaces Postman at a much more affordable price!