Tronsave
🇨🇳 Chinese
🇨🇳 Chinese
  • 📗INTRODUCTION
    • Tronsave是什么?
    • 什么选 Tronsave?
  • Buyer
    • 如何购买能量?
      • 在网站上购买
      • 如何在Telegram上购买能源
        • 1: 创建Telegram Tronsave帐户
        • 2: 如何存款
        • 3: 获取Tronsave API密钥
        • 4. 如何在 Telegram 上购买
    • 延长
      • 快速延长
      • 提高
  • 🏬Seller
    • 质押 2.0 (Stake 2.0)
    • 权限 (Permission)
    • 购买能源
      • 设置自动卖出 (Setup Auto Sell)
      • 手动出售
      • 卖出建议
  • DEVELOPER
    • 获取 API 密钥
      • 在网站上
      • 在Telegram上
    • 购买资源 (v2)
      • 使用签名交易 (Signed tx)
        • 估算TRX
        • 获取已签名交易
        • 创建订单
      • 使用 API 密钥
        • 获取内部账户信息
        • 获取订单簿 (Order book)
        • 获取估算 TRX (Estimate TRX)
        • 购买能源
        • 获取单个订单详情
        • 获取内部账户订单历史
    • 扩展订单 (v2)
      • 步骤 1:获取可扩展的委托人
      • 步骤 2:扩展请求
    • SDK 库
    • REST API v0
      • 通过 REST API 购买
        • 使用签名交易 (Signed tx)
          • 估算TRX
          • 获取已签名交易
          • 创建订单
          • Demo
        • 使用 API 密钥
          • 获取内部账户信息
          • 获取订单簿 (Order book)
          • 获取估算 TRX (Estimate TRX)
          • 购买能源
          • 获取单个订单详情
          • 获取内部账户订单历史
      • 订单延长使用API密钥
  • 🤝 Referrer
    • 推荐 (Referral)
  • 💡FAQ
    • 能源市场问题
    • 计算 TronSave 的年化收益率 (APY)
    • 如何在 Tronsave 中连接钱包?
    • 服务团队
  • 👨‍💻Full Code Example
    • Code Example (v2)
      • 使用私钥通过 API 购买能源
      • 使用 API 密钥通过 API 购买能源
      • 使用 API 密钥通过 API 扩展订单
      • 使用私钥通过 API 扩展订单
    • Code Exaample (v0)
      • 使用私钥通过 API 购买能源
      • 使用 API 密钥通过 API 购买能源
      • 使用API密钥通过API延长订单
Powered by GitBook
On this page
  1. Full Code Example
  2. Code Example (v2)

使用私钥通过 API 购买能源

这是使用私钥通过 API 密钥购买能源的完整示例

PreviousCode Example (v2)Next使用 API 密钥通过 API 购买能源

Last updated 19 days ago

要求:TronWeb 版本 5.3.2

npm i tronweb@5.3.2 @noble/secp256k1@1.7.1

(了解更多:)

const {TronWeb} = require('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 = 3600; // 1 hour

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

const GetEstimate = async (resourceAmount, durationSec) => {
    const url = TRONSAVE_API_URL + "/v2/estimate-buy-resource";
    const body = {
        resourceAmount,
        unitPrice: "MEDIUM",
        resourceType: RESOURCE_TYPE,
        durationSec,
    };
    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 (resourceAmount, signedTx, receiverAddress, unitPrice, durationSec, options) => {
    const url = TRONSAVE_API_URL + "/v2/buy-resource";
    const body = {
        resourceType: RESOURCE_TYPE,
        resourceAmount,
        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 resource using private key
 * @returns {Promise<void>}
 */
const BuyResourceUsingPrivateKey = async () => {
    //Step 1: Estimate the cost of buy order
    const estimateData = await GetEstimate(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 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 dataCreateOrder = await CreateOrder(BUY_AMOUNT, signedTx, RECEIVER_ADDRESS, unitPrice, durationSec);
        console.log(dataCreateOrder);
    }
};
BuyResourceUsingPrivateKey()
<?php

// Configuration constants
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 = 3600; // 1 hour

function getEstimate($resourceAmount, $durationSec) {
    $url = TRONSAVE_API_URL . "/v2/estimate-buy-resource";
    $body = [
        'resourceAmount' => $resourceAmount,
        'unitPrice' => "MEDIUM",
        'resourceType' => RESOURCE_TYPE,
        'durationSec' => $durationSec,
    ];

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($body),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => ['Content-Type: application/json']
    ]);

    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true);
}

function getSignedTransaction($estimateTrx, $requestAddress) {
    // 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' => $requestAddress,
                            'to_address' => TRONSAVE_RECEIVER_ADDRESS
                        ],
                        'type_url' => 'type.googleapis.com/protocol.TransferContract'
                    ],
                    'type' => 'TransferContract'
                ]
            ]
        ]
    ];
}

function createOrder($resourceAmount, $signedTx, $receiverAddress, $unitPrice, $durationSec) {
    $url = TRONSAVE_API_URL . "/v2/buy-resource";
    $body = [
        'resourceType' => RESOURCE_TYPE,
        'resourceAmount' => $resourceAmount,
        'unitPrice' => $unitPrice,
        'allowPartialFill' => true,
        'receiver' => $receiverAddress,
        'durationSec' => $durationSec,
        'signedTx' => $signedTx
    ];

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($body),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => ['Content-Type: application/json']
    ]);

    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true);
}

function buyResourceUsingPrivateKey() {
    try {
        // Step 1: Estimate the cost
        $estimateData = getEstimate(BUY_AMOUNT, DURATION_SEC);
        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, REQUEST_ADDRESS);
            print_r($signedTx);

            // Step 3: Create order
            $dataCreateOrder = createOrder(BUY_AMOUNT, $signedTx, RECEIVER_ADDRESS, $unitPrice, $durationSec);
            print_r($dataCreateOrder);
        }
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage() . "\n";
    }
}

// Run the main function
buyResourceUsingPrivateKey();
import requests
from typing import Dict, Any

# Configuration constants
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 = 3600  # 1 hour

def get_estimate(resource_amount: int, duration_sec: int) -> Dict[str, Any]:
    url = f"{TRONSAVE_API_URL}/v2/estimate-buy-resource"
    body = {
        'resourceAmount': resource_amount,
        'unitPrice': "MEDIUM",
        'resourceType': RESOURCE_TYPE,
        'durationSec': duration_sec,
    }
    
    response = requests.post(url, json=body)
    return response.json()

def get_signed_transaction(estimate_trx: int, request_address: str) -> Dict[str, Any]:
    # 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(resource_amount: int, signed_tx: Dict[str, Any], 
                receiver_address: str, unit_price: int, duration_sec: int) -> Dict[str, Any]:
    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
    }
    
    response = requests.post(url, json=body)
    return response.json()

def buy_resource_using_private_key() -> None:
    try:
        # Step 1: Estimate the cost
        estimate_data = get_estimate(BUY_AMOUNT, DURATION_SEC)
        if estimate_data['error']:
            raise Exception(estimate_data['message'])
        print(estimate_data)

        data = estimate_data['data']
        unit_price = data['unitPrice']
        estimate_trx = data['estimateTrx']
        duration_sec = data['durationSec']
        available_resource = 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, REQUEST_ADDRESS)
            print(signed_tx)

            # Step 3: Create order
            data_create_order = create_order(
                BUY_AMOUNT, signed_tx, RECEIVER_ADDRESS, unit_price, duration_sec)
            print(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/