Docs

wallet/getaccountresource - Get TRON Account Re...

Get TRON account bandwidth and energy resources for transaction fee optimization. Monitor resource usage and manage stake efficiently with Dwellir RPC.

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

Request Parameters

Request
addressstring

TRON address in Base58 format Example: `"TNPdqto8HiuMzoG7Vv9wyyYhWzCojLeHAF"`

visibleboolean

`true` - Use Base58 address format `false` - Use hex address format

Response Body

Response
resultOBJECT

`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

Bash
# 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": "TNPdqto8HiuMzoG7Vv9wyyYhWzCojLeHAF",
    "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": "TNPdqto8HiuMzoG7Vv9wyyYhWzCojLeHAF",
    "visible": true
  }' | jq '{
    address: "TNPdqto8HiuMzoG7Vv9wyyYhWzCojLeHAF",
    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=("TNPdqto8HiuMzoG7Vv9wyyYhWzCojLeHAF" "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 TNPdqto8HiuMzoG7Vv9wyyYhWzCojLeHAF transfer    # Estimate transfer cost"
    echo "  $0 stake TNPdqto8HiuMzoG7Vv9wyyYhWzCojLeHAF 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

JSON
{
  "freeNetLimit": 5000,
  "freeNetUsed": 1234,
  "NetLimit": 10000,
  "NetUsed": 2500,
  "EnergyLimit": 150000,
  "EnergyUsed": 45000,
  "tronPowerLimit": 1000000,
  "assetNetUsed": [],
  "assetNetLimit": []
}

New Account (Minimal Resources)

JSON
{
  "freeNetLimit": 5000,
  "freeNetUsed": 0
}

Account with Token-Specific Bandwidth

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

JavaScript
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

JavaScript
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

JavaScript
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
JavaScript
// 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.