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

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.

Optimize your energy usage →

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

  1. owner_address - string (required)

    • Address that will execute the contract call
    • Example: "TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh"
  2. contract_address - string (required)

    • Smart contract address to call
    • Example: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t" (USDT)
  3. function_selector - string (required)

    • Function signature to estimate
    • Example: "transfer(address,uint256)"
  4. parameter - string (optional)

    • Hex-encoded function parameters
    • Example: "0000000000000000000000004142b5e01c8c59a25d78acdbec2bfc7e89e5e86300000000000000000000000000000000000000000000000000000000000f4240"
  5. call_value - integer (optional)

    • TRX amount to send (in SUN) for payable functions
    • Default: 0
  6. visible - boolean (optional, default: false)

    • true - Use Base58 address format
    • false - 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 consumption
  • result - Execution success/failure simulation
  • energy_used - Base energy used for calculation

Implementation Examples

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

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.