wallet/getaccountbalance
Lightning-Fast Balance Queries
Dwellir's TRON nodes return balance information in under 30ms with real-time synchronization. Get account balances with block height confirmation for accurate balance tracking.
Retrieve the balance of a TRON account including TRX and all token holdings with the specific block height at which the balance was calculated.
Use Cases
wallet/getaccountbalance
is perfect for:
- Wallet Applications - Display real-time balance updates
- Exchange Integration - Track deposit confirmations
- Portfolio Trackers - Monitor multiple asset balances
- Payment Verification - Confirm payment receipt at specific block
- Audit Systems - Historical balance verification
Parameters
Parameter | Type | Required | Description |
---|---|---|---|
account_identifier | object | Yes | Account identification object |
account_identifier.address | string | Yes | TRON address (Base58 or Hex) |
block_identifier | object | No | Specific block for balance query |
block_identifier.hash | string | No | Block hash |
block_identifier.number | number | No | Block height |
visible | boolean | No | Use Base58 format (default: true) |
Request Example
{
"account_identifier": {
"address": "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN"
},
"block_identifier": {
"number": 58234567
},
"visible": true
}
Response Fields
Field | Type | Description |
---|---|---|
balance | number | TRX balance in SUN (1 TRX = 1,000,000 SUN) |
block_identifier | object | Block at which balance was calculated |
block_identifier.hash | string | Block hash |
block_identifier.number | number | Block height |
trc10 | array | TRC10 token balances |
trc20 | array | TRC20 token balances (requires indexing) |
Implementation Examples
- JavaScript
- Python
- cURL
const TRON_API = 'https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY';
// Get current balance
async function getAccountBalance(address) {
const response = await fetch(`${TRON_API}/wallet/getaccountbalance`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
account_identifier: {
address: address
},
visible: true
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
}
// Get balance at specific block
async function getBalanceAtBlock(address, blockNumber) {
const response = await fetch(`${TRON_API}/wallet/getaccountbalance`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
account_identifier: {
address: address
},
block_identifier: {
number: blockNumber
},
visible: true
})
});
return await response.json();
}
// Comprehensive balance tracker
class BalanceTracker {
constructor(apiKey) {
this.apiUrl = `https://api-tron-mainnet.n.dwellir.com/${apiKey}`;
}
async getFullBalance(address) {
try {
const balance = await this.getBalance(address);
return {
trx: {
amount: balance.balance / 1_000_000,
sun: balance.balance
},
block: {
height: balance.block_identifier.number,
hash: balance.block_identifier.hash
},
trc10: this.formatTokenBalances(balance.trc10 || []),
trc20: this.formatTokenBalances(balance.trc20 || []),
timestamp: new Date().toISOString()
};
} catch (error) {
console.error('Balance fetch error:', error);
throw error;
}
}
async getBalance(address) {
const response = await fetch(`${this.apiUrl}/wallet/getaccountbalance`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
account_identifier: { address },
visible: true
})
});
if (!response.ok) {
throw new Error(`Balance query failed: ${response.statusText}`);
}
return await response.json();
}
formatTokenBalances(tokens) {
return tokens.map(token => ({
id: token.key || token.contract_address,
balance: token.value,
name: token.name || 'Unknown Token'
}));
}
async compareBalances(address, blockNumbers) {
const balances = await Promise.all(
blockNumbers.map(block => this.getBalanceAtBlock(address, block))
);
return balances.map((balance, index) => ({
block: blockNumbers[index],
trx: balance.balance / 1_000_000,
tokenCount: (balance.trc10?.length || 0) + (balance.trc20?.length || 0)
}));
}
async getBalanceAtBlock(address, blockNumber) {
const response = await fetch(`${this.apiUrl}/wallet/getaccountbalance`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
account_identifier: { address },
block_identifier: { number: blockNumber },
visible: true
})
});
return await response.json();
}
}
// Usage examples
(async () => {
const tracker = new BalanceTracker('YOUR_API_KEY');
try {
// Get current balance
const balance = await tracker.getFullBalance('TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN');
console.log(`Current balance: ${balance.trx.amount} TRX at block ${balance.block.height}`);
// Compare historical balances
const history = await tracker.compareBalances(
'TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN',
[58234567, 58234568, 58234569]
);
console.log('Balance history:', history);
} catch (error) {
console.error('Error:', error);
}
})();
import requests
import json
from typing import Dict, List, Optional, Union
from datetime import datetime
class TronBalanceClient:
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_balance(
self,
address: str,
block_number: Optional[int] = None,
block_hash: Optional[str] = None,
visible: bool = True
) -> Dict:
"""
Get account balance at current or specific block
"""
url = f"{self.base_url}/wallet/getaccountbalance"
payload = {
"account_identifier": {
"address": address
},
"visible": visible
}
# Add block identifier if specified
if block_number or block_hash:
payload["block_identifier"] = {}
if block_number:
payload["block_identifier"]["number"] = block_number
if block_hash:
payload["block_identifier"]["hash"] = block_hash
response = requests.post(url, headers=self.headers, json=payload)
response.raise_for_status()
return response.json()
def get_formatted_balance(self, address: str) -> Dict:
"""
Get formatted balance with TRX conversion
"""
try:
balance_data = self.get_account_balance(address)
return {
'address': address,
'trx': {
'amount': balance_data.get('balance', 0) / 1_000_000,
'sun': balance_data.get('balance', 0)
},
'block': {
'height': balance_data.get('block_identifier', {}).get('number'),
'hash': balance_data.get('block_identifier', {}).get('hash')
},
'trc10_tokens': self._format_tokens(balance_data.get('trc10', [])),
'trc20_tokens': self._format_tokens(balance_data.get('trc20', [])),
'query_time': datetime.now().isoformat()
}
except requests.RequestException as e:
print(f"Error fetching balance: {e}")
raise
def _format_tokens(self, tokens: List[Dict]) -> List[Dict]:
"""
Format token balances for display
"""
formatted = []
for token in tokens:
formatted.append({
'id': token.get('key') or token.get('contract_address'),
'balance': token.get('value', 0),
'name': token.get('name', 'Unknown')
})
return formatted
def get_balance_history(
self,
address: str,
block_numbers: List[int]
) -> List[Dict]:
"""
Get balance at multiple block heights
"""
history = []
for block_num in block_numbers:
try:
balance = self.get_account_balance(
address=address,
block_number=block_num
)
history.append({
'block': block_num,
'trx_balance': balance.get('balance', 0) / 1_000_000,
'sun_balance': balance.get('balance', 0),
'token_count': len(balance.get('trc10', [])) + len(balance.get('trc20', []))
})
except Exception as e:
history.append({
'block': block_num,
'error': str(e)
})
return history
def monitor_balance_changes(
self,
address: str,
previous_balance: Optional[int] = None
) -> Dict:
"""
Monitor balance changes between calls
"""
current = self.get_formatted_balance(address)
if previous_balance is not None:
change = current['trx']['sun'] - previous_balance
current['change'] = {
'sun': change,
'trx': change / 1_000_000,
'percentage': (change / previous_balance * 100) if previous_balance > 0 else 0
}
return current
def get_multi_account_balances(self, addresses: List[str]) -> List[Dict]:
"""
Get balances for multiple accounts
"""
balances = []
for address in addresses:
try:
balance = self.get_formatted_balance(address)
balances.append({
'success': True,
'data': balance
})
except Exception as e:
balances.append({
'success': False,
'address': address,
'error': str(e)
})
return balances
# Usage examples
if __name__ == "__main__":
client = TronBalanceClient('YOUR_API_KEY')
try:
# Get current balance
balance = client.get_formatted_balance('TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN')
print(f"Current balance: {balance['trx']['amount']} TRX")
print(f"Block height: {balance['block']['height']}")
# Get balance at specific block
historical = client.get_account_balance(
address='TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN',
block_number=58234567
)
print(f"Balance at block 58234567: {historical['balance'] / 1_000_000} TRX")
# Get balance history
history = client.get_balance_history(
'TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN',
[58234565, 58234566, 58234567]
)
for entry in history:
print(f"Block {entry['block']}: {entry.get('trx_balance', 'Error')} TRX")
# Monitor multiple accounts
addresses = [
'TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN',
'TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh'
]
multi_balances = client.get_multi_account_balances(addresses)
for result in multi_balances:
if result['success']:
addr = result['data']['address']
bal = result['data']['trx']['amount']
print(f"{addr}: {bal} TRX")
else:
print(f"Error for {result['address']}: {result['error']}")
except Exception as e:
print(f"Error: {e}")
# Get current account balance
curl -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getaccountbalance" \
-H "Content-Type: application/json" \
-d '{
"account_identifier": {
"address": "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN"
},
"visible": true
}'
# Get balance at specific block height
curl -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getaccountbalance" \
-H "Content-Type: application/json" \
-d '{
"account_identifier": {
"address": "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN"
},
"block_identifier": {
"number": 58234567
},
"visible": true
}'
# Get balance with hex address format
curl -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getaccountbalance" \
-H "Content-Type: application/json" \
-d '{
"account_identifier": {
"address": "41E552F6487585C2B58BC2C9BB4492BC1F17132CD0"
},
"visible": false
}'
# Parse balance with jq
curl -s -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getaccountbalance" \
-H "Content-Type: application/json" \
-d '{
"account_identifier": {
"address": "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN"
},
"visible": true
}' | jq '{
trx_balance: (.balance // 0) / 1000000,
sun_balance: .balance // 0,
block_height: .block_identifier.number,
block_hash: .block_identifier.hash,
trc10_count: (.trc10 // [] | length),
trc20_count: (.trc20 // [] | length)
}'
Response Examples
Successful Response
{
"balance": 15000000000,
"block_identifier": {
"hash": "0000000003787ac74d9bb8f8c9c59ac3f3e3b9b8c9e3e8f9c8d7e8f9c8d7e8f9",
"number": 58234567
},
"trc10": [
{
"key": "1002000",
"value": 50000000
}
],
"trc20": [
{
"contract_address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
"value": "100000000",
"name": "USDT",
"symbol": "USDT",
"decimals": 6
}
]
}
Empty Account Response
{
"balance": 0,
"block_identifier": {
"hash": "0000000003787ac74d9bb8f8c9c59ac3f3e3b9b8c9e3e8f9c8d7e8f9c8d7e8f9",
"number": 58234567
},
"trc10": [],
"trc20": []
}
Common Use Cases
1. Real-Time Balance Display
async function displayBalance(address) {
const balance = await getAccountBalance(address);
return {
display: `${(balance.balance / 1_000_000).toFixed(6)} TRX`,
blockHeight: balance.block_identifier.number,
tokens: [
...(balance.trc10 || []).map(t => ({ type: 'TRC10', ...t })),
...(balance.trc20 || []).map(t => ({ type: 'TRC20', ...t }))
]
};
}
2. Payment Confirmation
async function confirmPayment(address, expectedAmount, minConfirmations = 19) {
const balance = await getAccountBalance(address);
const currentBlock = balance.block_identifier.number;
// Check if payment received
const received = balance.balance >= expectedAmount;
// Get latest block to check confirmations
const latestBlock = await getLatestBlock();
const confirmations = latestBlock.number - currentBlock;
return {
received,
amount: balance.balance,
confirmations,
confirmed: received && confirmations >= minConfirmations
};
}
3. Balance Change Detection
class BalanceMonitor {
constructor(apiKey, address) {
this.apiKey = apiKey;
this.address = address;
this.lastBalance = null;
}
async checkForChanges() {
const current = await getAccountBalance(this.address);
if (this.lastBalance === null) {
this.lastBalance = current.balance;
return { changed: false, balance: current.balance };
}
const changed = current.balance !== this.lastBalance;
const difference = current.balance - this.lastBalance;
this.lastBalance = current.balance;
return {
changed,
balance: current.balance,
difference,
direction: difference > 0 ? 'received' : 'sent',
amount: Math.abs(difference) / 1_000_000
};
}
}
Error Handling
Error Code | Description | Solution |
---|---|---|
400 | Invalid address format | Verify address is valid Base58 or Hex |
404 | Block not found | Check block number exists |
429 | Rate limit exceeded | Implement backoff strategy |
500 | Internal server error | Retry with exponential backoff |
async function safeGetBalance(address, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
return await getAccountBalance(address);
} catch (error) {
if (i === retries - 1) throw error;
// Exponential backoff
await new Promise(resolve =>
setTimeout(resolve, Math.pow(2, i) * 1000)
);
}
}
}
Best Practices
- Cache Results - Balance queries can be cached for 3 seconds
- Batch Requests - Query multiple accounts in parallel
- Monitor Changes - Use block height to detect balance changes
- Handle Errors - Implement proper error handling and retries
- Validate Addresses - Check address format before querying
Related Methods
- wallet/getaccount - Get detailed account information
- wallet/getaccountresource - Get resource details
- wallet/validateaddress - Validate address format
- wallet/getaccountnet - Get bandwidth usage
Need help? Contact support or check our TRON documentation.