Tronsave
🇬🇧 English
🇬🇧 English
  • 📗INTRODUCTION
    • What is Tronsave ?
    • Why Tronsave?
  • Buyer
    • How to buy Energy ?
      • Buy on the Website
      • Buy on Telegram
        • 1. Create a Tronsave telegram account
        • 2. How To Deposit TRX
        • 3. Get the Tronsave API Key
        • 4. How to buy on Telegram
    • Extend
      • Quick extend
      • Advance
  • 🏬Seller
    • Get Energy by Staking 2.0
    • Permission
    • Sell Energy
      • Manual Sell
      • Auto Sell
      • Sell Suggestion
  • DEVELOPER
    • Get API key
      • On the Website
      • On Telegram
    • Buy Resources (v2)
      • Use Signed Transaction
        • Estimate TRX
        • Get Signed Transaction
        • Create order
      • Use API Key
        • Get Internal Account Info
        • Get Order Book
        • Estimate TRX
        • Create order
        • Get one order details
        • Get Internal Account Order History
    • Extend Orders (v2)
      • Step 1: Get Extendable Delegates
      • Step 2: Extend Request
    • Rest API v0
      • Buy on Rest API
        • Use Signed Transaction
          • Estimate TRX
          • Get Signed Transaction
          • Create order
          • Demo
        • Use API Key
          • Get Internal Account Info
          • Get Order Book
          • Estimate of TRX
          • Create order
          • Get one order details
          • Get Internal Account Order History
      • Extend with Rest API
  • 🤝Referrer
    • Referrals
  • 💡FAQ
    • Questions for Energy market
    • Calculate APY in TronSave
    • How to connect wallet in Tronsave?
    • Team of Service
  • 👨‍💻Full Code Example
    • Code Example (v2)
      • Buy Resource by API using private key
      • Buy Resources by API using api key
      • Extend order by API using api key
      • Extend order by API using private key
    • Code Example (v0)
      • Buy energy by API using private key
      • Buy energy by API using api key
      • Extend order by API using api key
Powered by GitBook
On this page
  1. Full Code Example
  2. Code Example (v2)

Buy Resource by API using private key

This is full example buy resources by API key using private key

PreviousCode Example (v2)NextBuy Resources by API using api key

Last updated 1 day ago

Requirement: TronWeb version 5.3.2

npm i tronweb@5.3.2 @noble/secp256k1@1.7.1

(Read more: )

import { TronWeb } from 'tronweb';

// Configuration constants
const TRONSAVE_RECEIVER_ADDRESS = "TWZEhq5JuUVvGtutNgnRBATbF8BnHGyn4S"; //in testnet mode change it to "TATT1UzHRikft98bRFqApFTsaSw73ycfoS"
const PRIVATE_KEY = "your_private_key"; //Change it
const TRON_FULL_NODE = "https://api.trongrid.io"; //in testnet mode change it to "https://api.nileex.io"
const TRONSAVE_API_URL = "https://api.tronsave.io"; //in testnet mode change it to "https://api-dev.tronsave.io"
const RESOURCE_TYPE = "ENERGY"; // ENERGY or BANDWIDTH

const REQUEST_ADDRESS = "your_request_address"; //Change it
const RECEIVER_ADDRESS = "your_receiver_address"; //Change it
const BUY_AMOUNT = 32000; //Chanageable
const DURATION_SEC = 3 * 86400; //3 days.Changeable

// Initialize TronWeb instance
const tronWeb = new TronWeb({
    fullNode: TRON_FULL_NODE,
    solidityNode: TRON_FULL_NODE,
    eventServer: TRON_FULL_NODE,
});

const GetEstimate = async (requestAddress, receiverAddress, resourceAmount, durationSec) => {
    const url = TRONSAVE_API_URL + "/v2/estimate-buy-resource";
    const body = {
        resourceAmount,
        unitPrice: "MEDIUM",
        resourceType: RESOURCE_TYPE,
        durationSec,
        requester: requestAddress,
        receiver: receiverAddress,
        options: {
            allowPartialFill: true,
        },
    };
    const data = await fetch(url, {
        method: "POST",
        headers: {
            "content-type": "application/json",
        },
        body: JSON.stringify(body),
    });
    const response = await data.json();
    /**
     * Example response 
   {
        "error": false,
        "message": 'Success',
        "data": {
            "unitPrice": 50,
            "durationSec": 259200,
            "estimateTrx": 7680000,
            "availableResource": 32000
        }
    }
     */
    return response;
};

const GetSignedTransaction = async (estimateTrx, requestAddress) => {
    const dataSendTrx = await tronWeb.transactionBuilder.sendTrx(TRONSAVE_RECEIVER_ADDRESS, estimateTrx, requestAddress);
    const signedTx = await tronWeb.trx.sign(dataSendTrx, PRIVATE_KEY);
    return signedTx;
};

const CreateOrder = async (signedTx, receiverAddress, resourceAmount, unitPrice, durationSec, options) => {
    const url = TRONSAVE_API_URL + "/v2/buy-resource";
    const body = {
        resourceType: RESOURCE_TYPE,
        unitPrice,
        allowPartialFill: true,
        receiver: receiverAddress,
        durationSec,
        signedTx,
        options
    };
    const data = await fetch(url, {
        method: "POST",
        headers: {
            "content-type": "application/json",
        },
        body: JSON.stringify(body),
    });
    const response = await data.json();
    /**
     * Example response
     * {
     *     "error": false,
     *     "message": "Success",
     *     "data": {
     *         "orderId": "6809fdb7b9ba217a41d726fd"
     *     }
     * }
     */
    return response;
};

/**
 * Main function to buy resources using private key
 * @returns {Promise<void>}
 */
const BuyResourceUsingPrivateKey = async () => {
    //Step 1: Estimate the cost of buy order
    const estimateData = await GetEstimate(REQUEST_ADDRESS, RECEIVER_ADDRESS, BUY_AMOUNT, DURATION_SEC);
    if (estimateData.error) throw new Error(estimateData.message);
    console.log(estimateData);
    const { unitPrice, estimateTrx, durationSec, availableResource } = estimateData.data;
    /*
    {
        "unitPrice": 60,
        "durationSec": 259200,
        "availableResource": 4298470,
        "estimateTrx": 13500000,
    }
     */
    const isReadyFulfilled = availableResource >= BUY_AMOUNT; //if availableResource equal BUY_AMOUNT it means that your order can be fulfilled 100%
    if (isReadyFulfilled) {
        //Step 2: Build signed transaction by using the private key
        const signedTx = await GetSignedTransaction(estimateTrx, REQUEST_ADDRESS);
        console.log(signedTx);
        /*
        {
            "visible": false,
            "txID": "446eed36e31249b98b201db2e81a3825b185f1a3d8b2fea348b24fc021e58e0d",
            "raw_data": {
                "contract": [
                {
                    "parameter": {
                    "value": {
                        "amount": 13500000,
                        "owner_address": "417a0d868d1418c9038584af1252f85d486502eec0",
                        "to_address": "41055756f33f419278d9ea059bd2b21120e6add748"
                    },
                    "type_url": "type.googleapis.com/protocol.TransferContract"
                    },
                    "type": "TransferContract"
                }
                ],
                "ref_block_bytes": "0713",
                "ref_block_hash": "6c5f7686f4176139",
                "expiration": 1691465106000,
                "timestamp": 1691465046758
            },
            "raw_data_hex": "0a02071322086c5f7686f417613940d084b5999d315a68080112640a2d747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e5472616e73666572436f6e747261637412330a15417a0d868d1418c9038584af1252f85d486502eec0121541055756f33f419278d9ea059bd2b21120e6add74818e0fcb70670e6b5b1999d31",
            "signature": ["xxxxxxxxx"]
        }
         */

        //Step 3: Create order
        const options = {
            allowPartialFill: true,
            maxPriceAccepted: 100,
        }
        const dataCreateOrder = await CreateOrder(signedTx, RECEIVER_ADDRESS, unitPrice, durationSec, options);
        console.log(dataCreateOrder);
    }
};
BuyResourceUsingPrivateKey()
<?php

// Configuration
const TRONSAVE_RECEIVER_ADDRESS = "TWZEhq5JuUVvGtutNgnRBATbF8BnHGyn4S";
const PRIVATE_KEY = "your_private_key";
const TRON_FULL_NODE = "https://api.trongrid.io";
const TRONSAVE_API_URL = "https://api.tronsave.io";
const RESOURCE_TYPE = "ENERGY";

const REQUEST_ADDRESS = "your_request_address";
const RECEIVER_ADDRESS = "your_receiver_address";
const BUY_AMOUNT = 32000;
const DURATION_SEC = 3 * 86400; // 3 days

/**
 * Get an estimate for buying the resource
 * @return array
 */
function getEstimate(): array {
    $url = TRONSAVE_API_URL . "/v2/estimate-buy-resource";
    $body = [
        'resourceAmount' => BUY_AMOUNT,
        'unitPrice' => "MEDIUM",
        'resourceType' => RESOURCE_TYPE,
        'durationSec' => DURATION_SEC,
        'requester' => REQUEST_ADDRESS,
        'receiver' => RECEIVER_ADDRESS,
        'options' => [
            'allowPartialFill' => true,
        ]
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json'
    ]);
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true);
}

/**
 * Get a signed transaction
 * @param int $estimateTrx
 * @return array
 */
function getSignedTransaction(int $estimateTrx): array {
    // This is a placeholder. In real implementation, you would use TronWeb PHP SDK
    return [
        'visible' => false,
        'txID' => '...',
        'raw_data' => [
            'contract' => [
                [
                    'parameter' => [
                        'value' => [
                            'amount' => $estimateTrx,
                            'owner_address' => REQUEST_ADDRESS,
                            'to_address' => TRONSAVE_RECEIVER_ADDRESS
                        ],
                        'type_url' => 'type.googleapis.com/protocol.TransferContract'
                    ],
                    'type' => 'TransferContract'
                ]
            ]
        ]
    ];
}

/**
 * Create order
 * @param array $signedTx
 * @param string $receiverAddress
 * @param int $unitPrice
 * @param int $durationSec
 * @param array $options
 * @return array
 */
function createOrder(array $signedTx, string $receiverAddress, int $resourceAmount, int $unitPrice, int $durationSec, array $options): array {
    $url = TRONSAVE_API_URL . "/v2/buy-resource";
    $body = [
        'resourceType' => RESOURCE_TYPE,
        'resourceAmount' => $resourceAmount,
        'unitPrice' => $unitPrice,
        'allowPartialFill' => true,
        'receiver' => $receiverAddress,
        'durationSec' => $durationSec,
        'signedTx' => $signedTx,
        'options' => $options
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json'
    ]);
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true);
}

/**
 * Main function to buy resources using private key
 */
function buyResourceUsingPrivateKey(): void {
    // Step 1: Estimate the cost
    $estimateData = getEstimate();
    if ($estimateData['error']) {
        throw new Exception($estimateData['message']);
    }
    print_r($estimateData);

    $unitPrice = $estimateData['data']['unitPrice'];
    $estimateTrx = $estimateData['data']['estimateTrx'];
    $durationSec = $estimateData['data']['durationSec'];
    $availableResource = $estimateData['data']['availableResource'];

    $isReadyFulfilled = $availableResource >= BUY_AMOUNT;
    if ($isReadyFulfilled) {
        // Step 2: Build signed transaction
        $signedTx = getSignedTransaction($estimateTrx);
        print_r($signedTx);

        // Step 3: Create order
        $options = [
            'allowPartialFill' => true,
            'maxPriceAccepted' => 100,
        ];
        $dataCreateOrder = createOrder($signedTx, RECEIVER_ADDRESS, BUY_AMOUNT, $unitPrice, $durationSec, $options);
        print_r($dataCreateOrder);
    }
}

// Run the main function
try {
    buyResourceUsingPrivateKey();
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
} 
import requests
from typing import Dict, Any, Optional

# Configuration
TRONSAVE_RECEIVER_ADDRESS = "TWZEhq5JuUVvGtutNgnRBATbF8BnHGyn4S"
PRIVATE_KEY = "your_private_key"
TRON_FULL_NODE = "https://api.trongrid.io"
TRONSAVE_API_URL = "https://api.tronsave.io"
RESOURCE_TYPE = "ENERGY"

REQUEST_ADDRESS = "your_request_address"
RECEIVER_ADDRESS = "your_receiver_address"
BUY_AMOUNT = 32000
DURATION_SEC = 3 * 86400  # 3 days

def get_estimate() -> Dict[str, Any]:
    """Get estimate for buying resource"""
    url = f"{TRONSAVE_API_URL}/v2/estimate-buy-resource"
    body = {
        'resourceAmount': BUY_AMOUNT,
        'unitPrice': "MEDIUM",
        'resourceType': RESOURCE_TYPE,
        'durationSec': DURATION_SEC,
        'requester': REQUEST_ADDRESS,
        'receiver': RECEIVER_ADDRESS,
        'options': {
            'allowPartialFill': True,
        }
    }
    
    response = requests.post(url, json=body)
    return response.json()

def get_signed_transaction(estimate_trx: int) -> Dict[str, Any]:
    """Get signed transaction"""
    # This is a placeholder. In real implementation, you would use TronWeb Python SDK
    return {
        'visible': False,
        'txID': '...',
        'raw_data': {
            'contract': [{
                'parameter': {
                    'value': {
                        'amount': estimate_trx,
                        'owner_address': REQUEST_ADDRESS,
                        'to_address': TRONSAVE_RECEIVER_ADDRESS
                    },
                    'type_url': 'type.googleapis.com/protocol.TransferContract'
                },
                'type': 'TransferContract'
            }]
        }
    }

def create_order(signed_tx: Dict[str, Any], receiver_address: str, resource_amount: int,
                unit_price: int, duration_sec: int, options: Dict[str, Any]) -> Dict[str, Any]:

    """Create order"""
    url = f"{TRONSAVE_API_URL}/v2/buy-resource"
    body = {
        'resourceType': RESOURCE_TYPE,
        'resourceAmount': resource_amount,
        'unitPrice': unit_price,
        'allowPartialFill': True,
        'receiver': receiver_address,
        'durationSec': duration_sec,
        'signedTx': signed_tx,
        'options': options
    }
    
    response = requests.post(url, json=body)
    return response.json()

def buy_resource_using_private_key() -> None:
    """Main function to buy resource using private key"""
    try:
        # Step 1: Estimate the cost
        estimate_data = get_estimate()
        if estimate_data['error']:
            raise Exception(estimate_data['message'])
        print("Estimate Data:", estimate_data)

        unit_price = estimate_data['data']['unitPrice']
        estimate_trx = estimate_data['data']['estimateTrx']
        duration_sec = estimate_data['data']['durationSec']
        available_resource = estimate_data['data']['availableResource']

        is_ready_fulfilled = available_resource >= BUY_AMOUNT
        if is_ready_fulfilled:
            # Step 2: Build signed transaction
            signed_tx = get_signed_transaction(estimate_trx)
            print("Signed Transaction:", signed_tx)

            # Step 3: Create order
            options = {
                'allowPartialFill': True,
                'maxPriceAccepted': 100,
            }
            data_create_order = create_order(
                signed_tx, RECEIVER_ADDRESS, BUY_AMOUNT, unit_price, duration_sec, options)
            print("Create Order Response:", data_create_order)

    except Exception as e:
        print(f"Error: {str(e)}")

if __name__ == "__main__":
    buy_resource_using_private_key() 
👨‍💻
https://tronweb.network/docu/docs/5.3.2/Release%20Note/