5 分钟内完成您的首次 API 调用
本指南将通过 Python 带您完成一次完整的能量购买流程 —— 从查询余额到确认代理。
前置条件
您需要一个 API key 才能跟随本教程操作。如果尚未创建,请在仪表盘中创建。
第 1 步:查询账户
首先查询您的余额和充值地址。
import requests
API_KEY = "ta_your_key_here"
BASE_URL = "https://tronagg.ai/api/v1"
response = requests.get(
f"{BASE_URL}/account",
headers={"X-API-Key": API_KEY}
)
account = response.json()
print(f"Balance: {account['balance_trx']} TRX")
print(f"Deposit to: {account['deposit_address']}")
如果余额为零,请将 TRX 充值到响应中返回的 deposit_address,或通过仪表盘的充值页面充值。
第 2 步:获取价格预估
在确认购买之前,先查询购买能量需要多少费用。
response = requests.get(
f"{BASE_URL}/estimate",
headers={"X-API-Key": API_KEY},
params={"resource_amount": 100000, "duration": "1h"}
)
estimate = response.json()
print(f"100K energy costs {estimate['total_price_trx']} TRX")
第 3 步:购买能量
通过指定接收方地址和数量来购买能量。费用将立即从您的余额中扣除。
response = requests.post(
f"{BASE_URL}/buy",
headers={"X-API-Key": API_KEY, "Content-Type": "application/json"},
json={
"receiver_address": "TYourReceiverAddress...",
"resource_amount": 100000,
"duration": "1h",
}
)
purchase = response.json()
print(f"Order: {purchase['order_id']}, Status: {purchase['status']}")
提示
请将 TYourReceiverAddress... 替换为实际需要能量的 TRON 地址,通常是调用智能合约的那个地址。
第 4 步:查询订单状态
订单通常在数秒内完成。使用购买响应中的订单 ID 查询其状态。
order_id = purchase["order_id"]
response = requests.get(
f"{BASE_URL}/order/{order_id}",
headers={"X-API-Key": API_KEY}
)
order = response.json()
print(f"Status: {order['status']}")
if order["status"] == "completed":
print(f"Energy delegated! TXs: {order['delegation_txids']}")
可能的状态:pending → completed 或 failed。如需生产级的超时轮询实现,请参见代码示例。