wallet/getaccountresource
Optimize Transaction Costs
Dwellir's TRON endpoints help you monitor and optimize bandwidth/energy usage for zero-fee transactions. Track resources in real-time to minimize transaction costs on TRON.
Retrieves detailed information about an account's bandwidth and energy resources on the TRON network. Essential for managing transaction costs and optimizing resource usage.
When to Use This Method
wallet/getaccountresource
is essential for:
- Resource Monitoring - Track bandwidth and energy consumption
- Fee Optimization - Determine if transactions will be free or require TRX
- Staking Strategy - Plan TRX staking for bandwidth/energy
- Transaction Planning - Estimate resource requirements
- Wallet Management - Display resource status to users
Parameters
-
address -
string
(required)- TRON address in Base58 format
- Example:
"TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN"
-
visible -
boolean
(optional, default: false)true
- Use Base58 address formatfalse
- Use hex address format
{
"address": "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN",
"visible": true
}
Returns
Resource Object containing:
freeNetLimit
- Daily free bandwidth limit (5000 for new accounts)freeNetUsed
- Free bandwidth consumed todayNetLimit
- Additional bandwidth from frozen TRXNetUsed
- Additional bandwidth consumedEnergyLimit
- Energy from frozen TRXEnergyUsed
- Energy consumedtronPowerLimit
- Voting power from staked TRXassetNetLimit
- Token-specific bandwidth limitsassetNetUsed
- Token-specific bandwidth usage
Implementation Examples
- JavaScript
- Python
- cURL
const TRON_API = 'https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY';
// Get account resources
async function getAccountResource(address) {
const response = await fetch(`${TRON_API}/wallet/getaccountresource`, {
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 resource analyzer
class TronResourceAnalyzer {
constructor(apiKey) {
this.apiKey = apiKey;
this.apiUrl = `https://api-tron-mainnet.n.dwellir.com/${apiKey}`;
}
async getResourceStatus(address) {
try {
const resource = await this.getAccountResource(address);
// Calculate bandwidth status
const freeBandwidthTotal = resource.freeNetLimit || 0;
const freeBandwidthUsed = resource.freeNetUsed || 0;
const freeBandwidthRemaining = freeBandwidthTotal - freeBandwidthUsed;
const stakedBandwidthTotal = resource.NetLimit || 0;
const stakedBandwidthUsed = resource.NetUsed || 0;
const stakedBandwidthRemaining = stakedBandwidthTotal - stakedBandwidthUsed;
const totalBandwidth = freeBandwidthTotal + stakedBandwidthTotal;
const totalBandwidthUsed = freeBandwidthUsed + stakedBandwidthUsed;
const totalBandwidthRemaining = totalBandwidth - totalBandwidthUsed;
// Calculate energy status
const energyTotal = resource.EnergyLimit || 0;
const energyUsed = resource.EnergyUsed || 0;
const energyRemaining = energyTotal - energyUsed;
return {
address: address,
bandwidth: {
free: {
total: freeBandwidthTotal,
used: freeBandwidthUsed,
remaining: freeBandwidthRemaining,
usagePercent: freeBandwidthTotal > 0 ? (freeBandwidthUsed / freeBandwidthTotal * 100).toFixed(2) : 0
},
staked: {
total: stakedBandwidthTotal,
used: stakedBandwidthUsed,
remaining: stakedBandwidthRemaining,
usagePercent: stakedBandwidthTotal > 0 ? (stakedBandwidthUsed / stakedBandwidthTotal * 100).toFixed(2) : 0
},
total: {
total: totalBandwidth,
used: totalBandwidthUsed,
remaining: totalBandwidthRemaining,
usagePercent: totalBandwidth > 0 ? (totalBandwidthUsed / totalBandwidth * 100).toFixed(2) : 0
}
},
energy: {
total: energyTotal,
used: energyUsed,
remaining: energyRemaining,
usagePercent: energyTotal > 0 ? (energyUsed / energyTotal * 100).toFixed(2) : 0
},
votingPower: resource.tronPowerLimit || 0,
canMakeFreeTransactions: freeBandwidthRemaining > 0 || stakedBandwidthRemaining > 0,
needsEnergyForContracts: energyRemaining === 0,
recommendations: this.generateRecommendations(
freeBandwidthRemaining,
stakedBandwidthRemaining,
energyRemaining
)
};
} catch (error) {
console.error('Error getting resource status:', error);
throw error;
}
}
async getAccountResource(address) {
const response = await fetch(`${this.apiUrl}/wallet/getaccountresource`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ address, visible: true })
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
}
generateRecommendations(freeBandwidth, stakedBandwidth, energy) {
const recommendations = [];
if (freeBandwidth <= 0 && stakedBandwidth <= 0) {
recommendations.push({
type: 'bandwidth',
priority: 'high',
message: 'No bandwidth remaining. Transactions will cost TRX.',
action: 'Consider freezing TRX for bandwidth or wait for daily reset.'
});
} else if (freeBandwidth + stakedBandwidth < 1000) {
recommendations.push({
type: 'bandwidth',
priority: 'medium',
message: 'Low bandwidth remaining. Monitor usage carefully.',
action: 'Consider reducing transaction frequency or staking TRX.'
});
}
if (energy <= 0) {
recommendations.push({
type: 'energy',
priority: 'high',
message: 'No energy remaining. Smart contract calls will be expensive.',
action: 'Freeze TRX for energy or rent energy from platforms like JustLend.'
});
} else if (energy < 50000) {
recommendations.push({
type: 'energy',
priority: 'medium',
message: 'Low energy remaining. Limit smart contract interactions.',
action: 'Consider staking more TRX for energy.'
});
}
if (freeBandwidth > 3000 && energy > 100000) {
recommendations.push({
type: 'optimization',
priority: 'low',
message: 'Resources are well managed.',
action: 'Continue current staking strategy.'
});
}
return recommendations;
}
// Calculate transaction cost estimate
async estimateTransactionCost(address, transactionType = 'transfer') {
try {
const resourceStatus = await this.getResourceStatus(address);
const costs = {
transfer: { bandwidth: 268, energy: 0 },
trc20Transfer: { bandwidth: 345, energy: 13000 },
smartContract: { bandwidth: 345, energy: 50000 },
vote: { bandwidth: 200, energy: 0 },
freeze: { bandwidth: 200, energy: 0 }
};
const required = costs[transactionType] || costs.transfer;
let bandwidthCost = 0;
let energyCost = 0;
// Calculate bandwidth cost
if (required.bandwidth > resourceStatus.bandwidth.total.remaining) {
const excessBandwidth = required.bandwidth - resourceStatus.bandwidth.total.remaining;
bandwidthCost = excessBandwidth * 0.001; // 0.001 TRX per bandwidth point
}
// Calculate energy cost
if (required.energy > resourceStatus.energy.remaining) {
const excessEnergy = required.energy - resourceStatus.energy.remaining;
energyCost = excessEnergy * 0.00014; // ~0.00014 TRX per energy unit
}
const totalCostTRX = bandwidthCost + energyCost;
return {
transactionType,
required,
costs: {
bandwidth: bandwidthCost,
energy: energyCost,
total: totalCostTRX
},
willBeFree: totalCostTRX === 0,
resourceStatus
};
} catch (error) {
console.error('Error estimating transaction cost:', error);
throw error;
}
}
}
// Resource monitoring dashboard
class TronResourceMonitor {
constructor(apiKey, addresses = []) {
this.analyzer = new TronResourceAnalyzer(apiKey);
this.addresses = addresses;
this.isMonitoring = false;
this.monitoringInterval = null;
this.alerts = [];
}
addAddress(address) {
if (!this.addresses.includes(address)) {
this.addresses.push(address);
}
}
removeAddress(address) {
this.addresses = this.addresses.filter(addr => addr !== address);
}
async checkAllResources() {
const results = [];
for (const address of this.addresses) {
try {
const resourceStatus = await this.analyzer.getResourceStatus(address);
results.push({
address,
success: true,
data: resourceStatus
});
// Check for alerts
this.checkForAlerts(address, resourceStatus);
} catch (error) {
results.push({
address,
success: false,
error: error.message
});
}
}
return results;
}
checkForAlerts(address, resourceStatus) {
const now = Date.now();
// Bandwidth alerts
if (resourceStatus.bandwidth.total.remaining < 500) {
this.alerts.push({
address,
type: 'bandwidth_low',
message: `Low bandwidth: ${resourceStatus.bandwidth.total.remaining} remaining`,
timestamp: now,
severity: 'warning'
});
}
// Energy alerts
if (resourceStatus.energy.remaining < 10000) {
this.alerts.push({
address,
type: 'energy_low',
message: `Low energy: ${resourceStatus.energy.remaining} remaining`,
timestamp: now,
severity: 'warning'
});
}
// Critical alerts
if (resourceStatus.bandwidth.total.remaining === 0) {
this.alerts.push({
address,
type: 'bandwidth_exhausted',
message: 'Bandwidth exhausted - transactions will cost TRX',
timestamp: now,
severity: 'critical'
});
}
// Keep only recent alerts (last hour)
this.alerts = this.alerts.filter(alert => now - alert.timestamp < 3600000);
}
startMonitoring(intervalMinutes = 5) {
if (this.isMonitoring) {
console.log('Already monitoring resources');
return;
}
this.isMonitoring = true;
console.log(`Starting resource monitoring for ${this.addresses.length} addresses (${intervalMinutes}min intervals)`);
this.monitoringInterval = setInterval(async () => {
try {
const results = await this.checkAllResources();
const successful = results.filter(r => r.success);
console.log(`Resource check complete: ${successful.length}/${results.length} successful`);
// Report any new alerts
const recentAlerts = this.alerts.filter(alert =>
Date.now() - alert.timestamp < intervalMinutes * 60 * 1000
);
recentAlerts.forEach(alert => {
console.log(`⚠️ ${alert.severity.toUpperCase()}: ${alert.message} (${alert.address})`);
});
} catch (error) {
console.error('Resource monitoring error:', error);
}
}, intervalMinutes * 60 * 1000);
}
stopMonitoring() {
if (this.monitoringInterval) {
clearInterval(this.monitoringInterval);
this.monitoringInterval = null;
}
this.isMonitoring = false;
console.log('Resource monitoring stopped');
}
getAlerts(severity = null) {
if (severity) {
return this.alerts.filter(alert => alert.severity === severity);
}
return this.alerts;
}
}
// Usage examples
(async () => {
try {
const analyzer = new TronResourceAnalyzer('YOUR_API_KEY');
const address = 'TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN';
// Get resource status
const resourceStatus = await analyzer.getResourceStatus(address);
console.log('Resource Status:', resourceStatus);
// Estimate transaction costs
const transferCost = await analyzer.estimateTransactionCost(address, 'transfer');
console.log('Transfer cost:', transferCost);
const trc20Cost = await analyzer.estimateTransactionCost(address, 'trc20Transfer');
console.log('TRC20 transfer cost:', trc20Cost);
// Set up monitoring
const monitor = new TronResourceMonitor('YOUR_API_KEY', [address]);
monitor.startMonitoring(1); // Check every minute for demo
// Stop monitoring after 5 minutes
setTimeout(() => {
monitor.stopMonitoring();
console.log('Final alerts:', monitor.getAlerts());
}, 5 * 60 * 1000);
} catch (error) {
console.error('Error:', error);
}
})();
import requests
import json
import time
import threading
from typing import Dict, List, Optional
from datetime import datetime, timedelta
class TronResourceAnalyzer:
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_account_resource(self, address: str) -> Dict:
"""Get raw account resource data"""
url = f"{self.base_url}/wallet/getaccountresource"
payload = {
"address": address,
"visible": True
}
response = requests.post(url, headers=self.headers, json=payload)
response.raise_for_status()
return response.json()
def get_resource_status(self, address: str) -> Dict:
"""Get formatted resource status with analysis"""
try:
resource = self.get_account_resource(address)
# Calculate bandwidth status
free_bandwidth_total = resource.get('freeNetLimit', 0)
free_bandwidth_used = resource.get('freeNetUsed', 0)
free_bandwidth_remaining = free_bandwidth_total - free_bandwidth_used
staked_bandwidth_total = resource.get('NetLimit', 0)
staked_bandwidth_used = resource.get('NetUsed', 0)
staked_bandwidth_remaining = staked_bandwidth_total - staked_bandwidth_used
total_bandwidth = free_bandwidth_total + staked_bandwidth_total
total_bandwidth_used = free_bandwidth_used + staked_bandwidth_used
total_bandwidth_remaining = total_bandwidth - total_bandwidth_used
# Calculate energy status
energy_total = resource.get('EnergyLimit', 0)
energy_used = resource.get('EnergyUsed', 0)
energy_remaining = energy_total - energy_used
return {
'address': address,
'bandwidth': {
'free': {
'total': free_bandwidth_total,
'used': free_bandwidth_used,
'remaining': free_bandwidth_remaining,
'usage_percent': round(free_bandwidth_used / free_bandwidth_total * 100, 2) if free_bandwidth_total > 0 else 0
},
'staked': {
'total': staked_bandwidth_total,
'used': staked_bandwidth_used,
'remaining': staked_bandwidth_remaining,
'usage_percent': round(staked_bandwidth_used / staked_bandwidth_total * 100, 2) if staked_bandwidth_total > 0 else 0
},
'total': {
'total': total_bandwidth,
'used': total_bandwidth_used,
'remaining': total_bandwidth_remaining,
'usage_percent': round(total_bandwidth_used / total_bandwidth * 100, 2) if total_bandwidth > 0 else 0
}
},
'energy': {
'total': energy_total,
'used': energy_used,
'remaining': energy_remaining,
'usage_percent': round(energy_used / energy_total * 100, 2) if energy_total > 0 else 0
},
'voting_power': resource.get('tronPowerLimit', 0),
'can_make_free_transactions': free_bandwidth_remaining > 0 or staked_bandwidth_remaining > 0,
'needs_energy_for_contracts': energy_remaining == 0,
'recommendations': self._generate_recommendations(
free_bandwidth_remaining,
staked_bandwidth_remaining,
energy_remaining
)
}
except Exception as e:
print(f"Error getting resource status: {e}")
raise
def _generate_recommendations(self, free_bandwidth: int, staked_bandwidth: int, energy: int) -> List[Dict]:
"""Generate resource optimization recommendations"""
recommendations = []
if free_bandwidth <= 0 and staked_bandwidth <= 0:
recommendations.append({
'type': 'bandwidth',
'priority': 'high',
'message': 'No bandwidth remaining. Transactions will cost TRX.',
'action': 'Consider freezing TRX for bandwidth or wait for daily reset.'
})
elif free_bandwidth + staked_bandwidth < 1000:
recommendations.append({
'type': 'bandwidth',
'priority': 'medium',
'message': 'Low bandwidth remaining. Monitor usage carefully.',
'action': 'Consider reducing transaction frequency or staking TRX.'
})
if energy <= 0:
recommendations.append({
'type': 'energy',
'priority': 'high',
'message': 'No energy remaining. Smart contract calls will be expensive.',
'action': 'Freeze TRX for energy or rent energy from platforms like JustLend.'
})
elif energy < 50000:
recommendations.append({
'type': 'energy',
'priority': 'medium',
'message': 'Low energy remaining. Limit smart contract interactions.',
'action': 'Consider staking more TRX for energy.'
})
if free_bandwidth > 3000 and energy > 100000:
recommendations.append({
'type': 'optimization',
'priority': 'low',
'message': 'Resources are well managed.',
'action': 'Continue current staking strategy.'
})
return recommendations
def estimate_transaction_cost(self, address: str, transaction_type: str = 'transfer') -> Dict:
"""Estimate transaction cost based on current resources"""
try:
resource_status = self.get_resource_status(address)
# Transaction resource requirements
costs = {
'transfer': {'bandwidth': 268, 'energy': 0},
'trc20_transfer': {'bandwidth': 345, 'energy': 13000},
'smart_contract': {'bandwidth': 345, 'energy': 50000},
'vote': {'bandwidth': 200, 'energy': 0},
'freeze': {'bandwidth': 200, 'energy': 0}
}
required = costs.get(transaction_type, costs['transfer'])
bandwidth_cost = 0
energy_cost = 0
# Calculate bandwidth cost
bandwidth_remaining = resource_status['bandwidth']['total']['remaining']
if required['bandwidth'] > bandwidth_remaining:
excess_bandwidth = required['bandwidth'] - bandwidth_remaining
bandwidth_cost = excess_bandwidth * 0.001 # 0.001 TRX per bandwidth point
# Calculate energy cost
energy_remaining = resource_status['energy']['remaining']
if required['energy'] > energy_remaining:
excess_energy = required['energy'] - energy_remaining
energy_cost = excess_energy * 0.00014 # ~0.00014 TRX per energy unit
total_cost_trx = bandwidth_cost + energy_cost
return {
'transaction_type': transaction_type,
'required': required,
'costs': {
'bandwidth': bandwidth_cost,
'energy': energy_cost,
'total': total_cost_trx
},
'will_be_free': total_cost_trx == 0,
'resource_status': resource_status
}
except Exception as e:
print(f"Error estimating transaction cost: {e}")
raise
class TronResourceMonitor:
def __init__(self, api_key: str, addresses: List[str] = None):
self.analyzer = TronResourceAnalyzer(api_key)
self.addresses = addresses or []
self.is_monitoring = False
self.monitoring_thread = None
self.alerts = []
self.monitor_interval = 300 # 5 minutes default
def add_address(self, address: str):
"""Add address to monitoring list"""
if address not in self.addresses:
self.addresses.append(address)
def remove_address(self, address: str):
"""Remove address from monitoring list"""
if address in self.addresses:
self.addresses.remove(address)
def check_all_resources(self) -> List[Dict]:
"""Check resources for all monitored addresses"""
results = []
for address in self.addresses:
try:
resource_status = self.analyzer.get_resource_status(address)
results.append({
'address': address,
'success': True,
'data': resource_status
})
# Check for alerts
self._check_for_alerts(address, resource_status)
except Exception as e:
results.append({
'address': address,
'success': False,
'error': str(e)
})
return results
def _check_for_alerts(self, address: str, resource_status: Dict):
"""Check for resource alerts"""
now = datetime.now()
# Bandwidth alerts
bandwidth_remaining = resource_status['bandwidth']['total']['remaining']
if bandwidth_remaining < 500:
self.alerts.append({
'address': address,
'type': 'bandwidth_low',
'message': f'Low bandwidth: {bandwidth_remaining} remaining',
'timestamp': now,
'severity': 'warning'
})
# Energy alerts
energy_remaining = resource_status['energy']['remaining']
if energy_remaining < 10000:
self.alerts.append({
'address': address,
'type': 'energy_low',
'message': f'Low energy: {energy_remaining} remaining',
'timestamp': now,
'severity': 'warning'
})
# Critical alerts
if bandwidth_remaining == 0:
self.alerts.append({
'address': address,
'type': 'bandwidth_exhausted',
'message': 'Bandwidth exhausted - transactions will cost TRX',
'timestamp': now,
'severity': 'critical'
})
# Keep only recent alerts (last hour)
cutoff_time = now - timedelta(hours=1)
self.alerts = [alert for alert in self.alerts if alert['timestamp'] > cutoff_time]
def start_monitoring(self, interval_minutes: int = 5):
"""Start resource monitoring"""
if self.is_monitoring:
print("Already monitoring resources")
return
self.monitor_interval = interval_minutes * 60
self.is_monitoring = True
print(f"Starting resource monitoring for {len(self.addresses)} addresses ({interval_minutes}min intervals)")
self.monitoring_thread = threading.Thread(target=self._monitoring_loop)
self.monitoring_thread.daemon = True
self.monitoring_thread.start()
def _monitoring_loop(self):
"""Main monitoring loop"""
while self.is_monitoring:
try:
results = self.check_all_resources()
successful = [r for r in results if r['success']]
print(f"Resource check complete: {len(successful)}/{len(results)} successful")
# Report any new alerts
recent_alerts = [
alert for alert in self.alerts
if (datetime.now() - alert['timestamp']).total_seconds() < self.monitor_interval
]
for alert in recent_alerts:
print(f"⚠️ {alert['severity'].upper()}: {alert['message']} ({alert['address']})")
except Exception as e:
print(f"Resource monitoring error: {e}")
time.sleep(self.monitor_interval)
def stop_monitoring(self):
"""Stop resource monitoring"""
self.is_monitoring = False
if self.monitoring_thread:
self.monitoring_thread.join()
print("Resource monitoring stopped")
def get_alerts(self, severity: str = None) -> List[Dict]:
"""Get alerts, optionally filtered by severity"""
if severity:
return [alert for alert in self.alerts if alert['severity'] == severity]
return self.alerts
class TronResourceOptimizer:
def __init__(self, api_key: str):
self.analyzer = TronResourceAnalyzer(api_key)
def calculate_optimal_stake(self, address: str, daily_transactions: int,
smart_contract_calls: int = 0) -> Dict:
"""Calculate optimal TRX staking for bandwidth and energy"""
try:
# Daily bandwidth requirement
bandwidth_per_tx = 268 # Basic transfer
daily_bandwidth_needed = daily_transactions * bandwidth_per_tx
# Daily energy requirement
energy_per_call = 50000 # Average smart contract call
daily_energy_needed = smart_contract_calls * energy_per_call
# Account for free bandwidth (5000 daily)
extra_bandwidth_needed = max(0, daily_bandwidth_needed - 5000)
# TRX staking calculations (simplified)
# 1 TRX frozen = ~1000 bandwidth points or ~4000 energy
trx_for_bandwidth = extra_bandwidth_needed / 1000
trx_for_energy = daily_energy_needed / 4000
total_trx_to_stake = trx_for_bandwidth + trx_for_energy
return {
'daily_requirements': {
'transactions': daily_transactions,
'smart_contract_calls': smart_contract_calls,
'bandwidth_needed': daily_bandwidth_needed,
'energy_needed': daily_energy_needed
},
'current_status': self.analyzer.get_resource_status(address),
'recommendations': {
'trx_for_bandwidth': round(trx_for_bandwidth, 2),
'trx_for_energy': round(trx_for_energy, 2),
'total_trx_to_stake': round(total_trx_to_stake, 2),
'will_eliminate_fees': total_trx_to_stake > 0
},
'savings_estimate': {
'daily_fee_savings': round((daily_transactions * 0.268 + smart_contract_calls * 7) * 0.1, 4),
'monthly_fee_savings': round((daily_transactions * 0.268 + smart_contract_calls * 7) * 0.1 * 30, 2)
}
}
except Exception as e:
print(f"Error calculating optimal stake: {e}")
raise
# Usage examples
if __name__ == "__main__":
analyzer = TronResourceAnalyzer('YOUR_API_KEY')
try:
address = 'TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN'
# Get resource status
resource_status = analyzer.get_resource_status(address)
print("Resource Status:")
print(f" Bandwidth: {resource_status['bandwidth']['total']['remaining']}/{resource_status['bandwidth']['total']['total']}")
print(f" Energy: {resource_status['energy']['remaining']}/{resource_status['energy']['total']}")
# Estimate costs
transfer_cost = analyzer.estimate_transaction_cost(address, 'transfer')
print(f"\nTransfer cost: {transfer_cost['costs']['total']} TRX (Free: {transfer_cost['will_be_free']})")
trc20_cost = analyzer.estimate_transaction_cost(address, 'trc20_transfer')
print(f"TRC20 transfer cost: {trc20_cost['costs']['total']} TRX (Free: {trc20_cost['will_be_free']})")
# Resource optimization
optimizer = TronResourceOptimizer('YOUR_API_KEY')
optimization = optimizer.calculate_optimal_stake(address, daily_transactions=10, smart_contract_calls=5)
print(f"\nOptimal staking:")
print(f" TRX for bandwidth: {optimization['recommendations']['trx_for_bandwidth']}")
print(f" TRX for energy: {optimization['recommendations']['trx_for_energy']}")
print(f" Total TRX to stake: {optimization['recommendations']['total_trx_to_stake']}")
print(f" Monthly savings: {optimization['savings_estimate']['monthly_fee_savings']} TRX")
# Start monitoring (comment out for non-continuous examples)
# monitor = TronResourceMonitor('YOUR_API_KEY', [address])
# monitor.start_monitoring(1) # Check every minute
# time.sleep(60) # Monitor for 1 minute
# monitor.stop_monitoring()
except Exception as e:
print(f"Error: {e}")
# Get account resources
curl -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getaccountresource" \
-H "Content-Type: application/json" \
-d '{
"address": "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN",
"visible": true
}'
# Format and analyze resource data
curl -s -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getaccountresource" \
-H "Content-Type: application/json" \
-d '{
"address": "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN",
"visible": true
}' | jq '{
address: "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN",
bandwidth: {
free_limit: .freeNetLimit // 0,
free_used: .freeNetUsed // 0,
free_remaining: (.freeNetLimit // 0) - (.freeNetUsed // 0),
staked_limit: .NetLimit // 0,
staked_used: .NetUsed // 0,
staked_remaining: (.NetLimit // 0) - (.NetUsed // 0),
total_remaining: ((.freeNetLimit // 0) - (.freeNetUsed // 0)) + ((.NetLimit // 0) - (.NetUsed // 0))
},
energy: {
limit: .EnergyLimit // 0,
used: .EnergyUsed // 0,
remaining: (.EnergyLimit // 0) - (.EnergyUsed // 0)
},
voting_power: .tronPowerLimit // 0
}'
# Resource monitoring script
#!/bin/bash
API_KEY="YOUR_API_KEY"
ADDRESSES=("TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN" "TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh")
ALERT_LOG="/tmp/tron_alerts.log"
# Function to get resources for an address
get_resources() {
local address=$1
curl -s -X POST "https://api-tron-mainnet.n.dwellir.com/$API_KEY/wallet/getaccountresource" \
-H "Content-Type: application/json" \
-d "{\"address\": \"$address\", \"visible\": true}"
}
# Function to analyze resources and generate alerts
analyze_resources() {
local address=$1
local resource_data=$2
# Extract resource values
local free_limit=$(echo "$resource_data" | jq -r '.freeNetLimit // 0')
local free_used=$(echo "$resource_data" | jq -r '.freeNetUsed // 0')
local staked_limit=$(echo "$resource_data" | jq -r '.NetLimit // 0')
local staked_used=$(echo "$resource_data" | jq -r '.NetUsed // 0')
local energy_limit=$(echo "$resource_data" | jq -r '.EnergyLimit // 0')
local energy_used=$(echo "$resource_data" | jq -r '.EnergyUsed // 0')
# Calculate remaining resources
local free_remaining=$((free_limit - free_used))
local staked_remaining=$((staked_limit - staked_used))
local total_bandwidth_remaining=$((free_remaining + staked_remaining))
local energy_remaining=$((energy_limit - energy_used))
# Generate status report
echo "=== Resource Status for $address ==="
echo "Bandwidth:"
echo " Free: $free_remaining / $free_limit"
echo " Staked: $staked_remaining / $staked_limit"
echo " Total: $total_bandwidth_remaining"
echo "Energy:"
echo " Remaining: $energy_remaining / $energy_limit"
echo ""
# Check for alerts
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
if [ "$total_bandwidth_remaining" -lt 500 ]; then
echo "⚠️ WARNING: Low bandwidth ($total_bandwidth_remaining remaining) - $address" | tee -a "$ALERT_LOG"
fi
if [ "$total_bandwidth_remaining" -eq 0 ]; then
echo "🚨 CRITICAL: Bandwidth exhausted - transactions will cost TRX - $address" | tee -a "$ALERT_LOG"
fi
if [ "$energy_remaining" -lt 10000 ]; then
echo "⚠️ WARNING: Low energy ($energy_remaining remaining) - $address" | tee -a "$ALERT_LOG"
fi
if [ "$energy_remaining" -eq 0 ]; then
echo "🚨 CRITICAL: Energy exhausted - smart contracts will be expensive - $address" | tee -a "$ALERT_LOG"
fi
}
# Function to estimate transaction costs
estimate_transaction_cost() {
local address=$1
local tx_type=${2:-"transfer"}
local resource_data=$(get_resources "$address")
local total_bandwidth_remaining=$(echo "$resource_data" | jq -r '
((.freeNetLimit // 0) - (.freeNetUsed // 0)) +
((.NetLimit // 0) - (.NetUsed // 0))
')
local energy_remaining=$(echo "$resource_data" | jq -r '(.EnergyLimit // 0) - (.EnergyUsed // 0)')
# Define transaction requirements
case "$tx_type" in
"transfer")
local bandwidth_needed=268
local energy_needed=0
;;
"trc20")
local bandwidth_needed=345
local energy_needed=13000
;;
"contract")
local bandwidth_needed=345
local energy_needed=50000
;;
*)
local bandwidth_needed=268
local energy_needed=0
;;
esac
# Calculate costs
local bandwidth_cost=0
local energy_cost=0
if [ "$bandwidth_needed" -gt "$total_bandwidth_remaining" ]; then
local excess_bandwidth=$((bandwidth_needed - total_bandwidth_remaining))
bandwidth_cost=$(echo "scale=6; $excess_bandwidth * 0.001" | bc -l)
fi
if [ "$energy_needed" -gt "$energy_remaining" ]; then
local excess_energy=$((energy_needed - energy_remaining))
energy_cost=$(echo "scale=6; $excess_energy * 0.00014" | bc -l)
fi
local total_cost=$(echo "scale=6; $bandwidth_cost + $energy_cost" | bc -l)
echo "Transaction cost estimate for $tx_type:"
echo " Bandwidth cost: $bandwidth_cost TRX"
echo " Energy cost: $energy_cost TRX"
echo " Total cost: $total_cost TRX"
if [ "$total_cost" = "0.000000" ]; then
echo " ✅ Transaction will be FREE"
else
echo " 💰 Transaction will cost $total_cost TRX"
fi
echo ""
}
# Function to calculate optimal staking
calculate_optimal_stake() {
local address=$1
local daily_txs=${2:-10}
local daily_contracts=${3:-0}
echo "=== Optimal Staking Calculation for $address ==="
echo "Daily usage: $daily_txs transfers, $daily_contracts smart contract calls"
# Calculate daily requirements
local daily_bandwidth=$((daily_txs * 268))
local daily_energy=$((daily_contracts * 50000))
# Account for free bandwidth
local extra_bandwidth_needed=$((daily_bandwidth > 5000 ? daily_bandwidth - 5000 : 0))
# Calculate TRX staking needs (simplified ratios)
local trx_for_bandwidth=$(echo "scale=2; $extra_bandwidth_needed / 1000" | bc -l)
local trx_for_energy=$(echo "scale=2; $daily_energy / 4000" | bc -l)
local total_trx=$(echo "scale=2; $trx_for_bandwidth + $trx_for_energy" | bc -l)
echo "Requirements:"
echo " Daily bandwidth needed: $daily_bandwidth"
echo " Daily energy needed: $daily_energy"
echo " Extra bandwidth needed: $extra_bandwidth_needed"
echo ""
echo "Recommended staking:"
echo " TRX for bandwidth: $trx_for_bandwidth"
echo " TRX for energy: $trx_for_energy"
echo " Total TRX to stake: $total_trx"
echo ""
}
# Resource monitoring function
monitor_resources() {
local interval=${1:-300} # Default 5 minutes
local duration=${2:-3600} # Default 1 hour
echo "Starting resource monitoring for ${#ADDRESSES[@]} addresses..."
echo "Check interval: ${interval}s, Duration: ${duration}s"
echo "Alerts will be logged to $ALERT_LOG"
echo ""
local end_time=$(($(date +%s) + duration))
while [ $(date +%s) -lt $end_time ]; do
echo "=== Resource Check at $(date) ==="
for address in "${ADDRESSES[@]}"; do
local resource_data=$(get_resources "$address")
if [ $? -eq 0 ] && [ -n "$resource_data" ]; then
analyze_resources "$address" "$resource_data"
else
echo "❌ Failed to get resources for $address"
fi
done
echo "Sleeping for ${interval}s..."
echo ""
sleep "$interval"
done
echo "Resource monitoring completed."
echo "Final alert summary:"
cat "$ALERT_LOG" 2>/dev/null || echo "No alerts logged."
}
# Usage examples
case "${1:-status}" in
"status")
# Default: show status for all addresses
for address in "${ADDRESSES[@]}"; do
resource_data=$(get_resources "$address")
analyze_resources "$address" "$resource_data"
done
;;
"cost")
# Estimate transaction costs
estimate_transaction_cost "$2" "$3"
;;
"stake")
# Calculate optimal staking
calculate_optimal_stake "$2" "$3" "$4"
;;
"monitor")
# Start monitoring
monitor_resources "$2" "$3"
;;
*)
echo "Usage: $0 {status|cost ADDRESS [TYPE]|stake ADDRESS [DAILY_TXS] [DAILY_CONTRACTS]|monitor [INTERVAL] [DURATION]}"
echo ""
echo "Examples:"
echo " $0 status # Show resource status"
echo " $0 cost TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN transfer # Estimate transfer cost"
echo " $0 stake TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN 10 5 # Calculate staking for 10 transfers + 5 contracts daily"
echo " $0 monitor 60 1800 # Monitor for 30 minutes, check every minute"
;;
esac
Response Examples
Normal Account with Resources
{
"freeNetLimit": 5000,
"freeNetUsed": 1234,
"NetLimit": 10000,
"NetUsed": 2500,
"EnergyLimit": 150000,
"EnergyUsed": 45000,
"tronPowerLimit": 1000000,
"assetNetUsed": [],
"assetNetLimit": []
}
New Account (Minimal Resources)
{
"freeNetLimit": 5000,
"freeNetUsed": 0
}
Account with Token-Specific Bandwidth
{
"freeNetLimit": 5000,
"freeNetUsed": 500,
"NetLimit": 5000,
"NetUsed": 1000,
"EnergyLimit": 100000,
"EnergyUsed": 25000,
"tronPowerLimit": 500000,
"assetNetUsed": [
{
"key": "1000001",
"value": 100
}
],
"assetNetLimit": [
{
"key": "1000001",
"value": 1000
}
]
}
Common Use Cases
1. Wallet Resource Dashboard
class WalletResourceDashboard {
constructor(apiKey) {
this.analyzer = new TronResourceAnalyzer(apiKey);
this.updateInterval = null;
}
async createDashboard(address) {
const resourceStatus = await this.analyzer.getResourceStatus(address);
return {
address: address,
lastUpdated: new Date().toISOString(),
status: {
bandwidth: {
percentage: resourceStatus.bandwidth.total.usagePercent,
remaining: resourceStatus.bandwidth.total.remaining,
status: this.getStatusLevel(resourceStatus.bandwidth.total.usagePercent),
resetTime: this.calculateBandwidthReset()
},
energy: {
percentage: resourceStatus.energy.usagePercent,
remaining: resourceStatus.energy.remaining,
status: this.getStatusLevel(resourceStatus.energy.usagePercent)
}
},
capabilities: {
canMakeFreeTransfers: resourceStatus.canMakeFreeTransactions,
canCallContracts: resourceStatus.energy.remaining > 0,
recommendedActions: resourceStatus.recommendations
},
estimatedCosts: await this.getEstimatedCosts(address)
};
}
getStatusLevel(percentage) {
if (percentage < 50) return 'good';
if (percentage < 80) return 'warning';
return 'critical';
}
calculateBandwidthReset() {
const now = new Date();
const tomorrow = new Date(now);
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(0, 0, 0, 0);
return tomorrow.toISOString();
}
async getEstimatedCosts(address) {
const [transfer, trc20, contract] = await Promise.all([
this.analyzer.estimateTransactionCost(address, 'transfer'),
this.analyzer.estimateTransactionCost(address, 'trc20Transfer'),
this.analyzer.estimateTransactionCost(address, 'smartContract')
]);
return { transfer, trc20, contract };
}
}
2. Smart Contract Gas Optimizer
class TronGasOptimizer {
constructor(apiKey) {
this.analyzer = new TronResourceAnalyzer(apiKey);
}
async optimizeContractCall(address, estimatedEnergy) {
const resourceStatus = await this.analyzer.getResourceStatus(address);
const energyRemaining = resourceStatus.energy.remaining;
if (energyRemaining >= estimatedEnergy) {
return {
strategy: 'use_staked_energy',
cost: 0,
message: 'Use existing staked energy - free transaction'
};
}
const energyNeeded = estimatedEnergy - energyRemaining;
const trxCost = energyNeeded * 0.00014;
// Calculate different strategies
const strategies = [
{
strategy: 'pay_with_trx',
cost: trxCost,
message: `Pay ${trxCost.toFixed(6)} TRX for energy`
},
{
strategy: 'stake_trx',
cost: energyNeeded / 4000, // Simplified ratio
message: `Stake ${(energyNeeded / 4000).toFixed(2)} TRX for energy`,
benefits: 'Reusable energy for future transactions'
},
{
strategy: 'rent_energy',
cost: trxCost * 0.7, // Assume 30% savings
message: `Rent energy for ${(trxCost * 0.7).toFixed(6)} TRX`,
benefits: 'Lower cost for one-time use'
}
];
// Sort by cost
strategies.sort((a, b) => a.cost - b.cost);
return {
energyNeeded,
currentEnergy: energyRemaining,
requiredEnergy: estimatedEnergy,
recommendedStrategy: strategies[0],
allStrategies: strategies
};
}
}
3. Resource Alert System
class TronResourceAlertSystem {
constructor(apiKey) {
this.analyzer = new TronResourceAnalyzer(apiKey);
this.alertCallbacks = new Map();
this.thresholds = {
bandwidth: { warning: 1000, critical: 100 },
energy: { warning: 20000, critical: 5000 }
};
}
onAlert(type, callback) {
if (!this.alertCallbacks.has(type)) {
this.alertCallbacks.set(type, []);
}
this.alertCallbacks.get(type).push(callback);
}
async checkAndAlert(address) {
try {
const resourceStatus = await this.analyzer.getResourceStatus(address);
// Check bandwidth alerts
const bandwidthRemaining = resourceStatus.bandwidth.total.remaining;
if (bandwidthRemaining <= this.thresholds.bandwidth.critical) {
this.triggerAlert('bandwidth_critical', {
address,
remaining: bandwidthRemaining,
severity: 'critical',
message: 'Bandwidth critically low - transactions will cost TRX'
});
} else if (bandwidthRemaining <= this.thresholds.bandwidth.warning) {
this.triggerAlert('bandwidth_warning', {
address,
remaining: bandwidthRemaining,
severity: 'warning',
message: 'Bandwidth running low'
});
}
// Check energy alerts
const energyRemaining = resourceStatus.energy.remaining;
if (energyRemaining <= this.thresholds.energy.critical) {
this.triggerAlert('energy_critical', {
address,
remaining: energyRemaining,
severity: 'critical',
message: 'Energy critically low - smart contracts will be expensive'
});
} else if (energyRemaining <= this.thresholds.energy.warning) {
this.triggerAlert('energy_warning', {
address,
remaining: energyRemaining,
severity: 'warning',
message: 'Energy running low'
});
}
} catch (error) {
this.triggerAlert('error', {
address,
error: error.message,
severity: 'error',
message: 'Failed to check resources'
});
}
}
triggerAlert(type, data) {
const callbacks = this.alertCallbacks.get(type) || [];
callbacks.forEach(callback => {
try {
callback(data);
} catch (error) {
console.error('Alert callback error:', error);
}
});
}
setThreshold(resource, level, value) {
if (this.thresholds[resource] && this.thresholds[resource][level] !== undefined) {
this.thresholds[resource][level] = value;
}
}
}
Performance Tips
- Cache Resource Data - Resources update slowly, cache for 30-60 seconds
- Batch Monitoring - Check multiple addresses in sequence with slight delays
- Smart Polling - Increase check frequency when resources are low
- Alert Optimization - Use thresholds to avoid alert spam
// Optimized resource monitoring with smart intervals
class SmartResourceMonitor {
constructor(apiKey) {
this.analyzer = new TronResourceAnalyzer(apiKey);
this.cache = new Map();
this.dynamicIntervals = new Map();
}
async monitorWithSmartIntervals(address) {
const resourceStatus = await this.analyzer.getResourceStatus(address);
// Determine monitoring frequency based on resource levels
const bandwidthPercent = resourceStatus.bandwidth.total.usagePercent;
const energyPercent = resourceStatus.energy.usagePercent;
let interval;
if (bandwidthPercent > 90 || energyPercent > 90) {
interval = 60000; // 1 minute for critical
} else if (bandwidthPercent > 70 || energyPercent > 70) {
interval = 300000; // 5 minutes for warning
} else {
interval = 1800000; // 30 minutes for normal
}
this.dynamicIntervals.set(address, interval);
// Cache result
this.cache.set(address, {
data: resourceStatus,
timestamp: Date.now(),
ttl: Math.min(interval / 2, 60000) // Cache for half the interval, max 1 minute
});
return resourceStatus;
}
}
Need help? Contact our support team or check the TRON documentation.