Code Examples
Copy-paste Python and JavaScript snippets for every API endpoint. Each example includes error handling.
For a narrative walkthrough, see the Quickstart.
Setup
Python
import os
import requests
API_KEY = os.environ.get("TRONAGG_API_KEY", "ta_your_key_here")
BASE_URL = "https://tronagg.ai/api/v1"
HEADERS = {"X-API-Key": API_KEY}
JavaScript
const API_KEY = process.env.TRONAGG_API_KEY || "ta_your_key_here";
const BASE_URL = "https://tronagg.ai/api/v1";
const HEADERS = { "X-API-Key": API_KEY };
Get Account Info
Python
response = requests.get(f"{BASE_URL}/account", headers=HEADERS)
data = response.json()
print(f"Balance: {data['balance_trx']} TRX")
print(f"Deposit to: {data['deposit_address']}")
print(f"Wallet: {data['wallet_address']}")
JavaScript
const response = await fetch(`${BASE_URL}/account`, { headers: HEADERS });
const data = await response.json();
console.log(`Balance: ${data.balance_trx} TRX`);
console.log(`Deposit to: ${data.deposit_address}`);
console.log(`Wallet: ${data.wallet_address}`);
Get Price Estimate
Python
response = requests.get(
f"{BASE_URL}/estimate",
headers=HEADERS,
params={"resource_amount": 100000, "duration": "1h"}
)
data = response.json()
print(f"Unit price: {data['unit_price_sun']} SUN per energy")
print(f"Total: {data['total_price_trx']} TRX ({data['total_price_sun']} SUN)")
JavaScript
const params = new URLSearchParams({
resource_amount: "100000",
duration: "1h",
});
const response = await fetch(`${BASE_URL}/estimate?${params}`, {
headers: HEADERS,
});
const data = await response.json();
console.log(`Unit price: ${data.unit_price_sun} SUN per energy`);
console.log(`Total: ${data.total_price_trx} TRX (${data.total_price_sun} SUN)`);
Buy Energy
Python
response = requests.post(
f"{BASE_URL}/buy",
headers={**HEADERS, "Content-Type": "application/json"},
json={
"receiver_address": "TReceiverAddress...",
"resource_amount": 100000,
"duration": "1h",
}
)
if response.status_code == 201:
data = response.json()
print(f"Order created: {data['order_id']}")
print(f"Cost: {data['total_price_trx']} TRX")
print(f"Remaining balance: {data['balance_after_sun'] / 1_000_000} TRX")
elif response.status_code == 400:
error = response.json()
if error.get("error") == "insufficient_balance":
print(f"Not enough balance. Have: {error['current_balance']} SUN, need: {error['required_amount']} SUN")
else:
print(f"Error: {error}")
JavaScript
const response = await fetch(`${BASE_URL}/buy`, {
method: "POST",
headers: { ...HEADERS, "Content-Type": "application/json" },
body: JSON.stringify({
receiver_address: "TReceiverAddress...",
resource_amount: 100000,
duration: "1h",
}),
});
const data = await response.json();
if (response.status === 201) {
console.log(`Order created: ${data.order_id}`);
console.log(`Cost: ${data.total_price_trx} TRX`);
console.log(`Remaining balance: ${data.balance_after_sun / 1_000_000} TRX`);
} else if (response.status === 400) {
if (data.error === "insufficient_balance") {
console.log(`Not enough balance. Have: ${data.current_balance} SUN, need: ${data.required_amount} SUN`);
} else {
console.error("Error:", data);
}
}
Check Order Status
Retrieve order details. Poll in a loop to wait for completion — orders typically resolve within seconds.
Python
import time
order_id = "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
def wait_for_order(order_id, timeout=300, poll_interval=5):
"""Poll until completed or failed."""
start = time.time()
while time.time() - start < timeout:
response = requests.get(f"{BASE_URL}/order/{order_id}", headers=HEADERS)
order = response.json()
if order["status"] in ("completed", "failed"):
return order
print(f"Status: {order['status']}... waiting {poll_interval}s")
time.sleep(poll_interval)
raise TimeoutError(f"Order {order_id} did not complete within {timeout}s")
order = wait_for_order(order_id)
if order["status"] == "completed":
print(f"Delegation TXs: {order['delegation_txids']}")
else:
print(f"Error: {order['error_message']}")
JavaScript
const orderId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
async function waitForOrder(orderId, timeout = 300000, pollInterval = 5000) {
const start = Date.now();
while (Date.now() - start < timeout) {
const response = await fetch(`${BASE_URL}/order/${orderId}`, {
headers: HEADERS,
});
const order = await response.json();
if (order.status === "completed" || order.status === "failed") {
return order;
}
console.log(`Status: ${order.status}... waiting ${pollInterval / 1000}s`);
await new Promise((r) => setTimeout(r, pollInterval));
}
throw new Error(`Order ${orderId} did not complete within ${timeout}ms`);
}
const order = await waitForOrder(orderId);
if (order.status === "completed") {
console.log(`Delegation TXs: ${order.delegation_txids}`);
} else {
console.log(`Error: ${order.error_message}`);
}