⚠️Blast API (blastapi.io) ends Oct 31. Migrate to Dwellir and skip Alchemy's expensive compute units.
Switch Today →
Skip to main content

wallet/getcontract

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
{
"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

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

Response Examples

Verified Contract (USDT)

{
"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

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

Contract Not Found

{}

Common Use Cases

1. Contract Explorer

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.