wallet/freezebalancev2
Resource Management V2
Dwellir's TRON infrastructure supports the latest Stake 2.0 mechanism for efficient resource management. Stake TRX to get bandwidth/energy while earning rewards and voting rights.
Freeze (stake) TRX balance to obtain bandwidth or energy resources using the Stake 2.0 mechanism. Staked TRX earns rewards and provides voting power for Super Representatives.
Use Cases
wallet/freezebalancev2
is essential for:
- Resource Acquisition - Get bandwidth for transactions
- Energy Generation - Power smart contract interactions
- Reward Earning - Earn staking rewards (~4-7% APR)
- Governance Participation - Gain voting power for SRs
- DApp Operations - Ensure smooth contract execution
Parameters
Parameter | Type | Required | Description |
---|---|---|---|
owner_address | string | Yes | Address staking TRX (Base58 or Hex) |
frozen_balance | number | Yes | Amount to stake in SUN (1 TRX = 1,000,000 SUN) |
resource | string | Yes | Resource type: "BANDWIDTH" or "ENERGY" |
visible | boolean | No | Use Base58 format (default: true) |
permission_id | number | No | Permission ID for multi-sig accounts |
Request Example
{
"owner_address": "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN",
"frozen_balance": 10000000000,
"resource": "ENERGY",
"visible": true
}
Response Fields
Field | Type | Description |
---|---|---|
txid | string | Transaction ID |
visible | boolean | Address format used |
raw_data | object | Transaction raw data |
raw_data.contract | array | Contract details |
raw_data.ref_block_bytes | string | Reference block bytes |
raw_data.ref_block_hash | string | Reference block hash |
raw_data.expiration | number | Transaction expiration time |
raw_data.timestamp | number | Transaction timestamp |
Implementation Examples
- JavaScript
- Python
- cURL
const TronWeb = require('tronweb');
class TronStakingManager {
constructor(apiKey, privateKey = null) {
this.apiUrl = `https://api-tron-mainnet.n.dwellir.com/${apiKey}`;
this.headers = { 'Content-Type': 'application/json' };
this.privateKey = privateKey;
// Initialize TronWeb for signing if private key provided
if (privateKey) {
this.tronWeb = new TronWeb({
fullHost: this.apiUrl,
privateKey: privateKey
});
}
}
// Create freeze balance v2 transaction
async createFreezeV2Transaction(address, amountTRX, resource = 'ENERGY') {
const amountSUN = amountTRX * 1_000_000; // Convert TRX to SUN
const response = await fetch(`${this.apiUrl}/wallet/freezebalancev2`, {
method: 'POST',
headers: this.headers,
body: JSON.stringify({
owner_address: address,
frozen_balance: amountSUN,
resource: resource.toUpperCase(),
visible: true
})
});
if (!response.ok) {
throw new Error(`Freeze transaction failed: ${response.statusText}`);
}
return await response.json();
}
// Sign and broadcast transaction
async stakeAndBroadcast(address, amountTRX, resource = 'ENERGY') {
if (!this.privateKey) {
throw new Error('Private key required for signing');
}
// Create transaction
const transaction = await this.createFreezeV2Transaction(address, amountTRX, resource);
// Sign transaction
const signedTx = await this.tronWeb.trx.sign(transaction);
// Broadcast transaction
const result = await this.broadcastTransaction(signedTx);
return {
txid: result.txid,
success: result.result,
resource: resource,
amountTRX: amountTRX,
message: result.message || 'Transaction broadcast successfully'
};
}
async broadcastTransaction(signedTransaction) {
const response = await fetch(`${this.apiUrl}/wallet/broadcasttransaction`, {
method: 'POST',
headers: this.headers,
body: JSON.stringify(signedTransaction)
});
return await response.json();
}
// Calculate optimal stake amount
async calculateOptimalStake(address, dailyOperations = 100) {
// Get current account resources
const accountResource = await this.getAccountResource(address);
// Estimate required resources
const bandwidthPerTx = 250; // Average bandwidth per transaction
const energyPerContract = 50000; // Average energy per contract call
const dailyBandwidth = dailyOperations * bandwidthPerTx;
const dailyEnergy = dailyOperations * energyPerContract;
// Calculate TRX needed (approximate)
const trxForBandwidth = Math.ceil(dailyBandwidth / 1000); // ~1000 bandwidth per TRX
const trxForEnergy = Math.ceil(dailyEnergy / 280); // ~280 energy per TRX
return {
recommended: {
bandwidth: trxForBandwidth,
energy: trxForEnergy
},
current: {
bandwidth: accountResource.freeNetLimit || 0,
energy: accountResource.EnergyLimit || 0
},
dailyRequirement: {
bandwidth: dailyBandwidth,
energy: dailyEnergy
}
};
}
async getAccountResource(address) {
const response = await fetch(`${this.apiUrl}/wallet/getaccountresource`, {
method: 'POST',
headers: this.headers,
body: JSON.stringify({
address: address,
visible: true
})
});
return await response.json();
}
// Batch stake for multiple resources
async stakeForResources(address, bandwidthTRX, energyTRX) {
const results = [];
if (bandwidthTRX > 0) {
try {
const bandwidthResult = await this.stakeAndBroadcast(
address,
bandwidthTRX,
'BANDWIDTH'
);
results.push({
type: 'BANDWIDTH',
success: true,
...bandwidthResult
});
} catch (error) {
results.push({
type: 'BANDWIDTH',
success: false,
error: error.message
});
}
}
if (energyTRX > 0) {
// Wait 3 seconds between transactions
await new Promise(resolve => setTimeout(resolve, 3000));
try {
const energyResult = await this.stakeAndBroadcast(
address,
energyTRX,
'ENERGY'
);
results.push({
type: 'ENERGY',
success: true,
...energyResult
});
} catch (error) {
results.push({
type: 'ENERGY',
success: false,
error: error.message
});
}
}
return results;
}
// Estimate staking rewards
estimateStakingRewards(amountTRX, durationDays = 365) {
const annualAPR = 0.05; // Approximate 5% APR
const dailyRate = annualAPR / 365;
const rewards = amountTRX * dailyRate * durationDays;
return {
amountStaked: amountTRX,
duration: durationDays,
estimatedRewards: rewards.toFixed(6),
apr: (annualAPR * 100).toFixed(2) + '%',
daily: (amountTRX * dailyRate).toFixed(6),
monthly: (amountTRX * dailyRate * 30).toFixed(6),
yearly: (amountTRX * annualAPR).toFixed(6)
};
}
}
// Resource Calculator
class ResourceCalculator {
constructor() {
this.rates = {
bandwidth: {
perTRX: 1000, // Approximate bandwidth per TRX
perTransaction: 250 // Average bandwidth per transaction
},
energy: {
perTRX: 280, // Approximate energy per TRX
perContractCall: 50000 // Average energy per smart contract call
}
};
}
calculateRequiredTRX(resourceType, amount) {
if (resourceType === 'BANDWIDTH') {
return Math.ceil(amount / this.rates.bandwidth.perTRX);
} else if (resourceType === 'ENERGY') {
return Math.ceil(amount / this.rates.energy.perTRX);
}
throw new Error('Invalid resource type');
}
estimateResourcesFromTRX(trxAmount, resourceType) {
if (resourceType === 'BANDWIDTH') {
return {
bandwidth: trxAmount * this.rates.bandwidth.perTRX,
transactions: Math.floor(
(trxAmount * this.rates.bandwidth.perTRX) /
this.rates.bandwidth.perTransaction
)
};
} else if (resourceType === 'ENERGY') {
return {
energy: trxAmount * this.rates.energy.perTRX,
contractCalls: Math.floor(
(trxAmount * this.rates.energy.perTRX) /
this.rates.energy.perContractCall
)
};
}
throw new Error('Invalid resource type');
}
getRecommendation(dailyTransactions, dailyContractCalls) {
const bandwidthNeeded = dailyTransactions * this.rates.bandwidth.perTransaction;
const energyNeeded = dailyContractCalls * this.rates.energy.perContractCall;
return {
bandwidth: {
required: bandwidthNeeded,
trxToStake: this.calculateRequiredTRX('BANDWIDTH', bandwidthNeeded),
dailyTransactions: dailyTransactions
},
energy: {
required: energyNeeded,
trxToStake: this.calculateRequiredTRX('ENERGY', energyNeeded),
dailyContractCalls: dailyContractCalls
},
total: {
trxRequired:
this.calculateRequiredTRX('BANDWIDTH', bandwidthNeeded) +
this.calculateRequiredTRX('ENERGY', energyNeeded)
}
};
}
}
// Usage examples
(async () => {
const staking = new TronStakingManager('YOUR_API_KEY', 'YOUR_PRIVATE_KEY');
const calculator = new ResourceCalculator();
try {
// Calculate resources needed
const recommendation = calculator.getRecommendation(
100, // Daily transactions
50 // Daily smart contract calls
);
console.log('Resource Recommendation:', recommendation);
// Estimate rewards
const rewards = staking.estimateStakingRewards(10000, 365);
console.log('Staking Rewards Estimate:', rewards);
// Calculate optimal stake
const optimal = await staking.calculateOptimalStake(
'TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN',
100
);
console.log('Optimal Stake:', optimal);
// Stake TRX for energy
const stakeResult = await staking.stakeAndBroadcast(
'TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN',
1000, // 1000 TRX
'ENERGY'
);
console.log('Stake Result:', stakeResult);
// Batch stake for both resources
const batchResult = await staking.stakeForResources(
'TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN',
500, // 500 TRX for bandwidth
1000 // 1000 TRX for energy
);
console.log('Batch Stake Results:', batchResult);
} catch (error) {
console.error('Error:', error);
}
})();
import requests
import json
import time
from typing import Dict, Optional, List
from datetime import datetime, timedelta
class TronStakingManager:
def __init__(self, api_key: str, private_key: Optional[str] = None):
self.base_url = f"https://api-tron-mainnet.n.dwellir.com/{api_key}"
self.headers = {'Content-Type': 'application/json'}
self.private_key = private_key
def create_freeze_v2_transaction(
self,
address: str,
amount_trx: float,
resource: str = 'ENERGY'
) -> Dict:
"""
Create a freeze balance v2 transaction
"""
amount_sun = int(amount_trx * 1_000_000) # Convert TRX to SUN
url = f"{self.base_url}/wallet/freezebalancev2"
payload = {
"owner_address": address,
"frozen_balance": amount_sun,
"resource": resource.upper(),
"visible": True
}
response = requests.post(url, headers=self.headers, json=payload)
response.raise_for_status()
return response.json()
def stake_trx(
self,
address: str,
amount_trx: float,
resource: str = 'ENERGY',
sign_and_broadcast: bool = False
) -> Dict:
"""
Stake TRX for resources
"""
# Create transaction
transaction = self.create_freeze_v2_transaction(address, amount_trx, resource)
if sign_and_broadcast and self.private_key:
# Sign transaction (requires tronpy or similar library)
# signed_tx = self.sign_transaction(transaction)
# result = self.broadcast_transaction(signed_tx)
# return result
pass
return {
'transaction': transaction,
'amount_trx': amount_trx,
'resource': resource,
'status': 'created',
'message': 'Transaction created. Sign and broadcast to complete.'
}
def calculate_optimal_stake(
self,
address: str,
daily_operations: int = 100
) -> Dict:
"""
Calculate optimal stake amount based on usage
"""
# Get current resources
resources = self.get_account_resource(address)
# Estimate requirements
bandwidth_per_tx = 250
energy_per_contract = 50000
daily_bandwidth = daily_operations * bandwidth_per_tx
daily_energy = daily_operations * energy_per_contract
# Calculate TRX needed
trx_for_bandwidth = daily_bandwidth // 1000 # ~1000 bandwidth per TRX
trx_for_energy = daily_energy // 280 # ~280 energy per TRX
return {
'recommended': {
'bandwidth_trx': trx_for_bandwidth,
'energy_trx': trx_for_energy,
'total_trx': trx_for_bandwidth + trx_for_energy
},
'current_resources': {
'bandwidth': resources.get('freeNetLimit', 0),
'energy': resources.get('EnergyLimit', 0)
},
'daily_requirement': {
'bandwidth': daily_bandwidth,
'energy': daily_energy,
'operations': daily_operations
}
}
def get_account_resource(self, address: str) -> Dict:
"""
Get account resource information
"""
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 batch_stake(
self,
address: str,
bandwidth_trx: float,
energy_trx: float
) -> List[Dict]:
"""
Stake for multiple resources in batch
"""
results = []
# Stake for bandwidth
if bandwidth_trx > 0:
try:
bandwidth_result = self.stake_trx(address, bandwidth_trx, 'BANDWIDTH')
results.append({
'type': 'BANDWIDTH',
'success': True,
**bandwidth_result
})
except Exception as e:
results.append({
'type': 'BANDWIDTH',
'success': False,
'error': str(e)
})
# Wait between transactions
time.sleep(3)
# Stake for energy
if energy_trx > 0:
try:
energy_result = self.stake_trx(address, energy_trx, 'ENERGY')
results.append({
'type': 'ENERGY',
'success': True,
**energy_result
})
except Exception as e:
results.append({
'type': 'ENERGY',
'success': False,
'error': str(e)
})
return results
def estimate_staking_rewards(
self,
amount_trx: float,
duration_days: int = 365
) -> Dict:
"""
Estimate staking rewards
"""
annual_apr = 0.05 # Approximate 5% APR
daily_rate = annual_apr / 365
rewards = amount_trx * daily_rate * duration_days
return {
'amount_staked': amount_trx,
'duration_days': duration_days,
'estimated_rewards': round(rewards, 6),
'apr': f"{annual_apr * 100:.2f}%",
'daily_rewards': round(amount_trx * daily_rate, 6),
'monthly_rewards': round(amount_trx * daily_rate * 30, 6),
'yearly_rewards': round(amount_trx * annual_apr, 6)
}
class ResourceCalculator:
"""
Calculate resource requirements and recommendations
"""
def __init__(self):
self.rates = {
'bandwidth': {
'per_trx': 1000, # Bandwidth per TRX
'per_transaction': 250 # Average bandwidth per tx
},
'energy': {
'per_trx': 280, # Energy per TRX
'per_contract_call': 50000 # Average energy per call
}
}
def calculate_required_trx(
self,
resource_type: str,
amount: int
) -> int:
"""
Calculate TRX needed for specific resource amount
"""
resource_type = resource_type.upper()
if resource_type == 'BANDWIDTH':
return (amount + self.rates['bandwidth']['per_trx'] - 1) // \
self.rates['bandwidth']['per_trx']
elif resource_type == 'ENERGY':
return (amount + self.rates['energy']['per_trx'] - 1) // \
self.rates['energy']['per_trx']
else:
raise ValueError(f"Invalid resource type: {resource_type}")
def estimate_resources_from_trx(
self,
trx_amount: float,
resource_type: str
) -> Dict:
"""
Estimate resources obtained from TRX amount
"""
resource_type = resource_type.upper()
if resource_type == 'BANDWIDTH':
bandwidth = int(trx_amount * self.rates['bandwidth']['per_trx'])
return {
'bandwidth': bandwidth,
'estimated_transactions': bandwidth // \
self.rates['bandwidth']['per_transaction']
}
elif resource_type == 'ENERGY':
energy = int(trx_amount * self.rates['energy']['per_trx'])
return {
'energy': energy,
'estimated_contract_calls': energy // \
self.rates['energy']['per_contract_call']
}
else:
raise ValueError(f"Invalid resource type: {resource_type}")
def get_recommendation(
self,
daily_transactions: int,
daily_contract_calls: int
) -> Dict:
"""
Get staking recommendation based on usage
"""
bandwidth_needed = daily_transactions * \
self.rates['bandwidth']['per_transaction']
energy_needed = daily_contract_calls * \
self.rates['energy']['per_contract_call']
bandwidth_trx = self.calculate_required_trx('BANDWIDTH', bandwidth_needed)
energy_trx = self.calculate_required_trx('ENERGY', energy_needed)
return {
'bandwidth': {
'daily_requirement': bandwidth_needed,
'trx_to_stake': bandwidth_trx,
'daily_transactions': daily_transactions
},
'energy': {
'daily_requirement': energy_needed,
'trx_to_stake': energy_trx,
'daily_contract_calls': daily_contract_calls
},
'total': {
'trx_required': bandwidth_trx + energy_trx,
'monthly_trx': (bandwidth_trx + energy_trx) * 30,
'yearly_trx': (bandwidth_trx + energy_trx) * 365
}
}
class StakingMonitor:
"""
Monitor and analyze staking positions
"""
def __init__(self, api_key: str):
self.staking = TronStakingManager(api_key)
self.calculator = ResourceCalculator()
def analyze_account(self, address: str) -> Dict:
"""
Analyze account staking status
"""
resources = self.staking.get_account_resource(address)
# Calculate utilization
bandwidth_used = resources.get('freeNetUsed', 0) + \
resources.get('NetUsed', 0)
bandwidth_limit = resources.get('freeNetLimit', 0) + \
resources.get('NetLimit', 0)
energy_used = resources.get('EnergyUsed', 0)
energy_limit = resources.get('EnergyLimit', 0)
bandwidth_utilization = (bandwidth_used / bandwidth_limit * 100) \
if bandwidth_limit > 0 else 0
energy_utilization = (energy_used / energy_limit * 100) \
if energy_limit > 0 else 0
return {
'address': address,
'bandwidth': {
'used': bandwidth_used,
'limit': bandwidth_limit,
'available': max(0, bandwidth_limit - bandwidth_used),
'utilization': f"{bandwidth_utilization:.2f}%"
},
'energy': {
'used': energy_used,
'limit': energy_limit,
'available': max(0, energy_limit - energy_used),
'utilization': f"{energy_utilization:.2f}%"
},
'recommendations': self._get_recommendations(
bandwidth_utilization,
energy_utilization
)
}
def _get_recommendations(
self,
bandwidth_util: float,
energy_util: float
) -> List[str]:
"""
Get staking recommendations based on utilization
"""
recommendations = []
if bandwidth_util > 80:
recommendations.append("High bandwidth usage - consider staking more TRX for bandwidth")
elif bandwidth_util < 20:
recommendations.append("Low bandwidth usage - you may have excess staked for bandwidth")
if energy_util > 80:
recommendations.append("High energy usage - consider staking more TRX for energy")
elif energy_util < 20:
recommendations.append("Low energy usage - you may have excess staked for energy")
if not recommendations:
recommendations.append("Resource usage is balanced")
return recommendations
# Usage examples
if __name__ == "__main__":
# Initialize managers
staking = TronStakingManager('YOUR_API_KEY')
calculator = ResourceCalculator()
monitor = StakingMonitor('YOUR_API_KEY')
try:
# Get staking recommendation
recommendation = calculator.get_recommendation(
daily_transactions=100,
daily_contract_calls=50
)
print("Staking Recommendation:")
print(json.dumps(recommendation, indent=2))
# Estimate rewards
rewards = staking.estimate_staking_rewards(
amount_trx=10000,
duration_days=365
)
print("\nEstimated Rewards:")
print(json.dumps(rewards, indent=2))
# Calculate optimal stake
optimal = staking.calculate_optimal_stake(
'TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN',
daily_operations=100
)
print("\nOptimal Stake:")
print(json.dumps(optimal, indent=2))
# Analyze account
analysis = monitor.analyze_account('TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN')
print("\nAccount Analysis:")
print(json.dumps(analysis, indent=2))
# Create stake transaction
stake_tx = staking.stake_trx(
'TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN',
amount_trx=1000,
resource='ENERGY'
)
print("\nStake Transaction Created:")
print(json.dumps(stake_tx, indent=2))
except Exception as e:
print(f"Error: {e}")
# Freeze TRX for ENERGY
curl -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/freezebalancev2" \
-H "Content-Type: application/json" \
-d '{
"owner_address": "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN",
"frozen_balance": 10000000000,
"resource": "ENERGY",
"visible": true
}'
# Freeze TRX for BANDWIDTH
curl -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/freezebalancev2" \
-H "Content-Type: application/json" \
-d '{
"owner_address": "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN",
"frozen_balance": 5000000000,
"resource": "BANDWIDTH",
"visible": true
}'
# Parse response with jq
curl -s -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/freezebalancev2" \
-H "Content-Type: application/json" \
-d '{
"owner_address": "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN",
"frozen_balance": 10000000000,
"resource": "ENERGY",
"visible": true
}' | jq '{
txid: .txid,
resource: .raw_data.contract[0].parameter.value.resource,
amount_sun: .raw_data.contract[0].parameter.value.frozen_balance,
amount_trx: (.raw_data.contract[0].parameter.value.frozen_balance / 1000000),
expiration: .raw_data.expiration
}'
# Script to calculate and stake optimal amounts
#!/bin/bash
API_KEY="YOUR_API_KEY"
ADDRESS="TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN"
# Function to stake TRX
stake_trx() {
local amount_sun=$1
local resource=$2
echo "Staking $((amount_sun / 1000000)) TRX for $resource..."
response=$(curl -s -X POST \
"https://api-tron-mainnet.n.dwellir.com/$API_KEY/wallet/freezebalancev2" \
-H "Content-Type: application/json" \
-d "{
\"owner_address\": \"$ADDRESS\",
\"frozen_balance\": $amount_sun,
\"resource\": \"$resource\",
\"visible\": true
}")
txid=$(echo "$response" | jq -r '.txid')
if [ "$txid" != "null" ]; then
echo "✓ Transaction created: $txid"
echo " Please sign and broadcast this transaction"
else
echo "✗ Failed to create transaction"
echo "$response" | jq .
fi
}
# Calculate resources needed
echo "=== Resource Staking Calculator ==="
echo
read -p "Daily transactions expected: " daily_tx
read -p "Daily smart contract calls expected: " daily_contracts
# Calculate requirements (approximate)
bandwidth_needed=$((daily_tx * 250))
energy_needed=$((daily_contracts * 50000))
trx_for_bandwidth=$((bandwidth_needed / 1000))
trx_for_energy=$((energy_needed / 280))
echo
echo "Resource Requirements:"
echo " Bandwidth needed: $bandwidth_needed"
echo " Energy needed: $energy_needed"
echo
echo "TRX to stake:"
echo " For Bandwidth: $trx_for_bandwidth TRX"
echo " For Energy: $trx_for_energy TRX"
echo " Total: $((trx_for_bandwidth + trx_for_energy)) TRX"
echo
read -p "Proceed with staking? (y/n): " confirm
if [ "$confirm" = "y" ]; then
# Convert to SUN and stake
stake_trx $((trx_for_bandwidth * 1000000)) "BANDWIDTH"
sleep 2
stake_trx $((trx_for_energy * 1000000)) "ENERGY"
fi
Response Example
Successful Response
{
"visible": true,
"txID": "7a2e5c8f9b3d1a4e6f8c2b5d9e1a3f7c4b8d2e6a9c3f5b8d1e4a7c9f2b5d8e",
"raw_data": {
"contract": [
{
"parameter": {
"value": {
"owner_address": "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN",
"frozen_balance": 10000000000,
"resource": "ENERGY"
},
"type_url": "type.googleapis.com/protocol.FreezeBalanceV2Contract"
},
"type": "FreezeBalanceV2Contract"
}
],
"ref_block_bytes": "7ac7",
"ref_block_hash": "4d9bb8f8c9c59ac3",
"expiration": 1702456849000,
"timestamp": 1702456789000,
"fee_limit": 1000000000
},
"raw_data_hex": "0a0207ac722..."
}
Common Use Cases
1. Auto-Staking System
class AutoStakingSystem {
constructor(apiKey) {
this.staking = new TronStakingManager(apiKey);
this.minBalance = 1000; // Minimum TRX to keep unstaked
}
async autoStake(address, keepBalance = 1000) {
// Get current balance
const account = await this.getAccount(address);
const availableTRX = (account.balance / 1_000_000) - keepBalance;
if (availableTRX <= 0) {
return { message: 'Insufficient balance for staking' };
}
// Split 30% bandwidth, 70% energy (typical DApp usage)
const bandwidthTRX = Math.floor(availableTRX * 0.3);
const energyTRX = Math.floor(availableTRX * 0.7);
return await this.staking.stakeForResources(
address,
bandwidthTRX,
energyTRX
);
}
}
2. Resource Optimization
async function optimizeResources(address) {
const resources = await getAccountResource(address);
// Check utilization
const bandwidthUtil = resources.freeNetUsed / resources.freeNetLimit;
const energyUtil = resources.EnergyUsed / resources.EnergyLimit;
const recommendations = [];
if (bandwidthUtil > 0.8) {
recommendations.push({
action: 'STAKE',
resource: 'BANDWIDTH',
reason: 'High bandwidth utilization',
suggestedTRX: 1000
});
}
if (energyUtil > 0.8) {
recommendations.push({
action: 'STAKE',
resource: 'ENERGY',
reason: 'High energy utilization',
suggestedTRX: 5000
});
}
return recommendations;
}
3. Staking Pool Management
class StakingPool {
async distributeStakes(participants, totalTRX) {
const stakes = [];
for (const participant of participants) {
const share = (participant.contribution / 100) * totalTRX;
stakes.push({
address: participant.address,
amount: share,
resource: participant.preferredResource || 'ENERGY'
});
}
return this.executeStakes(stakes);
}
}
Resource Calculation
Resource | Rate | Usage |
---|---|---|
Bandwidth | ~1,000 per TRX | Regular transactions |
Energy | ~280 per TRX | Smart contract calls |
Voting Power | 1 vote per TRX | SR voting |
Staking Recommendations by Use Case
Use Case | Bandwidth (TRX) | Energy (TRX) | Total |
---|---|---|---|
Basic Wallet | 100 | 0 | 100 |
DeFi User | 500 | 5,000 | 5,500 |
DApp Developer | 1,000 | 20,000 | 21,000 |
Exchange | 10,000 | 50,000 | 60,000 |
Error Handling
Error Code | Description | Solution |
---|---|---|
INVALID_RESOURCE | Invalid resource type | Use "BANDWIDTH" or "ENERGY" |
INSUFFICIENT_BALANCE | Not enough TRX | Check balance before staking |
ACCOUNT_NOT_FOUND | Address doesn't exist | Verify address validity |
TAPOS_ERROR | Transaction expired | Recreate with fresh block reference |
async function safeStake(address, amount, resource) {
try {
// Check balance first
const account = await getAccount(address);
const balance = account.balance / 1_000_000;
if (balance < amount) {
throw new Error(`Insufficient balance: ${balance} TRX available`);
}
// Validate resource type
if (!['BANDWIDTH', 'ENERGY'].includes(resource)) {
throw new Error(`Invalid resource: ${resource}`);
}
// Create and return transaction
return await createFreezeTransaction(address, amount, resource);
} catch (error) {
console.error('Staking error:', error);
return {
success: false,
error: error.message
};
}
}
Best Practices
- Keep Reserve - Always keep 50-100 TRX unstaked for fees
- Balance Resources - Monitor usage and adjust stakes accordingly
- Batch Operations - Stake for both resources in one session
- Monitor Rewards - Track staking rewards and compound regularly
- Plan Unstaking - Remember 14-day waiting period for unstaking
Notes
- Lock Period: Staked TRX has a minimum 14-day lock period
- Rewards: Staking rewards are distributed every 6 hours
- Voting Power: Staked TRX provides voting power for Super Representatives
- Resource Recovery: Bandwidth recovers 24 hours, energy recovers based on consumption
Related Methods
- wallet/unfreezebalancev2 - Unstake TRX
- wallet/delegateresource - Delegate resources
- wallet/getaccountresource - Check resources
Need help? Contact support or visit our TRON documentation.