러그체크 API 키 얻는 방법 및 러그체크 API 사용법

Mark Ponomarev

Mark Ponomarev

4 June 2025

러그체크 API 키 얻는 방법 및 러그체크 API 사용법

암호화폐 환경은 기회로 가득 차 있지만, 상당한 위험도 따릅니다. 러그 풀(rug pulls)과 부실하게 설계된 토큰은 막대한 손실로 이어질 수 있습니다. Rugcheck.xyz는 잠재적인 위험 신호를 분석하여 암호화폐 프로젝트에 대한 중요한 서비스를 제공합니다. API를 통해 개발자, 트레이더 및 분석가는 이러한 인사이트에 프로그래밍 방식으로 액세스하여 실사(due diligence) 노력을 자동화하고 확장할 수 있습니다. 이 가이드에서는 Rugcheck.xyz API를 사용하는 방법에 중점을 두고 실용적인 Python 예제를 제공합니다.

💡
아름다운 API 문서를 생성하는 훌륭한 API 테스트 도구를 원하시나요?

최대한의 생산성으로 개발팀이 함께 작업할 수 있는 통합된 올인원 플랫폼을 원하시나요?

Apidog는 귀하의 모든 요구 사항을 충족하며 Postman을 훨씬 저렴한 가격으로 대체합니다!
button

Rugcheck.xyz 및 API 개요

Rugcheck.xyz란 무엇인가요?

Rugcheck.xyz는 악의적인 의도(러그 풀 또는 허니팟 등) 또는 내재된 위험의 징후를 파악하기 위해 암호화폐 토큰 및 스마트 계약을 면밀히 조사하도록 설계된 플랫폼입니다. 계약 코드, 유동성, 토크노믹스, 개발자 지갑 등을 검사하여 위험 평가 및 상세 보고서를 제공합니다.

API를 사용하는 이유는 무엇인가요?

API는 Rugcheck.xyz의 분석 엔진에 프로그래밍 방식으로 액세스할 수 있도록 하여 다음을 가능하게 합니다.

Rugcheck.xyz API 키 얻기 – 필수 사항

API를 사용하려면 API 키가 필요합니다. Rugcheck.xyz API 문서(https://api.rugcheck.xyz/swagger/index.html)는 /user/api-keys와 같은 엔드포인트를 통한 키 관리를 위한 사용자 계정 시스템을 암시합니다.

  1. 등록/로그인: Rugcheck.xyz 웹사이트를 방문하여 계정을 만들거나 로그인합니다.
  2. API 설정 찾기: 사용자 대시보드에서 "API", "개발자" 또는 "API 키" 섹션을 찾습니다.
  3. 키 생성: 새 API 키를 생성합니다. 식별을 쉽게 하기 위해 이름을 지정할 수 있습니다.
  4. 키 보안: 생성된 키를 복사하여 안전하게 보관합니다(예: 암호 관리자, 환경 변수). 공개 코드 저장소 또는 클라이언트 측 애플리케이션에 절대 노출하지 마십시오.

모든 API 요청은 이 키를 X-API-KEY 헤더에 포함하여 전송해야 합니다.

코드를 시작하기 전에 사용할 주요 엔드포인트는 다음과 같습니다(자세한 내용은 Swagger 문서를 참조하십시오).

모든 요청의 기본 URLhttps://api.rugcheck.xyz입니다.

Rugcheck.xyz API 사용 방법: 심층 Python 예제

이제 실용적인 부분을 다룰 차례입니다. Python과 requests 라이브러리를 사용하겠습니다.

전제 조건:

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})

이것은 가장 강력한 엔드포인트 중 하나입니다. 토큰을 스캔하고 응답을 분석해 보겠습니다.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)

스캔 결과 해석:

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()

예제 실행:

이 예제를 실행하려면:

  1. 코드를 Python 파일(예: rugcheck_user.py)로 저장합니다.
  2. API 키 설정: export RUGCHECK_API_KEY="YOUR_ACTUAL_API_KEY" (Linux/macOS) 또는 시스템 환경 변수에 설정(Windows)합니다.
  3. 테스트하려는 각 함수 블록 끝에 있는 사용 예제 줄의 주석을 해제합니다.
  4. 터미널에서 실행: python rugcheck_user.py

파트 5: 모범 사례 및 고급 팁

결론

Rugcheck.xyz API는 암호화폐 프로젝트와 관련된 위험을 프로그래밍 방식으로 평가하는 강력하고 상세한 방법을 제공합니다. 이 가이드에서 보여준 실용적인 코딩을 통해 사용법을 숙달하면 실사 프로세스를 크게 개선하고 더 안전한 자동 거래 시스템을 구축하며 더 투명한 DeFi 생태계에 기여할 수 있습니다. 항상 이러한 도구를 책임감 있게 사용하고 포괄적인 연구와 함께 사용해야 합니다. API의 힘은 API가 제공하는 풍부한 데이터를 효과적으로 쿼리하고 구문 분석하며 해석하는 능력에 있습니다.

💡
아름다운 API 문서를 생성하는 훌륭한 API 테스트 도구를 원하시나요?

최대한의 생산성으로 개발팀이 함께 작업할 수 있는 통합된 올인원 플랫폼을 원하시나요?

Apidog는 귀하의 모든 요구 사항을 충족하며 Postman을 훨씬 저렴한 가격으로 대체합니다!
button

Apidog에서 API 설계-첫 번째 연습

API를 더 쉽게 구축하고 사용하는 방법을 발견하세요