暗号通貨の状況は機会に満ちていますが、同時に大きなリスクも伴います。ラグプルや設計の不十分なトークンは、多大な損失につながる可能性があります。Rugcheck.xyzは、暗号プロジェクトを潜在的な危険信号がないか分析することで、重要なサービスを提供しています。そのAPIを使用すると、開発者、トレーダー、アナリストはこれらの洞察にプログラムでアクセスでき、デューデリジェンスの取り組みを自動化およびスケーリングできます。このガイドでは、Rugcheck.xyz APIの使用方法に重点を置き、実践的なPythonの例を提供します。
開発チームが最大の生産性で協力するための統合されたオールインワンプラットフォームをお探しですか?
Apidogはあなたのすべての要求を満たし、Postmanをはるかに手頃な価格で置き換えます!
Rugcheck.xyzとそのAPIの概要
Rugcheck.xyzとは?
Rugcheck.xyzは、ラグプルやハニーポットなどの悪意のある意図や、固有のリスクの兆候がないか、暗号通貨トークンとスマートコントラクトを精査するために設計されたプラットフォームです。コントラクトコード、流動性、トークノミクス、開発者のウォレットなどを調査し、リスク評価と詳細なレポートを提供します。
なぜAPIなのか?
APIはRugcheck.xyzの分析エンジンへのプログラムアクセスを許可し、以下を可能にします。
- 自動化: トレーディングボットや新しいトークンアラートシステムにチェックを統合します。
- スケーラビリティ: 手動チェックよりもはるかに高速に多数のトークンを分析します。
- カスタマイズ: 生のAPIデータを使用して、独自のダッシュボードとリスクモデルを構築します。
Rugcheck.xyz APIキーの取得 – 必須事項
APIを使用するには、APIキーが必要です。Rugcheck.xyz APIドキュメント(https://api.rugcheck.xyz/swagger/index.html
)は、/user/api-keys
のようなエンドポイントを介したキー管理のためのユーザーアカウントシステムを示唆しています。
- 登録/ログイン: Rugcheck.xyzのメインウェブサイトにアクセスし、アカウントを作成するかサインインします。
- API設定を見つける: ユーザーダッシュボードで「API」、「開発者」、または「APIキー」セクションを探します。
- キーを生成する: 新しいAPIキーを作成します。識別しやすくするために名前を付けられる場合があります。
- キーを安全に保管する: 生成されたキーをコピーし、安全な場所に保管します(例:パスワードマネージャー、環境変数)。公開コードリポジトリやクライアントサイドアプリケーションで公開しないでください。
すべてのAPIリクエストでは、このキーをX-API-KEY
ヘッダーに含めて送信する必要があります。
コードに入る前に、これから使用する主要なエンドポイントをいくつか紹介します(詳細についてはSwaggerドキュメントを参照してください)。
GET /tokens/scan/{chain}/{contractAddress}
: トークンのリアルタイムスキャンを実行します。リスクレベル、警告、コントラクトの詳細、流動性情報などを返します。GET /tokens/source-code/{chain}/{contractAddress}
: トークンの検証済みスマートコントラクトソースコードとABIを取得します。GET /wallets/risk-rating/{chain}/{walletAddress}
: 指定されたウォレットアドレスのリスクプロファイルを評価します。GET /tokens/search
: 名前またはシンボルでトークンを検索します。GET /utils/chains
: APIでサポートされているすべてのブロックチェーンネットワークをリストアップします。
すべてのリクエストのベースURLは次のとおりです:https://api.rugcheck.xyz
Rugcheck.xyz APIの使用方法:詳細なPythonの例
ここから実践的な内容に入ります。Pythonとrequests
ライブラリを使用します。
前提条件:
- Python 3.xがインストールされていること。
requests
ライブラリ:pip install requests
- Rugcheck.xyz APIキー。
1. セットアップとコアAPI呼び出し関数
まず、環境をセットアップし、API呼び出しを処理するための再利用可能な関数を作成しましょう。APIキーを環境変数として保存するのがベストプラクティスです。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
重要:以下の例を実行するには、RUGCHECK_API_KEY
が環境に設定されていることを確認してください。また、それぞれのチェーンに対して有効なコントラクトアドレスとウォレットアドレスが必要です。
2. 例1:トークンスキャンの詳細(/tokens/scan/{chain}/{contractAddress}
)
これは最も強力なエンドポイントの1つです。トークンをスキャンして応答を分析してみましょう。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)
スキャン結果の解釈:
riskLevel
:潜在的な危険性をすぐに把握できます。「CRITICAL」または「HIGH」は細心の注意が必要です。trustScore
:追跡またはベンチマークできる数値スコアです。scams
およびwarnings
:これらの配列は非常に重要です。HONEYPOT
、PROXY_CONTRACT
、HIGH_TAXES
、OWNERSHIP_NOT_RENOUNCED
、BLACKLIST_FUNCTIONS
などの具体的な問題が詳細に示されます。これらのメッセージは常に注意深く確認してください。taxes
:高税率または変更可能な税率は危険信号です。liquidityDetails
:大量のロックされていない流動性や、デプロイヤーが大量に保有している場合はリスクがあります。ロックされた流動性は良い兆候ですが、ロック期間とベンダーを確認してください。holderAnalysis
:少数のウォレット(特にデプロイヤーまたはチームのウォレットで、ベスティングされていない場合)にトークンが集中している場合はリスクが高い可能性があります。
3. 例2:ソースコードの取得(/tokens/source-code/{chain}/{contractAddress}
)
コントラクトが検証されているかどうかを知り、そのソースコードを検査できることは非常に重要です。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. 例3:ウォレットリスク評価(/wallets/risk-rating/{chain}/{walletAddress}
)
プロジェクトに関連付けられたウォレット(例:デプロイヤー、チームウォレット)を分析することで、リスクが明らかになることがあります。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. 例4:トークンの検索(/tokens/search
)
トークン名またはシンボルしか分からない場合、そのコントラクトアドレスを見つけることができます。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. 例5:サポートされているチェーンのリストアップ(/utils/chains
)
APIがサポートしているチェーンのリストを取得するためのシンプルなユーティリティ呼び出しです。これは、ユーザー入力の検証やアプリケーションのドロップダウンリストの作成に役立ちます。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()
例の実行:
これらの例を実行するには:
- コードをPythonファイルとして保存します(例:
rugcheck_user.py
)。 - APIキーを設定します:
export RUGCHECK_API_KEY="YOUR_ACTUAL_API_KEY"
(Linux/macOS)またはシステム環境変数(Windows)に設定します。 - テストしたい各関数ブロックの末尾にある使用例の行のコメントを解除します。
- ターミナルから実行します:
python rugcheck_user.py
パート5:ベストプラクティスと高度なヒント
- APIキーのセキュリティ: 再度強調します:環境変数またはシークレット管理サービスを使用してください。キーをハードコーディングしないでください。
- レート制限: APIのレート制限に注意してください。
429 Too Many Requests
エラーが発生した場合は、リクエストの速度を落としてください。リトライには指数バックオフを実装してください。APIドキュメントまたはプランの詳細で制限が指定されているはずです。 - エラー処理:
make_api_request
関数には基本的なエラー処理が含まれています。アプリケーションの必要に応じてこれを拡張してください(例:エラーをファイルにログ記録する、特定のエラーコードに対する特定のリトライロジックなど)。 - Swaggerを参照する: Swagger UI(
https://api.rugcheck.xyz/swagger/index.html
)は、すべてのエンドポイント、パラメーター、リクエストボディ、およびレスポンススキーマに関する決定的な情報源です。定期的に更新を確認してください。 - キャッシング: 頻繁に変更されないデータ(デプロイされたコントラクトのソースコードや、
forceRescan
を使用しない限りスキャン結果など)については、APIレスポンスをキャッシングしてパフォーマンスを向上させ、API呼び出し量を減らすことを検討してください。 - 制限を理解する: Rugcheck.xyzのような自動化ツールは非常に価値がありますが、完璧ではありません。既知のパターンと潜在的なリスクを特定します。巧妙な詐欺師は新しい手法を考案する可能性があります。常にAPIデータと自身の調査(DYOR)および批判的思考を組み合わせてください。
- データの解釈: APIはデータを提供します。解釈はあなたが行います。各フィールドが何を意味するかを理解してください(例:
OWNERSHIP_NOT_RENOUNCED
に関する「警告」は重大なリスク要因です)。
結論
Rugcheck.xyz APIは、暗号通貨プロジェクトに関連するリスクをプログラムで評価するための堅牢で詳細な方法を提供します。このガイドで示された実践的なコーディングを通じてその使用法を習得することで、デューデリジェンスプロセスを大幅に強化し、より安全な自動取引システムを構築し、より透明性の高いDeFiエコシステムに貢献できます。常に責任を持って、包括的な調査と組み合わせてこれらのツールを使用することを忘れないでください。APIの力は、提供される豊富なデータを効果的にクエリ、解析、解釈する能力にあります。
開発チームが最大の生産性で協力するための統合されたオールインワンプラットフォームをお探しですか?
Apidogはあなたのすべての要求を満たし、Postmanをはるかに手頃な価格で置き換えます!