# wallet/getcontractinfo - Get Contract Details

Get detailed information about a deployed smart contract.

## Endpoint

```
POST /wallet/getcontractinfo
```

## Request Parameters

- `value` (`string, required`): Required parameter: Contract address (base58 or hex)
- `visible` (`boolean, required`): Optional parameter: Return base58 addresses (default: false returns hex)

## Request Example

```bash
# Get contract info with visible address
    curl -X POST https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getcontractinfo \
      -H "Content-Type: application/json" \
      -d '{
        "value": "TContractAddress...",
        "visible": true
      }'

    # Get contract info with hex address
    curl -X POST https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getcontractinfo \
      -H "Content-Type: application/json" \
      -d '{
        "value": "41a614f803b6fd780986a42c78ec9c7f77e6ded13c"
      }'

    # Extract ABI using jq
    curl -X POST https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getcontractinfo \
      -H "Content-Type: application/json" \
      -d '{
        "value": "TContractAddress...",
        "visible": true
      }' | jq '.abi.entrys[] | select(.type == "Function") | .name'
```

## Response Fields

- `result` (`OBJECT, required`): `contract_address` - Contract address `contract_name` - Contract name `abi` - Contract ABI (Application Binary Interface) `entrys` - Array of contract functions and events `bytecode` - Compiled contract bytecode `consumed_energy` - Total energy consumed by contract `origin_energy_limit` - Original energy limit `origin_address` - Contract creator address `trx_hash` - Transaction hash of contract creation

## Successful Response

```json
{
  "contract_address": "TContractAddress...",
  "contract_name": "MyToken",
  "abi": {
    "entrys": [
      {
        "name": "transfer",
        "inputs": [
          {
            "name": "to",
            "type": "address"
          },
          {
            "name": "amount",
            "type": "uint256"
          }
        ],
        "outputs": [
          {
            "type": "bool"
          }
        ],
        "type": "Function",
        "stateMutability": "nonpayable"
      },
      {
        "name": "Transfer",
        "inputs": [
          {
            "indexed": true,
            "name": "from",
            "type": "address"
          },
          {
            "indexed": true,
            "name": "to",
            "type": "address"
          },
          {
            "indexed": false,
            "name": "value",
            "type": "uint256"
          }
        ],
        "type": "Event"
      },
      {
        "name": "balanceOf",
        "inputs": [
          {
            "name": "account",
            "type": "address"
          }
        ],
        "outputs": [
          {
            "type": "uint256"
          }
        ],
        "type": "Function",
        "stateMutability": "view"
      }
    ]
  },
  "bytecode": "608060405234801561001057600080fd5b50...",
  "consumed_energy": 125430000,
  "origin_energy_limit": 10000000,
  "origin_address": "TCreatorAddress...",
  "trx_hash": "7c2d4206c03a883dd9066d6c839d0deaef32dc5a0d9b15f6d06e506906c90332"
}
```

## Implementation Examples

cURL
JavaScript
Python

```bash
# Get contract info with visible address
curl -X POST https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getcontractinfo \
  -H "Content-Type: application/json" \
  -d '{
    "value": "TContractAddress...",
    "visible": true
  }'

# Get contract info with hex address
curl -X POST https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getcontractinfo \
  -H "Content-Type: application/json" \
  -d '{
    "value": "41a614f803b6fd780986a42c78ec9c7f77e6ded13c"
  }'

# Extract ABI using jq
curl -X POST https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getcontractinfo \
  -H "Content-Type: application/json" \
  -d '{
    "value": "TContractAddress...",
    "visible": true
  }' | jq '.abi.entrys[] | select(.type == "Function") | .name'
```

```javascript
// Get contract information
const response = await fetch('https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getcontractinfo', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    value: 'TContractAddress...',
    visible: true
  }),
});

const contract = await response.json();

// Parse ABI
if (contract.abi && contract.abi.entrys) {
  console.log('Contract Functions:');
  contract.abi.entrys.forEach(entry => {
    if (entry.type === 'Function') {
      const inputs = entry.inputs ? entry.inputs.map(i => `${i.type} ${i.name}`).join(', ') : '';
      const outputs = entry.outputs ? entry.outputs.map(o => o.type).join(', ') : 'void';
      console.log(`  ${entry.name}(${inputs}) returns (${outputs})`);
    }
  });
  
  console.log('\nContract Events:');
  contract.abi.entrys.forEach(entry => {
    if (entry.type === 'Event') {
      const params = entry.inputs ? entry.inputs.map(i => `${i.type} ${i.indexed ? 'indexed ' : ''}${i.name}`).join(', ') : '';
      console.log(`  ${entry.name}(${params})`);
    }
  });
}

// Display contract stats
console.log('\nContract Statistics:');
console.log(`Creator: ${contract.origin_address}`);
console.log(`Energy Consumed: ${contract.consumed_energy}`);
console.log(`Creation TX: ${contract.trx_hash}`);
```

```python
import requests
import json

url = "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getcontractinfo"

payload = {
    "value": "TContractAddress...",
    "visible": True
}

response = requests.post(url, json=payload)
contract = response.json()

# Check if contract exists
if 'Error' in contract:
    print(f"Contract not found: {contract['Error']}")
else:
    print(f"Contract: {contract.get('contract_name', 'Unknown')}")
    print(f"Address: {contract.get('contract_address', '')}")
    print(f"Creator: {contract.get('origin_address', '')}")
    
    # Parse ABI
    if 'abi' in contract and 'entrys' in contract['abi']:
        functions = [e for e in contract['abi']['entrys'] if e.get('type') == 'Function']
        events = [e for e in contract['abi']['entrys'] if e.get('type') == 'Event']
        
        print(f"\nFunctions ({len(functions)}):")
        for func in functions:
            inputs = ', '.join([f"{i['type']} {i['name']}" for i in func.get('inputs', [])])
            outputs = ', '.join([o['type'] for o in func.get('outputs', [])])
            print(f"  - {func['name']}({inputs})")
            if outputs:
                print(f"    Returns: {outputs}")
        
        print(f"\nEvents ({len(events)}):")
        for event in events:
            params = ', '.join([
                f"{'indexed ' if i.get('indexed') else ''}{i['type']} {i['name']}" 
                for i in event.get('inputs', [])
            ])
            print(f"  - {event['name']}({params})")
    
    # Display energy consumption
    if 'consumed_energy' in contract:
        energy_in_trx = contract['consumed_energy'] * 420 / 1_000_000  # Energy price ~420 SUN
        print(f"\nTotal Energy Consumed: {contract['consumed_energy']:,}")
        print(f"Estimated Cost: {energy_in_trx:.2f} TRX")
```

## ABI Entry Types

### Function Entry

```json
{
  "name": "functionName",
  "inputs": [...],
  "outputs": [...],
  "type": "Function",
  "stateMutability": "view|pure|nonpayable|payable"
}
```

### Event Entry

```json
{
  "name": "EventName",
  "inputs": [
    {
      "indexed": true,
      "name": "param1",
      "type": "address"
    }
  ],
  "type": "Event"
}
```

### Constructor Entry

```json
{
  "inputs": [...],
  "type": "Constructor",
  "stateMutability": "nonpayable"
}
```

## Contract Verification

```javascript
// Verify contract source code matches deployed bytecode
async function verifyContract(address, sourceCode, compilerVersion) {
  // Get deployed contract info
  const response = await fetch(`${API_URL}/wallet/getcontractinfo`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ value: address, visible: true })
  });
  
  const contract = await response.json();
  const deployedBytecode = contract.bytecode;
  
  // Compile source code (pseudo-code)
  const compiledBytecode = await compileContract(sourceCode, compilerVersion);
  
  // Compare bytecodes (excluding metadata)
  const verified = compareBytecode(deployedBytecode, compiledBytecode);
  
  return {
    verified,
    contractName: contract.contract_name,
    abi: contract.abi,
    creator: contract.origin_address
  };
}
```

## Best Practices

### 1. **Cache Contract Info**

- ABI doesn't change after deployment
- Cache to reduce API calls
- Update cache only when needed

### 2. **Validate Contracts**

- Check bytecode exists
- Verify ABI structure
- Confirm expected functions present

### 3. **Energy Monitoring**

- Track consumed\_energy growth
- Monitor for unusual consumption
- Alert on high energy usage

## Common Errors

| Error                                            | Description               | Solution                  |
| ------------------------------------------------ | ------------------------- | ------------------------- |
| `Contract does not exist`                        | Invalid contract address  | Verify address is correct |
| `Not a smart contract address`                   | Address is not a contract | Check address type first  |
| `class org.tron.core.exception.BadItemException` | Malformed request         | Check parameter format    |

## Use Cases

- **Contract Verification**: Verify deployed contract matches source
- **ABI Extraction**: Get contract interface for interaction
- **DApp Integration**: Load contract details dynamically
- **Analytics**: Track contract usage and energy consumption
- **Security Auditing**: Analyze contract bytecode and functions

## Related Methods

- [wallet/triggersmartcontract](https://www.dwellir.com/docs/tron/wallet-triggersmartcontract) - Call contract function
- [wallet/triggerconstantcontract](https://www.dwellir.com/docs/tron/wallet-triggerconstantcontract) - Call view function
- [wallet/estimateenergy](https://www.dwellir.com/docs/tron/wallet-estimateenergy) - Estimate energy for call
