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

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.

Monitor your resources →

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

  1. address - string (required)

    • TRON address in Base58 format
    • Example: "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN"
  2. visible - boolean (optional, default: false)

    • true - Use Base58 address format
    • false - 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 today
  • NetLimit - Additional bandwidth from frozen TRX
  • NetUsed - Additional bandwidth consumed
  • EnergyLimit - Energy from frozen TRX
  • EnergyUsed - Energy consumed
  • tronPowerLimit - Voting power from staked TRX
  • assetNetLimit - Token-specific bandwidth limits
  • assetNetUsed - Token-specific bandwidth usage

Implementation Examples

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

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

  1. Cache Resource Data - Resources update slowly, cache for 30-60 seconds
  2. Batch Monitoring - Check multiple addresses in sequence with slight delays
  3. Smart Polling - Increase check frequency when resources are low
  4. 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.