Rent Tron Energy - TronWeb

This guide will walk you through the process of using TronNRG to rent energy for your application programmatically. By integrating with TronNRG, you can create a seamless user experience for your customers. The following steps demonstrate how to perform this integration using node.js and TronWeb. Please ensure that you have properly configured TronWeb before proceeding.

TronNRG offers a unique solution for renting energy for Tron transactions, allowing users to rent only the amount of energy needed for a single transaction. This feature can significantly reduce transaction fees and enhance cost efficiency for your users.

Consider a user making a single USDT TRC20 transaction that requires 32,000 energy units. By renting energy through TronNRG, the user would only need to pay from 3 TRX up to 8 TRX for the required amount of energy at the time of the transaction. In contrast, burning TRX for the same amount of energy would cost 14 TRX, resulting in a substantial cost saving for the user.

By integrating with TronNRG, your business gains access to our cutting-edge energy rental platform, providing exceptional benefits for both you and your users. Our unique system allows companies to integrate our platform seamlessly into their existing systems with just a few lines of code. This opens up new revenue streams and enhances user experiences with cost-effective transactions.

Step 1: Get an instance of the NRG contract using TronWeb

First, instantiate the NRG contract object using the NRG contact address provided:

NRG contract address = TEeLFcbSc2LFSFrTZnWRCacZzo3ZtBybh2

let NRG = await tronWeb.contract().at('TEeLFcbSc2LFSFrTZnWRCacZzo3ZtBybh2');

Step 2: Check energy availability

Determine if the desired amount of energy is available;

async function getAvailableEnergy(NRG) {
    try {
        let promises = [
            NRG.getDelegatableResource(1).call(),
            NRG.energyInfo().call(),
            NRG.getCurrentEnegryRate().call()
        ];

        let [getDelegatableResource, energyInfo, rate] = await Promise.all(promises);

        getDelegatableResource = parseInt(getDelegatableResource._hex, 16);
        energyInfo = parseInt(energyInfo.amountScheduledOut._hex, 16);
        rate = parseInt(rate._hex, 16);

        return roundnum(Math.floor(((getDelegatableResource - energyInfo) / 1000000) * rate));
    } catch (e) {
        console.log(e);
        return 0;
    }
};

var availableEnergy = await getAvailableEnergy(NRG);

Ensure that the availableEnergy value is greater than or equal to the amount you want to rent.

Step 3: Get a quote for the required energy

Call the calculatePrice function with the following parameters:

  • unitType: Integer value that specifies unit type this value should be 1

  • amount: The amount of energy required (e.g., 100,000 units)

  • rentalPeriod: The length of the rental period in hours according to the unitType

For example, to get a quote for 100,000 units of energy for one hour :

var calculatePriceResult = await NRG.calculatePrice(1, 100000, 1).call();

var quote = parseInt(calculatePriceResult.total._hex);

Step 4: Rent energy

Please note that all energy costs associated with renting energy are covered by the smart contract and you will incur no fees

Call the buyEnergy function with the following parameters:

If you are applying energy to other users accounts you may consider joining the NRG affiliate program, which allows you to earn 5% commission from your sales. Get your ID and pass it into the call.

  • address: The address to delegate resources to

  • unitType: Integer value 1

  • amount: The amount of energy to rent

  • affiliate: The affiliate ID number, if available; otherwise, use 0 as the default

  • rentalPeriod: The length of the rental period in hours or days, depending on the unitType

For example, to rent 100,000 energy for one hour:

var value = quote; // The amount to pay for the rental from step 3, in Sun

var buyEnergyResult = await NRG.buyEnergy("TFjbF1eGUTf44hGjYrHFarJz2v9h5uUxih", 1, 100000, 0, 1).send({ feeLimit: tronWeb.toSun('400'), callValue: value , shouldPollResponse: false });

Upon successful completion of the transaction, the rented energy will be immediately delegated to the specified address.

Here is an example of a function that could be used:


function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
};


async function getAvailableEnergy(NRG) {
    let energyAvailableNow;
    try {
        let getDelegatableResource = await NRG.getDelegatableResource(1).call();
        getDelegatableResource = parseInt(getDelegatableResource._hex, 16);
      
        let energyInfo = await NRG.energyInfo().call();
        energyInfo = parseInt(energyInfo.amountScheduledOut._hex, 16);
        
        let rate = await NRG.getCurrentEnegryRate().call();
        rate = parseInt(rate._hex, 16);
      
        energyAvailableNow = roundnum(Math.floor((getDelegatableResource - energyInfo) / 1000000) * rate);
       
    } catch (e) {
        energyAvailableNow = 0;
        console.log(e);
    }

    return energyAvailableNow;
};

// Define an async function that gets a quote for renting energy and rents it if available
async function getQuoteAndRent(delegateTo, unitType, energyAmount, rentalPeriod, affiliate) {
    try {
        // Instantiate the NRG contract object using TronWeb
        let NRG = await tronWeb.contract().at('TEeLFcbSc2LFSFrTZnWRCacZzo3ZtBybh2');

        // Get the available energy
        
        var availableEnergy = await getAvailableEnergy(NRG);

        // Check if the available energy is sufficient
        if (availableEnergy >= energyAmount) {
            // Get a quote for the required energy
            var calculatePriceResult = await NRG.calculatePrice(unitType, energyAmount, rentalPeriod).call();
            var quote = parseInt(calculatePriceResult.total._hex);

            // Rent the energy
            var buyEnergyResult = await NRG.buyEnergy(delegateTo, unitType, energyAmount, affiliate, rentalPeriod).send({
                feeLimit: tronWeb.toSun('400'),
                callValue: quote,
                shouldPollResponse: false
            });
             
             // Please note, if the transaction did not revert then the energy has already 
             // been applied to the user account
            
           return true
        } else {
            // Not enough energy available
            return false;
        }
    } catch (err) {
        console.log(err);
        // Handle errors and fix any issues
    }
}


var rentEnegry = await getQuoteAndRent("TFjbF1eGUTf44hGjYrHFarJz2v9h5uUxih",1,100000,1,0);

Last updated