Buy energy by API using api key

This is full example buy enery by API key using api key

How to get api key

Option 1: Generate the API key on the Tronsave website.

Option 2: Generate the API key on Telegram.

const API_KEY = `your_api_key`; // CHANGE ME
const TRONSAVE_API_URL = "https://api.tronsave.io" //in testnet mode change it to "https://api-dev.tronsave.io"
const RECEIVER_ADDRESS = 'your_receiver_address' // CHANGE ME
const BUY_AMOUNT = 100000 // CHANGE ME
const DURATION = 3600 * 1000 // current value: 1h. CHANGE ME
const MAX_PRICE_ACCEPTED = 100 // CHANGE ME

const sleep = async (ms) => {
    await new Promise((resolver, reject) => {
        setTimeout(() => resolver("OK"), ms)
    })
}

const GetOrderBook = async (api_key, receiver_address) => {
    const url = `${TRONSAVE_API_URL}/v0/order-book?address=${receiver_address}`
    const data = await fetch(url, {
        headers: {
            'apikey': api_key
        }
    })
    const response = await data.json()
    /**
     * Example response 
     * @link https://docs.tronsave.io/buy-energy-on-telegram/using-api-key-to/get-order-book
      [
        {
            "price": -1,
            "available_energy_amount": 177451
        },
        {
            "price": 30,
            "available_energy_amount": 331088
        },
        {
            "price": 35,
            "available_energy_amount": 2841948
        },
    ]
     */
    return response
}

const GetAccountInfo = async (api_key) => {
    const url = `${TRONSAVE_API_URL}/v0/user-info`
    const data = await fetch(url, {
        headers: {
            'apikey': api_key
        }
    })
    const response = await data.json()
    /**
     * Example response 
     * @link https://docs.tronsave.io/buy-energy-on-telegram/using-api-key-to/get-internal-account-info
    {
        "id": "user_id",
        "balance": "1000000",
        "represent_address": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
        "deposit_address": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
    }
     */
    return response
}


const BuyEnergy = async (api_key, target_address, amount, duration_ms, max_price_accepted) => {
    const url = `${TRONSAVE_API_URL}/v0/internal-buy-energy`
    //see more at https://docs.tronsave.io/buy-energy-on-telegram/using-api-key-to/buy-energy
    const body = {
        "resource_type": "ENERGY",
        "buy_energy_type": "MEDIUM", //price in sun or "SLOW"|"MEDIUM"|"FAST"
        "amount": amount, //Amount of resource want to buy
        "allow_partial_fill": true,
        "target_address": target_address,
        "duration_millisec": duration_ms, //order duration in milli sec. Default: 259200000 (3 days)
        "only_create_when_fulfilled": false,
        "max_price_accepted": max_price_accepted,
        "add_order_incomplete": false
    }
    const data = await fetch(url, {
        method: "POST",
        headers: {
            'apikey': api_key,
            "content-type": "application/json",
        },
        body: JSON.stringify(body)
    })
    const response = await data.json()
    /**
     * Example response 
     * @link  https://docs.tronsave.io/buy-energy-on-telegram/using-api-key-to/buy-energy
   {
      "order_id": "651d2306e55c073f6ca0992e",
      "requester": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
      "target": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
      "resource_amount": 100000,
      "resource_type": "ENERGY",
      "remain_amount": 0,
      "price": 67.5,
      "duration": 3600,
      "allow_partial_fill": true,
      "payout_amount": 6750000,
      "fulfilled_percent": 100
}
     */
    return response
}

const GetOneOrderDetails = async (api_key, order_id) => {
    const url = `${TRONSAVE_API_URL}/v0/orders/${order_id}`
    const data = await fetch(url, {
        headers: {
            'apikey': api_key
        }
    })
    const response = await data.json()
    /**
     * Example response 
     * @link https://docs.tronsave.io/buy-energy-on-telegram/using-api-key-to/get-internal-account-order-history
        {
            "id": "651d2306e55c073f6ca0992e",
            "requester": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
            "target": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
            "resource_amount": 100000,
            "resource_type": "ENERGY",
            "remain_amount": 0,
            "price": 67.5,
            "duration": 3600,
            "allow_partial_fill": true,
            "payout_amount": 6750000,
            "fulfilled_percent": 100,
            "matched_delegates": [
                        {
                            "delegator": "TKVSaJQDWeKFSEXmA44pjxduGTxy888888",
                            "amount": 100000,
                            "txid": "transaction_id_1"
                        }
                    ]
        }
     */
    return response
}

const CreateOrderByUsingApiKey = async () => {
    //Check energy available
    const order_book = await GetOrderBook(API_KEY, RECEIVER_ADDRESS)
    console.log(order_book)
    /*
      [
        {
            "price": -1,
            "available_energy_amount": 177451
        },
        {
            "price": 30,
            "available_energy_amount": 331088
        },
        {
            "price": 35,
            "available_energy_amount": 2841948
        },
    ]
    */
    //Look at response above, we have 177k energy at price less than 30, 331k enegy at price 30 and 2841k energy at price 35
    //Example if want to buy 500k energy in 3 days you have to place order at price at least 35 energy to fulfill your order (the price can be higher if duration of order less than 3 days)

    const need_trx = MAX_PRICE_ACCEPTED * BUY_AMOUNT

    //Check if your internal balance enough to buy
    const account_info = await GetAccountInfo(API_KEY)
    console.log(account_info)
    /*
     {
        "id": "user_id",
        "balance": "1000000",
        "represent_address": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
        "deposit_address": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
    }
    */
    const is_balance_enough = Number(account_info.balance) >= need_trx
    if (is_balance_enough) {

        const buy_energy_order = await BuyEnergy(API_KEY, RECEIVER_ADDRESS, BUY_AMOUNT, DURATION, MAX_PRICE_ACCEPTED)
        console.log(buy_energy_order)
        /*
          {
          "order_id": "651d2306e55c073f6ca0992e",
          "requester": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
          "target": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
          "resource_amount": 100000,
          "resource_type": "ENERGY",
          "remain_amount": 0,
          "price": 67.5,
          "duration": 3600,
          "allow_partial_fill": true,
          "payout_amount": 6750000,
          "fulfilled_percent": 100
        }
        */
        //Wait 3-5 seconds after buy then check 
        if (buy_energy_order.order_id) {
            while (true) {
                await sleep(3000)
                const order_details = await GetOneOrderDetails(API_KEY, buy_energy_order.order_id)
                console.log(order_details)
                /*
                    {
                        "id": "651d2306e55c073f6ca0992e",
                        "requester": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
                        "target": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
                        "resource_amount": 100000,
                        "resource_type": "ENERGY",
                        "remain_amount": 0,
                        "price": 67.5,
                        "duration": 3600,
                        "allow_partial_fill": true,
                        "payout_amount": 6750000,
                        "fulfilled_percent": 100,
                        "matched_delegates": [
                                    {
                                        "delegator": "TKVSaJQDWeKFSEXmA44pjxduGTxy888888",
                                        "amount": 100000,
                                        "txid": "transaction_id_1"
                                    }
                                ]
                    }
                */
                if (order_details && order_details.fulfilled_percent === 100 || order_details.remain_amount === 0) {
                    console.log(`Your order already fulfilled`)
                    break;
                } else {
                    console.log(`Your order is not fulfilled, wait 3s and recheck`)
                }
            }
        } else {
            console.log({ buy_energy_order })
            throw new Error(`Buy Order Failed`)
        }
    }
}

CreateOrderByUsingApiKey()

Last updated