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 扩展订单

这是使用 API 密钥通过 API 扩展订单的完整示例。

Previous使用 API 密钥通过 API 购买能源Next使用私钥通过 API 扩展订单

Last updated 19 days ago

如何获取api密钥

要求:TronWeb 版本 5.3.2

npm i tronweb@5.3.2 @noble/secp256k1@1.7.1

(了解更多:)

const API_KEY = `your-api-key`;
const TRONSAVE_API_URL = "https://api.tronsave.io"
const RECEIVER = "your-receiver-address"
const RESOURCE_TYPE = "ENERGY"

const GetEstimateExtendData = async (extendTo, maxPriceAccepted) => {
    const url = TRONSAVE_API_URL + `/v2/get-extendable-delegates`
    const body = {
        extendTo, //time in seconds you want to extend to
        receiver: RECEIVER,   //the address that receives the resource delegate
        maxPriceAccepted, //Optional. Number the maximum price you want to pay to extend
        resourceType: RESOURCE_TYPE, //ENERGY or BANDWIDTH. optional. The default is ENERGY
    }
    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  
       {
            "error": false,
            "message": "Success",
            "data": {
                "extendOrderBook": [
                    {
                        "price": 784,
                        "value": 1002
                    }
                ],
                "totalDelegateAmount": 5003,
                "totalAvailableExtendAmount": 5003,
                "totalEstimateTrx": 4085783,
                "isAbleToExtend": true,
                "yourBalance": 2377366851,
                "extendData": [
                    {
                        "delegator": "TGGVrYaT8Xoos...6dmSZkohGGcouYL4",
                        "isExtend": true,
                        "extraAmount": 0,
                        "extendTo": 1745833276
                    },
                    {
                        "delegator": "TQBV7xU489Rq8Z...zBhJMdrDr51wA2",
                        "isExtend": true,
                        "extraAmount": 0,
                        "extendTo": 1745833276
                    },
                    {
                        "delegator": "TSHZv6xsYHMRCbdVh...qNozxaPPjDR6",
                        "isExtend": true,
                        "extraAmount": 0,
                        "extendTo": 1745833276
                    }
                ]
            }
        }
     */
    return response
}

/**
 * @param {number} extendTo the time in seconds you want to extend to
 * @param {boolean} maxPriceAccepted number maximum price you want to pay to extend
 * @returns 
 */
const SendExtendRequest = async (extendTo, maxPriceAccepted) => {
    const url = TRONSAVE_API_URL + `/v2/extend-request`
    // Get estimate extendable delegates
    const estimateResponse = await GetEstimateExtendData(extendTo, maxPriceAccepted)
    const extendData = estimateResponse.data?.extendData
    if (extendData && extendData.length) { 
        const body = {
            extendData: extendData,
            receiver: RECEIVER,
        }
        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 
         {
            error: false,
            message: 'Success',
            data: { orderId: '680b5ac7b09a385fb3d582ff' }
            }
         */
        return response
    }
    return []
}

//Example run code
const ClientCode = async () => { 
    const extendTo = Math.floor(new Date().getTime() / 1000) + 3 * 86400 //Extend to 3 next days
    const maxPriceAccepted = 900
    const response = await SendExtendRequest(extendTo, maxPriceAccepted)
    console.log(response)
}


ClientCode()
//<?php

// Configuration
const API_KEY = 'your-api-key';
const TRONSAVE_API_URL = "https://api.tronsave.io";
const RECEIVER = "your-receiver-address";
const RESOURCE_TYPE = "ENERGY";

/**
 * Get estimate extend data
 * @param int $extendTo
 * @param int $maxPriceAccepted
 * @return array
 */
function getEstimateExtendData(int $extendTo, int $maxPriceAccepted): array {
    $url = TRONSAVE_API_URL . "/v2/get-extendable-delegates";
    $body = [
        'extendTo' => $extendTo,
        'receiver' => RECEIVER,
        'maxPriceAccepted' => $maxPriceAccepted,
        'resourceType' => RESOURCE_TYPE,
    ];

    $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, [
        'apikey: ' . API_KEY,
        'Content-Type: application/json'
    ]);
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true);
}

/**
 * Send extend request
 * @param int $extendTo
 * @param int $maxPriceAccepted
 * @return array
 */
function sendExtendRequest(int $extendTo, int $maxPriceAccepted): array {
    $url = TRONSAVE_API_URL . "/v2/extend-request";
    $estimateResponse = getEstimateExtendData($extendTo, $maxPriceAccepted);
    $extendData = $estimateResponse['data']['extendData'] ?? [];

    if (!empty($extendData)) {
        $body = [
            'extendData' => $extendData,
            'receiver' => RECEIVER,
        ];

        $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, [
            'apikey: ' . API_KEY,
            'Content-Type: application/json'
        ]);
        $response = curl_exec($ch);
        curl_close($ch);
        return json_decode($response, true);
    }

    return [];
}

// Example run code
try {
    $extendTo = time() + (3 * 86400); // Extend to 3 next days
    $maxPriceAccepted = 900;
    $response = sendExtendRequest($extendTo, $maxPriceAccepted);
    print_r($response);
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
} 
import time
import requests
from typing import Dict, Any, Optional

# Configuration
API_KEY = 'your-api-key'
TRONSAVE_API_URL = "https://api.tronsave.io"
RECEIVER = "your-receiver-address"
RESOURCE_TYPE = "ENERGY"

def get_estimate_extend_data(extend_to: int, max_price_accepted: int) -> Dict[str, Any]:
    """Get estimate extend data"""
    url = f"{TRONSAVE_API_URL}/v2/get-extendable-delegates"
    headers = {
        'apikey': API_KEY,
        'Content-Type': 'application/json'
    }
    
    body = {
        'extendTo': extend_to,
        'receiver': RECEIVER,
        'maxPriceAccepted': max_price_accepted,
        'resourceType': RESOURCE_TYPE,
    }
    
    response = requests.post(url, headers=headers, json=body)
    return response.json()

def send_extend_request(extend_to: int, max_price_accepted: int) -> Dict[str, Any]:
    """Send extend request"""
    url = f"{TRONSAVE_API_URL}/v2/extend-request"
    headers = {
        'apikey': API_KEY,
        'Content-Type': 'application/json'
    }
    
    estimate_response = get_estimate_extend_data(extend_to, max_price_accepted)
    extend_data = estimate_response.get('data', {}).get('extendData', [])

    if extend_data:
        body = {
            'extendData': extend_data,
            'receiver': RECEIVER,
        }
        
        response = requests.post(url, headers=headers, json=body)
        return response.json()

    return {}

def main() -> None:
    """Main function"""
    try:
        extend_to = int(time.time()) + (3 * 86400)  # Extend to 3 next days
        max_price_accepted = 900
        response = send_extend_request(extend_to, max_price_accepted)
        print("Response:", response)
    except Exception as e:
        print(f"Error: {str(e)}")

if __name__ == "__main__":
    main() 

👨‍💻
选项 1:在 Tronsave 网站上生成 API 密钥。
选项 2:在 Telegram 上生成 API 密钥。
https://tronweb.network/docu/docs/5.3.2/Release%20Note/