wallet/getaccount
Ultra-Fast Account Queries
Dwellir's TRON endpoints deliver account information in under 50ms with 99.9% uptime. Get comprehensive account data including balance, resources, and token holdings instantly.
Get comprehensive information about a TRON account including TRX balance, bandwidth, energy, TRC20 tokens, and account permissions.
When to Use This Method
wallet/getaccount
is essential for:
- Balance Checks - Display TRX balance in wallets and apps
- Resource Monitoring - Track bandwidth and energy consumption
- Token Holdings - View all TRC20/TRC721 tokens owned
- Account Validation - Verify account exists and activation status
- Permission Analysis - Check multi-signature and account permissions
Parameters
-
address -
string
(required)- TRON address in Base58 format (starts with 'T')
- Example:
"TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN"
-
visible -
boolean
(optional, default: false)true
- Use Base58 address formatfalse
- Use hex address format
{
"address": "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN",
"visible": true
}
Returns
Account Object containing:
address
- Account addressbalance
- TRX balance in SUN (1 TRX = 1,000,000 SUN)create_time
- Account creation timestamplatest_operation_time
- Last activity timestampaccount_resource
- Bandwidth and energy informationasset
- TRC10 token holdingsassetV2
- TRC20 token holdingsowner_permission
- Account permissionsactive_permission
- Active permissions for operations
Implementation Examples
- JavaScript
- Python
- cURL
const TRON_API = 'https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY';
// Get account information
async function getAccount(address) {
const response = await fetch(`${TRON_API}/wallet/getaccount`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
address: address,
visible: true
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
}
// Enhanced account info with formatted data
async function getAccountInfo(address) {
try {
const account = await getAccount(address);
// Check if account exists
if (!account.address) {
return {
exists: false,
message: 'Account not found or not activated'
};
}
return {
exists: true,
address: account.address,
balance: {
trx: (account.balance || 0) / 1_000_000, // Convert SUN to TRX
sun: account.balance || 0
},
resources: {
bandwidth: account.net_limit || 0,
energy: account.energy_limit || 0,
freeNetUsed: account.free_net_used || 0,
freeNetLimit: account.free_net_limit || 0
},
tokens: account.assetV2 || [],
permissions: {
owner: account.owner_permission,
active: account.active_permission
},
timestamps: {
created: account.create_time,
lastActive: account.latest_operation_time
}
};
} catch (error) {
console.error('Error fetching account:', error);
throw error;
}
}
// Check multiple accounts
async function checkMultipleAccounts(addresses) {
const results = await Promise.allSettled(
addresses.map(addr => getAccountInfo(addr))
);
return results.map((result, index) => ({
address: addresses[index],
success: result.status === 'fulfilled',
data: result.status === 'fulfilled' ? result.value : null,
error: result.status === 'rejected' ? result.reason.message : null
}));
}
// Usage examples
(async () => {
try {
// Single account query
const account = await getAccountInfo('TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN');
console.log('Account balance:', account.balance.trx, 'TRX');
// Multiple accounts
const addresses = [
'TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN',
'TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh'
];
const results = await checkMultipleAccounts(addresses);
console.log('Multiple accounts:', results);
} catch (error) {
console.error('Error:', error);
}
})();
import requests
import json
from typing import Dict, List, Optional
class TronAccountClient:
def __init__(self, api_key: str):
self.base_url = f"https://api-tron-mainnet.n.dwellir.com/{api_key}"
self.headers = {
'Content-Type': 'application/json'
}
def get_account(self, address: str, visible: bool = True) -> Dict:
"""Get raw account information from TRON network"""
url = f"{self.base_url}/wallet/getaccount"
payload = {
"address": address,
"visible": visible
}
response = requests.post(url, headers=self.headers, json=payload)
response.raise_for_status()
return response.json()
def get_account_info(self, address: str) -> Dict:
"""Get formatted account information"""
try:
account = self.get_account(address)
# Check if account exists
if not account.get('address'):
return {
'exists': False,
'message': 'Account not found or not activated'
}
return {
'exists': True,
'address': account['address'],
'balance': {
'trx': (account.get('balance', 0)) / 1_000_000, # Convert SUN to TRX
'sun': account.get('balance', 0)
},
'resources': {
'bandwidth': account.get('net_limit', 0),
'energy': account.get('energy_limit', 0),
'free_net_used': account.get('free_net_used', 0),
'free_net_limit': account.get('free_net_limit', 0)
},
'tokens': account.get('assetV2', []),
'permissions': {
'owner': account.get('owner_permission'),
'active': account.get('active_permission')
},
'timestamps': {
'created': account.get('create_time'),
'last_active': account.get('latest_operation_time')
}
}
except requests.RequestException as e:
print(f"Error fetching account: {e}")
raise
def check_multiple_accounts(self, addresses: List[str]) -> List[Dict]:
"""Check multiple accounts efficiently"""
results = []
for address in addresses:
try:
account_info = self.get_account_info(address)
results.append({
'address': address,
'success': True,
'data': account_info,
'error': None
})
except Exception as e:
results.append({
'address': address,
'success': False,
'data': None,
'error': str(e)
})
return results
def get_balance_in_trx(self, address: str) -> float:
"""Get account balance in TRX (simplified)"""
account = self.get_account(address)
return (account.get('balance', 0)) / 1_000_000
# Usage examples
if __name__ == "__main__":
client = TronAccountClient('YOUR_API_KEY')
try:
# Single account query
account = client.get_account_info('TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN')
print(f"Account balance: {account['balance']['trx']} TRX")
# Multiple accounts
addresses = [
'TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN',
'TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh'
]
results = client.check_multiple_accounts(addresses)
for result in results:
if result['success']:
print(f"{result['address']}: {result['data']['balance']['trx']} TRX")
else:
print(f"{result['address']}: Error - {result['error']}")
except Exception as e:
print(f"Error: {e}")
# Basic account query
curl -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getaccount" \
-H "Content-Type: application/json" \
-d '{
"address": "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN",
"visible": true
}'
# Query with hex address format
curl -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getaccount" \
-H "Content-Type: application/json" \
-d '{
"address": "41E552F6487585C2B58BC2C9BB4492BC1F17132CD0",
"visible": false
}'
# Using jq to parse response
curl -s -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getaccount" \
-H "Content-Type: application/json" \
-d '{
"address": "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN",
"visible": true
}' | jq '{
address: .address,
balance_trx: (.balance // 0) / 1000000,
balance_sun: .balance // 0,
free_bandwidth: .free_net_limit // 0,
used_bandwidth: .free_net_used // 0
}'
Response Examples
Successful Response (Active Account)
{
"address": "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN",
"balance": 1500000000,
"create_time": 1547736132000,
"latest_operation_time": 1734567890000,
"free_net_usage": 0,
"free_net_limit": 5000,
"net_limit": 10000,
"net_usage": 1234,
"energy_limit": 50000,
"energy_usage": 5000,
"assetV2": [
{
"key": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
"value": 100000000
}
],
"owner_permission": {
"type": 0,
"id": 0,
"permission_name": "owner",
"threshold": 1,
"keys": [
{
"address": "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN",
"weight": 1
}
]
},
"active_permission": [
{
"type": 2,
"id": 2,
"permission_name": "active0",
"threshold": 1,
"operations": "7fff1fc0037e0000000000000000000000000000000000000000000000000000",
"keys": [
{
"address": "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN",
"weight": 1
}
]
}
]
}
Empty Response (Non-existent Account)
{}
Common Use Cases
1. Wallet Balance Display
async function getWalletBalance(address) {
const account = await getAccountInfo(address);
if (!account.exists) {
return {
status: 'inactive',
balance: 0,
message: 'Account not activated. Send TRX to activate.'
};
}
return {
status: 'active',
balance: account.balance.trx,
freeTransactions: account.resources.freeNetLimit - account.resources.freeNetUsed,
lastActive: new Date(account.timestamps.lastActive).toLocaleString()
};
}
2. Account Validation
async function validateTronAddress(address) {
// Basic format validation
if (!address.startsWith('T') || address.length !== 34) {
return { valid: false, reason: 'Invalid address format' };
}
try {
const account = await getAccount(address);
return {
valid: true,
exists: !!account.address,
activated: !!account.balance || account.balance === 0
};
} catch (error) {
return { valid: false, reason: 'Address lookup failed' };
}
}
3. Resource Monitoring Dashboard
async function getResourceStatus(address) {
const account = await getAccountInfo(address);
if (!account.exists) {
return { error: 'Account not found' };
}
const bandwidthUsage = (account.resources.freeNetUsed / account.resources.freeNetLimit) * 100;
const energyUsage = account.resources.energy > 0
? (account.resources.energyUsed / account.resources.energy) * 100
: 0;
return {
bandwidth: {
used: account.resources.freeNetUsed,
limit: account.resources.freeNetLimit,
usage_percent: bandwidthUsage.toFixed(2),
status: bandwidthUsage > 80 ? 'high' : bandwidthUsage > 50 ? 'medium' : 'low'
},
energy: {
used: account.resources.energyUsed || 0,
limit: account.resources.energy,
usage_percent: energyUsage.toFixed(2),
status: energyUsage > 80 ? 'high' : energyUsage > 50 ? 'medium' : 'low'
},
recommendations: generateResourceRecommendations(bandwidthUsage, energyUsage)
};
}
function generateResourceRecommendations(bandwidthUsage, energyUsage) {
const recommendations = [];
if (bandwidthUsage > 80) {
recommendations.push('Consider freezing TRX for bandwidth');
}
if (energyUsage > 80) {
recommendations.push('Freeze TRX for energy or rent energy');
}
if (bandwidthUsage < 20 && energyUsage < 20) {
recommendations.push('Resources are well managed');
}
return recommendations;
}
4. Multi-Signature Account Analysis
async function analyzeAccountPermissions(address) {
const account = await getAccount(address);
if (!account.address) {
return { error: 'Account not found' };
}
const isMultiSig = account.owner_permission?.threshold > 1 ||
account.active_permission?.some(p => p.threshold > 1);
return {
address: account.address,
isMultiSignature: isMultiSig,
ownerPermission: {
threshold: account.owner_permission?.threshold || 1,
keyCount: account.owner_permission?.keys?.length || 1
},
activePermissions: account.active_permission?.map(p => ({
id: p.id,
name: p.permission_name,
threshold: p.threshold,
keyCount: p.keys?.length || 0
})) || []
};
}
Error Handling
Error Type | Description | Solution |
---|---|---|
Invalid Address | Malformed TRON address | Validate address format before calling |
Network Error | RPC connection failed | Implement retry logic with exponential backoff |
Empty Response | Account doesn't exist | Handle as non-activated account |
async function safeGetAccount(address, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
const account = await getAccount(address);
return { success: true, data: account };
} catch (error) {
if (i === retries - 1) {
return {
success: false,
error: error.message,
isNetworkError: error.name === 'TypeError' || error.code === 'NETWORK_ERROR'
};
}
// Exponential backoff
await new Promise(resolve => setTimeout(resolve, Math.pow(2, i) * 1000));
}
}
}
Performance Tips
- Batch Requests - Query multiple accounts concurrently but respect rate limits
- Cache Results - Cache account data for 30-60 seconds to reduce API calls
- Selective Queries - Only fetch account data when needed, not on every page load
- Error Boundaries - Implement proper error handling for non-existent accounts
// Simple caching example
class AccountCache {
constructor(ttl = 60000) { // 1 minute TTL
this.cache = new Map();
this.ttl = ttl;
}
async get(address) {
const cached = this.cache.get(address);
if (cached && Date.now() - cached.timestamp < this.ttl) {
return cached.data;
}
const account = await getAccountInfo(address);
this.cache.set(address, {
data: account,
timestamp: Date.now()
});
return account;
}
}
Need help? Contact our support team or check the TRON documentation.