NRG
Search
⌃K
⚡

How to check user energy levels

Prerequisites
Ensure that you have the TronWeb library installed and properly configured. You need to have a Tron node either a private node or using a public gateway such as TronGrid

Step 1: Define the Energy Requirement

Please note the minimum order is 25,000 energy units
Define how much energy your operation will need. This value should be set according to the specific action the user wants to take. For example, if your operation requires 100,000 units of energy, you should set amountRequired to 100000.
var amountRequired = 100000; // adjust this value based on your needs
​
​
/**
* Function to check if the user has sufficient energy.
*
* @param {number} amountRequired - The amount of energy required for the operation.
* @returns {number} The additional amount of energy required by the user.
*/
async function checkUserEnergyNeeded(amountRequired) {
// Initialize the variable for the additional energy needed.
var userNeeds = 0;
// Retrieve the account's resources.
await tronWeb.trx.getAccountResources(window.tronWeb.defaultAddress.base58)
.then(result => {
​
if ('EnergyLimit' in result && 'EnergyUsed' in result) {
// Calculate the available energy.
let availableEnergy = result.EnergyLimit - result.EnergyUsed;
// If the required energy is greater than the available energy,
// calculate the additional amount needed.
if (amountRequired > availableEnergy) {
userNeeds = amountRequired - availableEnergy;
}
} else {
userNeeds = amountRequired;
}
});
​
// Return the additional amount of energy needed, if any.
// If no additional energy is needed, this will be zero.
return userNeeds;
}
​

Step 2: Call the Function

Call your checkUserEnergyLevels function and pass the amountRequired as a parameter.
var extraEnergyNeeded = await checkUserEnergyNeeded(amountRequired);

Step 3: Interpret the Results

Interpret the results of the function call. The function will return the amount of additional energy the user needs to perform the operation. If no extra energy is needed, the function will return 0. If additional energy is required, it will return the amount of energy needed.
if (extraEnergyNeeded === 0) {
console.log('The user has sufficient energy for this operation.');
} else {
console.log('The user needs additional units of energy for this operation. ');
}
​
Step 4: Order the energy
Now you have determined how much if any the user may need you can now go to the next section to dynamically assign the amount the user needs