Docs

wallet/getcontract - Get TRON Smart Contract Info

Retrieve TRON smart contract information including bytecode, ABI, and metadata. Essential for contract verification and interaction via Dwellir RPC.

Comprehensive Contract Analysis

Dwellir's TRON endpoints provide complete smart contract information including bytecode and metadata. Build contract explorers and verification tools with our optimized contract data API.

Explore smart contracts

Retrieves comprehensive information about a deployed smart contract on the TRON network, including bytecode, ABI, creator details, and deployment information.

When to Use This Method

wallet/getcontract is essential for:

  • Contract Verification - Verify deployed contract matches source code
  • ABI Retrieval - Get contract interface for interaction
  • Contract Analysis - Analyze contract functionality and security
  • Block Explorers - Display contract information to users
  • Development Tools - Build contract interaction interfaces

Parameters

  1. value - string (required)

    • Smart contract address in Base58 format
    • Example: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t" (USDT contract)
  2. visible - boolean (optional, default: false)

    • true - Use Base58 address format in response
    • false - Use hex address format in response
JSON
{
  "value": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
  "visible": true
}

Returns

Contract Object containing:

  • bytecode - Contract bytecode (hex string)
  • name - Contract name (if available)
  • abi - Contract ABI (if available)
  • origin_address - Contract creator address
  • origin_energy_limit - Energy limit set by creator
  • contract_address - Contract address
  • code_hash - Hash of the contract code

Implementation Examples

Bash
# Get contract information
curl -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getcontract" \
  -H "Content-Type: application/json" \
  -d '{
    "value": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
    "visible": true
  }'

# Extract key contract information
curl -s -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getcontract" \
  -H "Content-Type: application/json" \
  -d '{
    "value": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
    "visible": true
  }' | jq '{
    address: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
    has_contract: (.bytecode != null and .bytecode != ""),
    creator: .origin_address,
    energy_limit: .origin_energy_limit,
    name: .name // "Unknown",
    has_abi: (.abi != null and .abi != ""),
    bytecode_size: (.bytecode | length) / 2,
    code_hash: .code_hash
  }'
JavaScript
const TRON_API = 'https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY';

// Get contract information
async function getContract(contractAddress) {
  const response = await fetch(`${TRON_API}/wallet/getcontract`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      value: contractAddress,
      visible: true
    })
  });

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  return await response.json();
}

// Smart contract analyzer
class TronContractAnalyzer {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.apiUrl = `https://api-tron-mainnet.n.dwellir.com/${apiKey}`;
  }
  
  async getContractInfo(contractAddress) {
    try {
      const contract = await this.getContract(contractAddress);
      
      if (!contract.bytecode) {
        return {
          exists: false,
          address: contractAddress,
          message: 'Contract not found or not deployed'
        };
      }
      
      return {
        exists: true,
        address: contractAddress,
        bytecode: contract.bytecode,
        codeHash: contract.code_hash,
        creator: contract.origin_address,
        energyLimit: contract.origin_energy_limit || 0,
        name: contract.name || 'Unknown',
        abi: this.parseABI(contract.abi),
        isVerified: !!contract.abi,
        functions: this.extractFunctions(contract.abi),
        events: this.extractEvents(contract.abi),
        analysis: this.analyzeContract(contract)
      };
    } catch (error) {
      console.error('Error getting contract info:', error);
      throw error;
    }
  }
  
  async getContract(contractAddress) {
    const response = await fetch(`${this.apiUrl}/wallet/getcontract`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ value: contractAddress, visible: true })
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    return await response.json();
  }
  
  parseABI(abiString) {
    if (!abiString) return null;
    
    try {
      if (typeof abiString === 'string') {
        return JSON.parse(abiString);
      }
      return abiString;
    } catch (error) {
      console.warn('Failed to parse ABI:', error);
      return null;
    }
  }
  
  extractFunctions(abi) {
    if (!abi || !Array.isArray(abi)) return [];
    
    return abi
      .filter(item => item.type === 'function')
      .map(func => ({
        name: func.name,
        type: func.stateMutability || 'nonpayable',
        inputs: func.inputs || [],
        outputs: func.outputs || [],
        signature: this.buildFunctionSignature(func),
        isView: func.stateMutability === 'view' || func.stateMutability === 'pure',
        isPayable: func.stateMutability === 'payable'
      }));
  }
  
  extractEvents(abi) {
    if (!abi || !Array.isArray(abi)) return [];
    
    return abi
      .filter(item => item.type === 'event')
      .map(event => ({
        name: event.name,
        inputs: event.inputs || [],
        signature: this.buildEventSignature(event),
        anonymous: event.anonymous || false
      }));
  }
  
  buildFunctionSignature(func) {
    const inputs = func.inputs?.map(input => input.type).join(',') || '';
    return `${func.name}(${inputs})`;
  }
  
  buildEventSignature(event) {
    const inputs = event.inputs?.map(input => input.type).join(',') || '';
    return `${event.name}(${inputs})`;
  }
  
  analyzeContract(contract) {
    const bytecode = contract.bytecode || '';
    const abi = this.parseABI(contract.abi);
    
    return {
      bytecodeSize: Math.floor(bytecode.length / 2), // Convert hex to bytes
      hasConstructor: abi?.some(item => item.type === 'constructor') || false,
      hasFallback: abi?.some(item => item.type === 'fallback') || false,
      hasReceive: abi?.some(item => item.type === 'receive') || false,
      functionCount: abi?.filter(item => item.type === 'function').length || 0,
      eventCount: abi?.filter(item => item.type === 'event').length || 0,
      hasPayableFunctions: abi?.some(item => 
        item.type === 'function' && item.stateMutability === 'payable'
      ) || false,
      isProxy: this.detectProxy(bytecode, abi),
      isToken: this.detectTokenStandard(abi),
      securityFlags: this.analyzeSecurityFeatures(abi)
    };
  }
  
  detectProxy(bytecode, abi) {
    // Simplified proxy detection - look for delegate call patterns
    const proxyPatterns = [
      '3660006000376110006000366000f3', // Minimal proxy pattern
      'delegatecall' // Contains delegate call
    ];
    
    return proxyPatterns.some(pattern => 
      bytecode.toLowerCase().includes(pattern.toLowerCase())
    );
  }
  
  detectTokenStandard(abi) {
    if (!abi || !Array.isArray(abi)) return null;
    
    const functions = abi.filter(item => item.type === 'function').map(f => f.name);
    const events = abi.filter(item => item.type === 'event').map(e => e.name);
    
    // Check for TRC20 standard
    const trc20Functions = ['totalSupply', 'balanceOf', 'transfer', 'transferFrom', 'approve', 'allowance'];
    const trc20Events = ['Transfer', 'Approval'];
    
    const hasTRC20Functions = trc20Functions.every(func => functions.includes(func));
    const hasTRC20Events = trc20Events.every(event => events.includes(event));
    
    if (hasTRC20Functions && hasTRC20Events) {
      return 'TRC20';
    }
    
    // Check for TRC721 standard
    const trc721Functions = ['balanceOf', 'ownerOf', 'approve', 'getApproved', 'setApprovalForAll', 'isApprovedForAll', 'transferFrom', 'safeTransferFrom'];
    const hasTRC721Functions = trc721Functions.every(func => functions.includes(func));
    
    if (hasTRC721Functions) {
      return 'TRC721';
    }
    
    return null;
  }
  
  analyzeSecurityFeatures(abi) {
    if (!abi || !Array.isArray(abi)) return [];
    
    const flags = [];
    const functions = abi.filter(item => item.type === 'function');
    
    // Check for common security patterns
    const hasOwner = functions.some(f => f.name.toLowerCase().includes('owner'));
    const hasPause = functions.some(f => 
      f.name.toLowerCase().includes('pause') || f.name.toLowerCase().includes('emergency')
    );
    const hasUpgrade = functions.some(f => f.name.toLowerCase().includes('upgrade'));
    const hasTimelock = functions.some(f => f.name.toLowerCase().includes('timelock'));
    
    if (hasOwner) flags.push('Ownable');
    if (hasPause) flags.push('Pausable');
    if (hasUpgrade) flags.push('Upgradeable');
    if (hasTimelock) flags.push('Timelock');
    
    return flags;
  }
}

// Contract verification helper
class TronContractVerifier {
  constructor(apiKey) {
    this.analyzer = new TronContractAnalyzer(apiKey);
  }
  
  async verifyContract(contractAddress, sourceCode, compilerVersion, optimized = false) {
    try {
      const contractInfo = await this.analyzer.getContractInfo(contractAddress);
      
      if (!contractInfo.exists) {
        return {
          verified: false,
          reason: 'Contract not found on blockchain'
        };
      }
      
      // In a real implementation, you would:
      // 1. Compile the source code with the specified compiler
      // 2. Compare the resulting bytecode with the deployed bytecode
      // 3. Handle constructor arguments and optimization settings
      
      // Simplified verification check
      const verification = this.simulateVerification(
        contractInfo.bytecode,
        sourceCode,
        compilerVersion,
        optimized
      );
      
      return {
        verified: verification.matches,
        contractInfo,
        verification: {
          sourceBytecodeHash: verification.sourceHash,
          deployedBytecodeHash: contractInfo.codeHash,
          matches: verification.matches,
          compilerVersion,
          optimized
        },
        reason: verification.matches ? 'Contract verified successfully' : 'Bytecode mismatch'
      };
      
    } catch (error) {
      return {
        verified: false,
        reason: `Verification error: ${error.message}`
      };
    }
  }
  
  simulateVerification(deployedBytecode, sourceCode, compilerVersion, optimized) {
    // This is a simplified simulation - real verification requires:
    // - Solidity compiler integration
    // - Constructor argument handling
    // - Library linking
    // - Optimization setting matching
    
    const sourceHash = this.hashString(sourceCode);
    const deployedHash = this.hashString(deployedBytecode);
    
    // In reality, you'd compile and compare actual bytecode
    return {
      matches: false, // Would be true if bytecode matches
      sourceHash,
      deployedHash
    };
  }
  
  hashString(str) {
    // Simple hash function for demo - use proper crypto hash in production
    let hash = 0;
    for (let i = 0; i < str.length; i++) {
      const char = str.charCodeAt(i);
      hash = ((hash << 5) - hash) + char;
      hash = hash & hash; // Convert to 32-bit integer
    }
    return hash.toString(16);
  }
}

// Contract interaction helper
class TronContractInteractor {
  constructor(apiKey) {
    this.analyzer = new TronContractAnalyzer(apiKey);
    this.apiUrl = `https://api-tron-mainnet.n.dwellir.com/${apiKey}`;
  }
  
  async generateInteractionInterface(contractAddress) {
    try {
      const contractInfo = await this.analyzer.getContractInfo(contractAddress);
      
      if (!contractInfo.exists) {
        throw new Error('Contract not found');
      }
      
      const interface = {
        address: contractAddress,
        name: contractInfo.name,
        isVerified: contractInfo.isVerified,
        functions: {
          view: contractInfo.functions.filter(f => f.isView),
          write: contractInfo.functions.filter(f => !f.isView),
          payable: contractInfo.functions.filter(f => f.isPayable)
        },
        events: contractInfo.events,
        standards: contractInfo.analysis.isToken ? [contractInfo.analysis.isToken] : [],
        interactionExamples: this.generateExamples(contractInfo)
      };
      
      return interface;
    } catch (error) {
      console.error('Error generating interface:', error);
      throw error;
    }
  }
  
  generateExamples(contractInfo) {
    const examples = [];
    
    // Generate examples for common functions
    const viewFunctions = contractInfo.functions.filter(f => f.isView && f.inputs.length === 0);
    const tokenFunctions = contractInfo.functions.filter(f => 
      ['balanceOf', 'totalSupply', 'name', 'symbol', 'decimals'].includes(f.name)
    );
    
    // Add view function examples
    viewFunctions.slice(0, 3).forEach(func => {
      examples.push({
        type: 'view',
        function: func.name,
        description: `Get ${func.name} information`,
        code: `// Call ${func.signature}\nconst result = await triggerSmartContract('${contractInfo.address}', '${func.signature}', '', ownerAddress);`
      });
    });
    
    // Add token-specific examples if it's a token
    if (contractInfo.analysis.isToken === 'TRC20') {
      examples.push({
        type: 'token',
        function: 'balanceOf',
        description: 'Get token balance for an address',
        code: `// Get TRC20 token balance\nconst balance = await getTokenBalance('${contractInfo.address}', 'USER_ADDRESS');`
      });
    }
    
    return examples;
  }
}

// Usage examples
(async () => {
  try {
    const analyzer = new TronContractAnalyzer('YOUR_API_KEY');
    const usdtContract = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t';
    
    // Get contract information
    const contractInfo = await analyzer.getContractInfo(usdtContract);
    console.log('Contract Info:', contractInfo.name);
    console.log('Is Token:', contractInfo.analysis.isToken);
    console.log('Function Count:', contractInfo.analysis.functionCount);
    console.log('Is Verified:', contractInfo.isVerified);
    
    // Generate interaction interface
    const interactor = new TronContractInteractor('YOUR_API_KEY');
    const interface = await interactor.generateInteractionInterface(usdtContract);
    console.log('View Functions:', interface.functions.view.length);
    console.log('Write Functions:', interface.functions.write.length);
    
    // Verify contract (simulation)
    const verifier = new TronContractVerifier('YOUR_API_KEY');
    const verification = await verifier.verifyContract(
      usdtContract,
      'contract source code here...',
      'v0.8.0',
      true
    );
    console.log('Verification:', verification.verified);
    
  } catch (error) {
    console.error('Error:', error);
  }
})();
Python
import requests
import json
import hashlib
from typing import Dict, List, Optional

class TronContractAnalyzer:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = f"https://api-tron-mainnet.n.dwellir.com/{api_key}"
        self.headers = {
            'Content-Type': 'application/json'
        }
    
    def get_contract(self, contract_address: str) -> Dict:
        """Get raw contract data"""
        url = f"{self.base_url}/wallet/getcontract"
        
        payload = {
            "value": contract_address,
            "visible": True
        }
        
        response = requests.post(url, headers=self.headers, json=payload)
        response.raise_for_status()
        
        return response.json()
    
    def get_contract_info(self, contract_address: str) -> Dict:
        """Get comprehensive contract information"""
        try:
            contract = self.get_contract(contract_address)
            
            if not contract.get('bytecode'):
                return {
                    'exists': False,
                    'address': contract_address,
                    'message': 'Contract not found or not deployed'
                }
            
            abi = self._parse_abi(contract.get('abi'))
            
            return {
                'exists': True,
                'address': contract_address,
                'bytecode': contract.get('bytecode'),
                'code_hash': contract.get('code_hash'),
                'creator': contract.get('origin_address'),
                'energy_limit': contract.get('origin_energy_limit', 0),
                'name': contract.get('name', 'Unknown'),
                'abi': abi,
                'is_verified': bool(contract.get('abi')),
                'functions': self._extract_functions(abi),
                'events': self._extract_events(abi),
                'analysis': self._analyze_contract(contract)
            }
        except Exception as e:
            print(f"Error getting contract info: {e}")
            raise
    
    def _parse_abi(self, abi_string) -> Optional[List]:
        """Parse ABI string to JSON"""
        if not abi_string:
            return None
        
        try:
            if isinstance(abi_string, str):
                return json.loads(abi_string)
            return abi_string
        except json.JSONDecodeError:
            print("Failed to parse ABI")
            return None
    
    def _extract_functions(self, abi: Optional[List]) -> List[Dict]:
        """Extract function information from ABI"""
        if not abi or not isinstance(abi, list):
            return []
        
        functions = []
        for item in abi:
            if item.get('type') == 'function':
                functions.append({
                    'name': item.get('name'),
                    'type': item.get('stateMutability', 'nonpayable'),
                    'inputs': item.get('inputs', []),
                    'outputs': item.get('outputs', []),
                    'signature': self._build_function_signature(item),
                    'is_view': item.get('stateMutability') in ['view', 'pure'],
                    'is_payable': item.get('stateMutability') == 'payable'
                })
        
        return functions
    
    def _extract_events(self, abi: Optional[List]) -> List[Dict]:
        """Extract event information from ABI"""
        if not abi or not isinstance(abi, list):
            return []
        
        events = []
        for item in abi:
            if item.get('type') == 'event':
                events.append({
                    'name': item.get('name'),
                    'inputs': item.get('inputs', []),
                    'signature': self._build_event_signature(item),
                    'anonymous': item.get('anonymous', False)
                })
        
        return events
    
    def _build_function_signature(self, func: Dict) -> str:
        """Build function signature string"""
        inputs = [inp.get('type', '') for inp in func.get('inputs', [])]
        return f"{func.get('name', '')}({','.join(inputs)})"
    
    def _build_event_signature(self, event: Dict) -> str:
        """Build event signature string"""
        inputs = [inp.get('type', '') for inp in event.get('inputs', [])]
        return f"{event.get('name', '')}({','.join(inputs)})"
    
    def _analyze_contract(self, contract: Dict) -> Dict:
        """Analyze contract features and patterns"""
        bytecode = contract.get('bytecode', '')
        abi = self._parse_abi(contract.get('abi'))
        
        analysis = {
            'bytecode_size': len(bytecode) // 2 if bytecode else 0,
            'has_constructor': False,
            'has_fallback': False,
            'has_receive': False,
            'function_count': 0,
            'event_count': 0,
            'has_payable_functions': False,
            'is_proxy': self._detect_proxy(bytecode, abi),
            'is_token': self._detect_token_standard(abi),
            'security_flags': self._analyze_security_features(abi)
        }
        
        if abi:
            analysis.update({
                'has_constructor': any(item.get('type') == 'constructor' for item in abi),
                'has_fallback': any(item.get('type') == 'fallback' for item in abi),
                'has_receive': any(item.get('type') == 'receive' for item in abi),
                'function_count': len([item for item in abi if item.get('type') == 'function']),
                'event_count': len([item for item in abi if item.get('type') == 'event']),
                'has_payable_functions': any(
                    item.get('type') == 'function' and item.get('stateMutability') == 'payable' 
                    for item in abi
                )
            })
        
        return analysis
    
    def _detect_proxy(self, bytecode: str, abi: Optional[List]) -> bool:
        """Detect if contract is a proxy"""
        if not bytecode:
            return False
        
        # Simplified proxy detection
        proxy_patterns = [
            '3660006000376110006000366000f3',  # Minimal proxy pattern
            'delegatecall'  # Contains delegate call
        ]
        
        return any(pattern.lower() in bytecode.lower() for pattern in proxy_patterns)
    
    def _detect_token_standard(self, abi: Optional[List]) -> Optional[str]:
        """Detect token standard (TRC20, TRC721, etc.)"""
        if not abi or not isinstance(abi, list):
            return None
        
        functions = [item.get('name') for item in abi if item.get('type') == 'function']
        events = [item.get('name') for item in abi if item.get('type') == 'event']
        
        # Check for TRC20 standard
        trc20_functions = ['totalSupply', 'balanceOf', 'transfer', 'transferFrom', 'approve', 'allowance']
        trc20_events = ['Transfer', 'Approval']
        
        has_trc20_functions = all(func in functions for func in trc20_functions)
        has_trc20_events = all(event in events for event in trc20_events)
        
        if has_trc20_functions and has_trc20_events:
            return 'TRC20'
        
        # Check for TRC721 standard
        trc721_functions = ['balanceOf', 'ownerOf', 'approve', 'getApproved', 'setApprovalForAll', 'isApprovedForAll', 'transferFrom', 'safeTransferFrom']
        has_trc721_functions = all(func in functions for func in trc721_functions)
        
        if has_trc721_functions:
            return 'TRC721'
        
        return None
    
    def _analyze_security_features(self, abi: Optional[List]) -> List[str]:
        """Analyze security features and patterns"""
        if not abi or not isinstance(abi, list):
            return []
        
        flags = []
        functions = [item for item in abi if item.get('type') == 'function']
        function_names = [func.get('name', '').lower() for func in functions]
        
        # Check for common security patterns
        if any('owner' in name for name in function_names):
            flags.append('Ownable')
        
        if any('pause' in name or 'emergency' in name for name in function_names):
            flags.append('Pausable')
        
        if any('upgrade' in name for name in function_names):
            flags.append('Upgradeable')
        
        if any('timelock' in name for name in function_names):
            flags.append('Timelock')
        
        return flags

class TronContractVerifier:
    def __init__(self, api_key: str):
        self.analyzer = TronContractAnalyzer(api_key)
    
    def verify_contract(self, contract_address: str, source_code: str, 
                       compiler_version: str, optimized: bool = False) -> Dict:
        """Verify contract against source code"""
        try:
            contract_info = self.analyzer.get_contract_info(contract_address)
            
            if not contract_info['exists']:
                return {
                    'verified': False,
                    'reason': 'Contract not found on blockchain'
                }
            
            # Simplified verification - in reality you'd compile the source
            verification = self._simulate_verification(
                contract_info['bytecode'],
                source_code,
                compiler_version,
                optimized
            )
            
            return {
                'verified': verification['matches'],
                'contract_info': contract_info,
                'verification': {
                    'source_bytecode_hash': verification['source_hash'],
                    'deployed_bytecode_hash': contract_info['code_hash'],
                    'matches': verification['matches'],
                    'compiler_version': compiler_version,
                    'optimized': optimized
                },
                'reason': 'Contract verified successfully' if verification['matches'] else 'Bytecode mismatch'
            }
            
        except Exception as e:
            return {
                'verified': False,
                'reason': f'Verification error: {str(e)}'
            }
    
    def _simulate_verification(self, deployed_bytecode: str, source_code: str, 
                              compiler_version: str, optimized: bool) -> Dict:
        """Simulate verification process"""
        # In reality, this would:
        # 1. Compile source code with specified compiler and settings
        # 2. Compare resulting bytecode with deployed bytecode
        # 3. Handle constructor arguments and library linking
        
        source_hash = hashlib.sha256(source_code.encode()).hexdigest()
        deployed_hash = hashlib.sha256(deployed_bytecode.encode()).hexdigest()
        
        return {
            'matches': False,  # Would be True if bytecode matches
            'source_hash': source_hash,
            'deployed_hash': deployed_hash
        }

# Usage examples
if __name__ == "__main__":
    analyzer = TronContractAnalyzer('YOUR_API_KEY')
    
    try:
        # USDT TRC20 contract
        usdt_contract = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'
        
        # Get contract information
        contract_info = analyzer.get_contract_info(usdt_contract)
        
        print("Contract Analysis:")
        print(f"  Name: {contract_info['name']}")
        print(f"  Exists: {contract_info['exists']}")
        print(f"  Verified: {contract_info['is_verified']}")
        print(f"  Token Standard: {contract_info['analysis']['is_token']}")
        print(f"  Function Count: {contract_info['analysis']['function_count']}")
        print(f"  Event Count: {contract_info['analysis']['event_count']}")
        print(f"  Bytecode Size: {contract_info['analysis']['bytecode_size']} bytes")
        print(f"  Security Features: {contract_info['analysis']['security_flags']}")
        
        # Show some functions
        if contract_info['functions']:
            print(f"\nSample Functions:")
            for func in contract_info['functions'][:5]:
                print(f"  {func['signature']} ({'view' if func['is_view'] else 'write'})")
        
        # Contract verification example
        verifier = TronContractVerifier('YOUR_API_KEY')
        verification = verifier.verify_contract(
            usdt_contract,
            "// Contract source code would go here",
            "v0.8.0",
            True
        )
        
        print(f"\nVerification Result: {verification['verified']}")
        print(f"Reason: {verification['reason']}")
        
    except Exception as e:
        print(f"Error: {e}")

Response Examples

Verified Contract (USDT)

JSON
{
  "bytecode": "608060405234801561001057600080fd5b50600436106101735760003560e01c80636a...",
  "name": "TetherToken",
  "abi": "[{\"inputs\":[{\"name\":\"_initialSupply\",\"type\":\"uint256\"}],\"name\":\"constructor\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"balance\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]",
  "origin_address": "TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh",
  "origin_energy_limit": 10000000,
  "contract_address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
  "code_hash": "a1b2c3d4e5f6789012345678901234567890123456789012345678901234567890"
}

Unverified Contract

JSON
{
  "bytecode": "608060405234801561001057600080fd5b506004361061017357600035...",
  "origin_address": "TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh",
  "origin_energy_limit": 5000000,
  "contract_address": "TAbCdEfGhIjKlMnOpQrStUvWxYz123456789",
  "code_hash": "b2c3d4e5f6789012345678901234567890123456789012345678901234567890a1"
}

Contract Not Found

JSON
{}

Common Use Cases

1. Contract Explorer

JavaScript
class TronContractExplorer {
  constructor(apiKey) {
    this.analyzer = new TronContractAnalyzer(apiKey);
  }
  
  async exploreContract(contractAddress) {
    try {
      const contractInfo = await this.analyzer.getContractInfo(contractAddress);
      
      if (!contractInfo.exists) {
        return { error: 'Contract not found' };
      }
      
      return {
        basicInfo: {
          address: contractInfo.address,
          name: contractInfo.name,
          creator: contractInfo.creator,
          isVerified: contractInfo.isVerified,
          standard: contractInfo.analysis.isToken
        },
        codeInfo: {
          bytecodeSize: contractInfo.analysis.bytecodeSize,
          codeHash: contractInfo.codeHash,
          hasProxy: contractInfo.analysis.isProxy
        },
        interface: {
          functionCount: contractInfo.analysis.functionCount,
          eventCount: contractInfo.analysis.eventCount,
          viewFunctions: contractInfo.functions.filter(f => f.isView).length,
          writeFunctions: contractInfo.functions.filter(f => !f.isView).length,
          payableFunctions: contractInfo.functions.filter(f => f.isPayable).length
        },
        security: {
          features: contractInfo.analysis.securityFlags,
          hasPayableFunctions: contractInfo.analysis.hasPayableFunctions,
          hasConstructor: contractInfo.analysis.hasConstructor
        }
      };
    } catch (error) {
      return { error: error.message };
    }
  }
}

Performance Tips

  1. Cache Contract Data - Contract information rarely changes, cache for hours
  2. Batch Requests - Check multiple contracts efficiently
  3. ABI Parsing - Parse and cache ABI data for reuse
  4. Selective Loading - Only fetch detailed analysis when needed

Need help? Contact our support team or check the TRON documentation.