wallet/estimateenergy
Optimize Smart Contract Costs
Dwellir's TRON endpoints provide accurate energy estimation to help you optimize smart contract execution costs. Plan your transactions and avoid energy shortfalls with precise cost forecasting.
Estimates the energy consumption required for executing a smart contract call on the TRON network. Essential for cost planning and resource management.
When to Use This Method
wallet/estimateenergy
is essential for:
- Cost Planning - Estimate transaction costs before execution
- Resource Management - Plan energy requirements for smart contracts
- User Interfaces - Display estimated costs to users
- Batch Operations - Calculate total energy needed for multiple calls
- Energy Optimization - Compare different execution strategies
Parameters
-
owner_address -
string
(required)- Address that will execute the contract call
- Example:
"TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh"
-
contract_address -
string
(required)- Smart contract address to call
- Example:
"TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
(USDT)
-
function_selector -
string
(required)- Function signature to estimate
- Example:
"transfer(address,uint256)"
-
parameter -
string
(optional)- Hex-encoded function parameters
- Example:
"0000000000000000000000004142b5e01c8c59a25d78acdbec2bfc7e89e5e86300000000000000000000000000000000000000000000000000000000000f4240"
-
call_value -
integer
(optional)- TRX amount to send (in SUN) for payable functions
- Default:
0
-
visible -
boolean
(optional, default: false)true
- Use Base58 address formatfalse
- Use hex address format
{
"owner_address": "TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh",
"contract_address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
"function_selector": "transfer(address,uint256)",
"parameter": "0000000000000000000000004142b5e01c8c59a25d78acdbec2bfc7e89e5e86300000000000000000000000000000000000000000000000000000000000f4240",
"visible": true
}
Returns
Energy Estimation containing:
energy_required
- Estimated energy consumptionresult
- Execution success/failure simulationenergy_used
- Base energy used for calculation
Implementation Examples
- JavaScript
- Python
- cURL
const TRON_API = 'https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY';
// Estimate energy for smart contract call
async function estimateEnergy(ownerAddress, contractAddress, functionSelector, parameters = '', callValue = 0) {
const response = await fetch(`${TRON_API}/wallet/estimateenergy`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
owner_address: ownerAddress,
contract_address: contractAddress,
function_selector: functionSelector,
parameter: parameters,
call_value: callValue,
visible: true
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
}
// Energy estimation and cost calculator
class TronEnergyEstimator {
constructor(apiKey) {
this.apiKey = apiKey;
this.apiUrl = `https://api-tron-mainnet.n.dwellir.com/${apiKey}`;
// Energy costs (approximate rates)
this.energyCostPerUnit = 0.00014; // TRX per energy unit (variable)
this.sunPerTrx = 1_000_000;
}
async estimateContractCall(ownerAddress, contractAddress, functionSelector, parameters = '', callValue = 0) {
try {
const estimation = await this.estimateEnergy(ownerAddress, contractAddress, functionSelector, parameters, callValue);
const energyRequired = estimation.energy_required || 0;
const willSucceed = estimation.result?.result !== false;
return {
success: true,
energyRequired,
willSucceed,
estimatedCostTRX: this.calculateCostInTRX(energyRequired),
estimatedCostSUN: this.calculateCostInSUN(energyRequired),
canExecuteForFree: await this.canExecuteForFree(ownerAddress, energyRequired),
recommendation: await this.generateRecommendation(ownerAddress, energyRequired),
rawEstimation: estimation
};
} catch (error) {
return {
success: false,
error: error.message,
energyRequired: 0,
estimatedCostTRX: 0
};
}
}
async estimateEnergy(ownerAddress, contractAddress, functionSelector, parameters, callValue) {
const response = await fetch(`${this.apiUrl}/wallet/estimateenergy`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
owner_address: ownerAddress,
contract_address: contractAddress,
function_selector: functionSelector,
parameter: parameters,
call_value: callValue,
visible: true
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
}
calculateCostInTRX(energyRequired) {
return energyRequired * this.energyCostPerUnit;
}
calculateCostInSUN(energyRequired) {
return Math.floor(energyRequired * this.energyCostPerUnit * this.sunPerTrx);
}
async canExecuteForFree(ownerAddress, energyRequired) {
try {
// Check if user has enough energy staked
const resourceResponse = await fetch(`${this.apiUrl}/wallet/getaccountresource`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ address: ownerAddress, visible: true })
});
const resources = await resourceResponse.json();
const availableEnergy = (resources.EnergyLimit || 0) - (resources.EnergyUsed || 0);
return availableEnergy >= energyRequired;
} catch (error) {
console.warn('Could not check energy availability:', error);
return false;
}
}
async generateRecommendation(ownerAddress, energyRequired) {
const canExecuteForFree = await this.canExecuteForFree(ownerAddress, energyRequired);
const costTRX = this.calculateCostInTRX(energyRequired);
if (canExecuteForFree) {
return {
type: 'success',
message: 'Transaction can execute for free using staked energy',
action: 'Proceed with transaction'
};
} else if (costTRX < 1) {
return {
type: 'low_cost',
message: `Transaction will cost ${costTRX.toFixed(6)} TRX`,
action: 'Consider proceeding with TRX payment'
};
} else if (costTRX < 10) {
return {
type: 'moderate_cost',
message: `Transaction will cost ${costTRX.toFixed(3)} TRX`,
action: 'Consider staking TRX for energy to reduce costs'
};
} else {
return {
type: 'high_cost',
message: `High cost: ${costTRX.toFixed(2)} TRX`,
action: 'Strongly recommend staking TRX for energy or renting energy'
};
}
}
// Estimate energy for common contract operations
async estimateCommonOperations(ownerAddress, contractAddress) {
const operations = [
{ name: 'Transfer TRC20', selector: 'transfer(address,uint256)', params: this.encodeTransferParams('TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN', 1000000) },
{ name: 'Approve TRC20', selector: 'approve(address,uint256)', params: this.encodeApprovalParams('TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN', 1000000) },
{ name: 'Get Balance', selector: 'balanceOf(address)', params: this.encodeAddressParam('TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN') }
];
const estimates = [];
for (const op of operations) {
try {
const estimate = await this.estimateContractCall(
ownerAddress,
contractAddress,
op.selector,
op.params
);
estimates.push({
operation: op.name,
...estimate
});
} catch (error) {
estimates.push({
operation: op.name,
success: false,
error: error.message,
energyRequired: 0
});
}
}
return estimates;
}
// Parameter encoding helpers
encodeAddressParam(address) {
// Simplified encoding - use proper library in production
return '0000000000000000000000004142b5e01c8c59a25d78acdbec2bfc7e89e5e863';
}
encodeTransferParams(toAddress, amount) {
// Simplified encoding for transfer(address,uint256)
const addressParam = this.encodeAddressParam(toAddress);
const amountParam = amount.toString(16).padStart(64, '0');
return addressParam + amountParam;
}
encodeApprovalParams(spenderAddress, amount) {
// Same as transfer params for approve(address,uint256)
return this.encodeTransferParams(spenderAddress, amount);
}
}
// Batch energy estimation for multiple operations
class TronBatchEnergyEstimator {
constructor(apiKey) {
this.estimator = new TronEnergyEstimator(apiKey);
}
async estimateBatchOperations(operations) {
const results = [];
let totalEnergyRequired = 0;
let totalCostTRX = 0;
let allWillSucceed = true;
for (const op of operations) {
try {
const estimate = await this.estimator.estimateContractCall(
op.ownerAddress,
op.contractAddress,
op.functionSelector,
op.parameters || '',
op.callValue || 0
);
results.push({
operation: op.name || 'Unknown',
...estimate
});
if (estimate.success) {
totalEnergyRequired += estimate.energyRequired;
totalCostTRX += estimate.estimatedCostTRX;
allWillSucceed = allWillSucceed && estimate.willSucceed;
}
} catch (error) {
results.push({
operation: op.name || 'Unknown',
success: false,
error: error.message
});
allWillSucceed = false;
}
}
return {
operations: results,
summary: {
totalOperations: operations.length,
successfulEstimations: results.filter(r => r.success).length,
totalEnergyRequired,
totalCostTRX,
totalCostSUN: Math.floor(totalCostTRX * 1_000_000),
allWillSucceed,
averageEnergyPerOperation: totalEnergyRequired / operations.length
}
};
}
}
// Energy optimization advisor
class TronEnergyOptimizer {
constructor(apiKey) {
this.estimator = new TronEnergyEstimator(apiKey);
}
async analyzeEnergyStrategy(ownerAddress, plannedOperations) {
const batchEstimator = new TronBatchEnergyEstimator(this.apiKey);
const estimates = await batchEstimator.estimateBatchOperations(plannedOperations);
const totalEnergyNeeded = estimates.summary.totalEnergyRequired;
const totalCostTRX = estimates.summary.totalCostTRX;
// Get current energy resources
const canExecuteForFree = await this.estimator.canExecuteForFree(ownerAddress, totalEnergyNeeded);
const strategies = [
{
name: 'Pay with TRX',
cost: totalCostTRX,
description: `Pay ${totalCostTRX.toFixed(6)} TRX for energy`,
pros: ['No upfront staking required', 'Immediate execution'],
cons: ['Higher cost per transaction', 'No reusable energy']
},
{
name: 'Stake TRX for Energy',
cost: totalEnergyNeeded / 4000, // Approximate staking ratio
description: `Stake ~${(totalEnergyNeeded / 4000).toFixed(2)} TRX for energy`,
pros: ['Reusable energy', 'Lower long-term costs', 'Supports network'],
cons: ['TRX locked for 3 days', 'Upfront capital required']
},
{
name: 'Rent Energy',
cost: totalCostTRX * 0.7, // Assume 30% savings
description: `Rent energy for ~${(totalCostTRX * 0.7).toFixed(6)} TRX`,
pros: ['Lower cost than direct payment', 'No long-term commitment'],
cons: ['One-time use', 'Requires third-party platform']
}
];
// Sort strategies by cost
strategies.sort((a, b) => a.cost - b.cost);
return {
analysis: {
totalEnergyNeeded,
totalCostTRX,
canExecuteForFree,
operationCount: plannedOperations.length
},
strategies,
recommendation: canExecuteForFree ?
'Use existing staked energy - execution will be free' :
strategies[0].name, // Cheapest strategy
operationDetails: estimates
};
}
}
// Usage examples
(async () => {
try {
const estimator = new TronEnergyEstimator('YOUR_API_KEY');
// Estimate single operation
const estimate = await estimator.estimateContractCall(
'TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh',
'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t', // USDT
'transfer(address,uint256)',
estimator.encodeTransferParams('TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN', 1000000)
);
console.log('Energy Estimate:', estimate.energyRequired);
console.log('Cost:', estimate.estimatedCostTRX, 'TRX');
console.log('Can execute for free:', estimate.canExecuteForFree);
// Batch estimation
const batchEstimator = new TronBatchEnergyEstimator('YOUR_API_KEY');
const operations = [
{
name: 'USDT Transfer',
ownerAddress: 'TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh',
contractAddress: 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
functionSelector: 'transfer(address,uint256)',
parameters: estimator.encodeTransferParams('TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN', 1000000)
}
];
const batchResults = await batchEstimator.estimateBatchOperations(operations);
console.log('Batch total energy:', batchResults.summary.totalEnergyRequired);
// Energy optimization analysis
const optimizer = new TronEnergyOptimizer('YOUR_API_KEY');
const strategy = await optimizer.analyzeEnergyStrategy('TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh', operations);
console.log('Recommended strategy:', strategy.recommendation);
console.log('Best option cost:', strategy.strategies[0].cost, 'TRX');
} catch (error) {
console.error('Error:', error);
}
})();
import requests
import json
from typing import Dict, List, Optional
class TronEnergyEstimator:
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'
}
# Energy costs (approximate rates)
self.energy_cost_per_unit = 0.00014 # TRX per energy unit
self.sun_per_trx = 1_000_000
def estimate_energy(self, owner_address: str, contract_address: str,
function_selector: str, parameters: str = '', call_value: int = 0) -> Dict:
"""Estimate energy for smart contract call"""
url = f"{self.base_url}/wallet/estimateenergy"
payload = {
"owner_address": owner_address,
"contract_address": contract_address,
"function_selector": function_selector,
"parameter": parameters,
"call_value": call_value,
"visible": True
}
response = requests.post(url, headers=self.headers, json=payload)
response.raise_for_status()
return response.json()
def estimate_contract_call(self, owner_address: str, contract_address: str,
function_selector: str, parameters: str = '', call_value: int = 0) -> Dict:
"""Estimate contract call with cost analysis"""
try:
estimation = self.estimate_energy(owner_address, contract_address, function_selector, parameters, call_value)
energy_required = estimation.get('energy_required', 0)
will_succeed = estimation.get('result', {}).get('result', True)
return {
'success': True,
'energy_required': energy_required,
'will_succeed': will_succeed,
'estimated_cost_trx': self.calculate_cost_in_trx(energy_required),
'estimated_cost_sun': self.calculate_cost_in_sun(energy_required),
'can_execute_for_free': self.can_execute_for_free(owner_address, energy_required),
'recommendation': self.generate_recommendation(owner_address, energy_required),
'raw_estimation': estimation
}
except Exception as e:
return {
'success': False,
'error': str(e),
'energy_required': 0,
'estimated_cost_trx': 0
}
def calculate_cost_in_trx(self, energy_required: int) -> float:
"""Calculate cost in TRX"""
return energy_required * self.energy_cost_per_unit
def calculate_cost_in_sun(self, energy_required: int) -> int:
"""Calculate cost in SUN"""
return int(energy_required * self.energy_cost_per_unit * self.sun_per_trx)
def can_execute_for_free(self, owner_address: str, energy_required: int) -> bool:
"""Check if user has enough staked energy"""
try:
url = f"{self.base_url}/wallet/getaccountresource"
response = requests.post(url, headers=self.headers, json={
"address": owner_address,
"visible": True
})
resources = response.json()
available_energy = (resources.get('EnergyLimit', 0) - resources.get('EnergyUsed', 0))
return available_energy >= energy_required
except Exception:
return False
def generate_recommendation(self, owner_address: str, energy_required: int) -> Dict:
"""Generate recommendation based on energy needs"""
can_execute_for_free = self.can_execute_for_free(owner_address, energy_required)
cost_trx = self.calculate_cost_in_trx(energy_required)
if can_execute_for_free:
return {
'type': 'success',
'message': 'Transaction can execute for free using staked energy',
'action': 'Proceed with transaction'
}
elif cost_trx < 1:
return {
'type': 'low_cost',
'message': f'Transaction will cost {cost_trx:.6f} TRX',
'action': 'Consider proceeding with TRX payment'
}
elif cost_trx < 10:
return {
'type': 'moderate_cost',
'message': f'Transaction will cost {cost_trx:.3f} TRX',
'action': 'Consider staking TRX for energy to reduce costs'
}
else:
return {
'type': 'high_cost',
'message': f'High cost: {cost_trx:.2f} TRX',
'action': 'Strongly recommend staking TRX for energy or renting energy'
}
def estimate_common_operations(self, owner_address: str, contract_address: str) -> List[Dict]:
"""Estimate energy for common contract operations"""
operations = [
{
'name': 'Transfer TRC20',
'selector': 'transfer(address,uint256)',
'params': self.encode_transfer_params('TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN', 1000000)
},
{
'name': 'Approve TRC20',
'selector': 'approve(address,uint256)',
'params': self.encode_approval_params('TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN', 1000000)
},
{
'name': 'Get Balance',
'selector': 'balanceOf(address)',
'params': self.encode_address_param('TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN')
}
]
estimates = []
for op in operations:
try:
estimate = self.estimate_contract_call(
owner_address,
contract_address,
op['selector'],
op['params']
)
estimate['operation'] = op['name']
estimates.append(estimate)
except Exception as e:
estimates.append({
'operation': op['name'],
'success': False,
'error': str(e),
'energy_required': 0
})
return estimates
# Parameter encoding helpers (simplified)
def encode_address_param(self, address: str) -> str:
"""Encode address parameter"""
# Simplified encoding - use proper library in production
return '0000000000000000000000004142b5e01c8c59a25d78acdbec2bfc7e89e5e863'
def encode_transfer_params(self, to_address: str, amount: int) -> str:
"""Encode transfer parameters"""
address_param = self.encode_address_param(to_address)
amount_param = format(amount, '064x')
return address_param + amount_param
def encode_approval_params(self, spender_address: str, amount: int) -> str:
"""Encode approval parameters"""
return self.encode_transfer_params(spender_address, amount)
class TronBatchEnergyEstimator:
def __init__(self, api_key: str):
self.estimator = TronEnergyEstimator(api_key)
def estimate_batch_operations(self, operations: List[Dict]) -> Dict:
"""Estimate energy for multiple operations"""
results = []
total_energy_required = 0
total_cost_trx = 0
all_will_succeed = True
for op in operations:
try:
estimate = self.estimator.estimate_contract_call(
op['owner_address'],
op['contract_address'],
op['function_selector'],
op.get('parameters', ''),
op.get('call_value', 0)
)
estimate['operation'] = op.get('name', 'Unknown')
results.append(estimate)
if estimate['success']:
total_energy_required += estimate['energy_required']
total_cost_trx += estimate['estimated_cost_trx']
all_will_succeed = all_will_succeed and estimate['will_succeed']
except Exception as e:
results.append({
'operation': op.get('name', 'Unknown'),
'success': False,
'error': str(e)
})
all_will_succeed = False
return {
'operations': results,
'summary': {
'total_operations': len(operations),
'successful_estimations': len([r for r in results if r.get('success')]),
'total_energy_required': total_energy_required,
'total_cost_trx': total_cost_trx,
'total_cost_sun': int(total_cost_trx * 1_000_000),
'all_will_succeed': all_will_succeed,
'average_energy_per_operation': total_energy_required / len(operations) if operations else 0
}
}
class TronEnergyOptimizer:
def __init__(self, api_key: str):
self.estimator = TronEnergyEstimator(api_key)
def analyze_energy_strategy(self, owner_address: str, planned_operations: List[Dict]) -> Dict:
"""Analyze optimal energy strategy for planned operations"""
batch_estimator = TronBatchEnergyEstimator(self.estimator.api_key)
estimates = batch_estimator.estimate_batch_operations(planned_operations)
total_energy_needed = estimates['summary']['total_energy_required']
total_cost_trx = estimates['summary']['total_cost_trx']
can_execute_for_free = self.estimator.can_execute_for_free(owner_address, total_energy_needed)
strategies = [
{
'name': 'Pay with TRX',
'cost': total_cost_trx,
'description': f'Pay {total_cost_trx:.6f} TRX for energy',
'pros': ['No upfront staking required', 'Immediate execution'],
'cons': ['Higher cost per transaction', 'No reusable energy']
},
{
'name': 'Stake TRX for Energy',
'cost': total_energy_needed / 4000, # Approximate staking ratio
'description': f'Stake ~{total_energy_needed / 4000:.2f} TRX for energy',
'pros': ['Reusable energy', 'Lower long-term costs', 'Supports network'],
'cons': ['TRX locked for 3 days', 'Upfront capital required']
},
{
'name': 'Rent Energy',
'cost': total_cost_trx * 0.7, # Assume 30% savings
'description': f'Rent energy for ~{total_cost_trx * 0.7:.6f} TRX',
'pros': ['Lower cost than direct payment', 'No long-term commitment'],
'cons': ['One-time use', 'Requires third-party platform']
}
]
# Sort strategies by cost
strategies.sort(key=lambda x: x['cost'])
return {
'analysis': {
'total_energy_needed': total_energy_needed,
'total_cost_trx': total_cost_trx,
'can_execute_for_free': can_execute_for_free,
'operation_count': len(planned_operations)
},
'strategies': strategies,
'recommendation': 'Use existing staked energy - execution will be free' if can_execute_for_free else strategies[0]['name'],
'operation_details': estimates
}
# Usage examples
if __name__ == "__main__":
estimator = TronEnergyEstimator('YOUR_API_KEY')
try:
# Estimate single operation
estimate = estimator.estimate_contract_call(
'TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh',
'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t', # USDT
'transfer(address,uint256)',
estimator.encode_transfer_params('TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN', 1000000)
)
print(f"Energy Estimate: {estimate['energy_required']}")
print(f"Cost: {estimate['estimated_cost_trx']} TRX")
print(f"Can execute for free: {estimate['can_execute_for_free']}")
print(f"Recommendation: {estimate['recommendation']['message']}")
# Batch estimation
batch_estimator = TronBatchEnergyEstimator('YOUR_API_KEY')
operations = [
{
'name': 'USDT Transfer',
'owner_address': 'TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh',
'contract_address': 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
'function_selector': 'transfer(address,uint256)',
'parameters': estimator.encode_transfer_params('TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN', 1000000)
}
]
batch_results = batch_estimator.estimate_batch_operations(operations)
print(f"\nBatch total energy: {batch_results['summary']['total_energy_required']}")
print(f"Total cost: {batch_results['summary']['total_cost_trx']} TRX")
# Energy optimization analysis
optimizer = TronEnergyOptimizer('YOUR_API_KEY')
strategy = optimizer.analyze_energy_strategy('TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh', operations)
print(f"\nRecommended strategy: {strategy['recommendation']}")
print(f"Best option cost: {strategy['strategies'][0]['cost']} TRX")
print(f"Description: {strategy['strategies'][0]['description']}")
except Exception as e:
print(f"Error: {e}")
# Estimate energy for TRC20 transfer
curl -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/estimateenergy" \
-H "Content-Type: application/json" \
-d '{
"owner_address": "TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh",
"contract_address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
"function_selector": "transfer(address,uint256)",
"parameter": "0000000000000000000000004142b5e01c8c59a25d78acdbec2bfc7e89e5e86300000000000000000000000000000000000000000000000000000000000f4240",
"visible": true
}'
# Extract energy estimation and calculate cost
curl -s -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/estimateenergy" \
-H "Content-Type: application/json" \
-d '{
"owner_address": "TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh",
"contract_address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
"function_selector": "transfer(address,uint256)",
"parameter": "0000000000000000000000004142b5e01c8c59a25d78acdbec2bfc7e89e5e86300000000000000000000000000000000000000000000000000000000000f4240",
"visible": true
}' | jq '{
energy_required: .energy_required,
will_succeed: .result.result,
estimated_cost_trx: (.energy_required * 0.00014),
estimated_cost_sun: (.energy_required * 0.00014 * 1000000 | floor)
}'
# Batch energy estimation script
#!/bin/bash
API_KEY="YOUR_API_KEY"
OWNER_ADDRESS="TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh"
# Function to estimate energy
estimate_energy() {
local contract_address=$1
local function_selector=$2
local parameters=$3
local call_value=${4:-0}
curl -s -X POST "https://api-tron-mainnet.n.dwellir.com/$API_KEY/wallet/estimateenergy" \
-H "Content-Type: application/json" \
-d "{
\"owner_address\": \"$OWNER_ADDRESS\",
\"contract_address\": \"$contract_address\",
\"function_selector\": \"$function_selector\",
\"parameter\": \"$parameters\",
\"call_value\": $call_value,
\"visible\": true
}"
}
# Function to calculate costs
calculate_costs() {
local energy_required=$1
local energy_cost_per_unit=0.00014
local cost_trx=$(echo "scale=8; $energy_required * $energy_cost_per_unit" | bc -l)
local cost_sun=$(echo "scale=0; $cost_trx * 1000000 / 1" | bc -l)
echo "Energy required: $energy_required"
echo "Cost in TRX: $cost_trx"
echo "Cost in SUN: $cost_sun"
}
# Function to check if execution can be free
check_free_execution() {
local address=$1
local energy_needed=$2
local resources=$(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}")
local energy_limit=$(echo "$resources" | jq -r '.EnergyLimit // 0')
local energy_used=$(echo "$resources" | jq -r '.EnergyUsed // 0')
local available_energy=$((energy_limit - energy_used))
if [ "$available_energy" -ge "$energy_needed" ]; then
echo "✅ Can execute for free using staked energy"
echo "Available energy: $available_energy"
else
echo "❌ Insufficient staked energy"
echo "Available: $available_energy, Needed: $energy_needed"
echo "Shortfall: $((energy_needed - available_energy))"
fi
}
# Estimate common operations
estimate_common_operations() {
local contract_address=$1
echo "=== Energy Estimation for Common Operations ==="
echo "Contract: $contract_address"
echo "Owner: $OWNER_ADDRESS"
echo ""
# TRC20 Transfer
echo "1. TRC20 Transfer"
local transfer_params="0000000000000000000000004142b5e01c8c59a25d78acdbec2bfc7e89e5e86300000000000000000000000000000000000000000000000000000000000f4240"
local transfer_result=$(estimate_energy "$contract_address" "transfer(address,uint256)" "$transfer_params")
local transfer_energy=$(echo "$transfer_result" | jq -r '.energy_required // 0')
calculate_costs "$transfer_energy"
check_free_execution "$OWNER_ADDRESS" "$transfer_energy"
echo ""
# TRC20 Approve
echo "2. TRC20 Approve"
local approve_result=$(estimate_energy "$contract_address" "approve(address,uint256)" "$transfer_params")
local approve_energy=$(echo "$approve_result" | jq -r '.energy_required // 0')
calculate_costs "$approve_energy"
check_free_execution "$OWNER_ADDRESS" "$approve_energy"
echo ""
# Balance query (view function)
echo "3. Balance Query (view function)"
local balance_params="0000000000000000000000004142b5e01c8c59a25d78acdbec2bfc7e89e5e863"
local balance_result=$(estimate_energy "$contract_address" "balanceOf(address)" "$balance_params")
local balance_energy=$(echo "$balance_result" | jq -r '.energy_required // 0')
calculate_costs "$balance_energy"
echo ""
# Summary
local total_energy=$((transfer_energy + approve_energy + balance_energy))
echo "=== Summary ==="
echo "Total energy for all operations: $total_energy"
calculate_costs "$total_energy"
}
# Energy optimization advisor
energy_optimization_advisor() {
local total_energy_needed=$1
echo "=== Energy Optimization Advisor ==="
echo "Total energy needed: $total_energy_needed"
echo ""
# Calculate different strategies
local pay_trx_cost=$(echo "scale=6; $total_energy_needed * 0.00014" | bc -l)
local stake_trx_needed=$(echo "scale=2; $total_energy_needed / 4000" | bc -l)
local rent_cost=$(echo "scale=6; $pay_trx_cost * 0.7" | bc -l)
echo "Strategy Options:"
echo ""
echo "1. Pay with TRX"
echo " Cost: $pay_trx_cost TRX"
echo " Pros: Immediate execution, no staking required"
echo " Cons: Higher cost per transaction"
echo ""
echo "2. Stake TRX for Energy"
echo " Stake needed: ~$stake_trx_needed TRX"
echo " Pros: Reusable energy, long-term savings"
echo " Cons: TRX locked for 3 days"
echo ""
echo "3. Rent Energy"
echo " Cost: ~$rent_cost TRX"
echo " Pros: Lower cost than direct payment"
echo " Cons: One-time use, requires third-party"
echo ""
# Recommendation
if (( $(echo "$pay_trx_cost < 1" | bc -l) )); then
echo "💡 Recommendation: Pay with TRX (low cost)"
elif (( $(echo "$stake_trx_needed < 100" | bc -l) )); then
echo "💡 Recommendation: Consider staking TRX for energy"
else
echo "💡 Recommendation: Rent energy for better cost efficiency"
fi
}
# Batch estimation for multiple contracts
batch_estimate() {
local contracts_file=$1
if [ ! -f "$contracts_file" ]; then
echo "Error: Contracts file not found: $contracts_file"
echo "Create a file with format: CONTRACT_ADDRESS:FUNCTION_SELECTOR:PARAMETERS"
return 1
fi
echo "=== Batch Energy Estimation ==="
echo "Processing contracts from: $contracts_file"
echo ""
local total_energy=0
local operation_count=0
while IFS=':' read -r contract_address function_selector parameters; do
# Skip empty lines
[ -z "$contract_address" ] && continue
((operation_count++))
echo "Operation $operation_count: $function_selector"
local result=$(estimate_energy "$contract_address" "$function_selector" "$parameters")
local energy=$(echo "$result" | jq -r '.energy_required // 0')
local will_succeed=$(echo "$result" | jq -r '.result.result // false')
echo " Energy: $energy"
echo " Will succeed: $will_succeed"
total_energy=$((total_energy + energy))
echo ""
done < "$contracts_file"
echo "=== Batch Summary ==="
echo "Total operations: $operation_count"
echo "Total energy required: $total_energy"
if [ "$total_energy" -gt 0 ]; then
calculate_costs "$total_energy"
energy_optimization_advisor "$total_energy"
fi
}
# Usage examples
case "${1:-common}" in
"common")
# Default: estimate common operations for USDT
estimate_common_operations "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
;;
"single")
# Estimate single operation
if [ $# -lt 3 ]; then
echo "Usage: $0 single CONTRACT_ADDRESS FUNCTION_SELECTOR [PARAMETERS]"
exit 1
fi
local result=$(estimate_energy "$2" "$3" "${4:-}")
local energy=$(echo "$result" | jq -r '.energy_required // 0')
echo "Energy estimation result:"
echo "$result" | jq .
echo ""
calculate_costs "$energy"
check_free_execution "$OWNER_ADDRESS" "$energy"
;;
"batch")
# Batch estimation
batch_estimate "$2"
;;
"optimize")
# Energy optimization for specific amount
energy_optimization_advisor "$2"
;;
*)
echo "Usage: $0 {common|single|batch|optimize} [args...]"
echo ""
echo "Commands:"
echo " common - Estimate common TRC20 operations"
echo " single CONTRACT FUNCTION [PARAMS] - Estimate single operation"
echo " batch CONTRACTS_FILE - Batch estimation from file"
echo " optimize ENERGY_AMOUNT - Get optimization advice"
;;
esac
Response Examples
Successful Energy Estimation
{
"energy_required": 13326,
"result": {
"result": true
},
"energy_used": 13326
}
Failed Estimation (Insufficient Balance)
{
"energy_required": 0,
"result": {
"result": false,
"code": "REVERT",
"message": "revert Insufficient balance"
}
}
Need help? Contact our support team or check the TRON documentation.