Code Examples
Copy-paste Python and JavaScript snippets for the core purchase flow: account, estimate, buy, and order status. Each example includes error handling. For the history endpoints (orders, transactions, deposits), see their reference pages.
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'] or '(none linked)'}")
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 || "(none linked)"}`);
Get Price Estimate
Python
from decimal import Decimal
response = requests.get(
f"{BASE_URL}/estimate",
headers=HEADERS,
# receiver_address is optional; pass it to include the one-time activation fee
# when the address has not been activated on TRON yet
params={"resource_amount": 100000, "receiver_address": "TReceiverAddress..."},
)
data = response.json()
print(f"Unit price: {Decimal(data['unit_price_sun'])} SUN per energy") # decimal string
print(f"Total: {data['total_price_trx']} TRX ({data['total_price_sun']} SUN)")
print(f"Activation fee included: {data['activation_fee_trx']} TRX")
print(f"Order limits: {data['min_amount']} - {data['max_amount']} energy") # None = no limit
JavaScript
const params = new URLSearchParams({
resource_amount: "100000",
// optional: include the one-time activation fee if the address is not activated yet
receiver_address: "TReceiverAddress...",
});
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`); // decimal string
console.log(`Total: ${data.total_price_trx} TRX (${data.total_price_sun} SUN)`);
console.log(`Activation fee included: ${data.activation_fee_trx} TRX`);
console.log(`Order limits: ${data.min_amount} - ${data.max_amount} energy`); // null = no limit
Buy Energy
Send an Idempotency-Key with every purchase and reuse it if you retry the same purchase — a retry then returns the original order instead of charging twice. See Idempotency.
Python
import uuid
from decimal import Decimal
idempotency_key = str(uuid.uuid4()) # reuse it if you retry this purchase
response = requests.post(
f"{BASE_URL}/buy",
headers={**HEADERS, "Idempotency-Key": idempotency_key},
json={
"receiver_address": "TReceiverAddress...",
"resource_amount": 100000,
},
)
if response.status_code == 201:
data = response.json()
print(f"Order created: {data['order_id']} ({data['status']})")
print(f"Cost: {data['total_price_trx']} TRX")
print(f"Remaining balance: {Decimal(data['balance_after_sun']) / 1_000_000} TRX")
else:
detail = response.json().get("detail")
if isinstance(detail, dict):
code = detail.get("error") or detail.get("code") # amount limits use "code"
if code == "insufficient_balance":
print(f"Not enough balance. Have: {detail['current_balance']} SUN, need: {detail['required_amount']} SUN")
elif code == "duplicate_request":
print("Still processing - retry with the same Idempotency-Key in a few seconds")
else:
print(f"Error {response.status_code} {code}: {detail.get('message', '')}")
else:
# plain-string detail (401, 429, ...) or a 422 list of field errors
print(f"Error {response.status_code}: {detail}")
JavaScript
import { randomUUID } from "node:crypto";
const idempotencyKey = randomUUID(); // reuse it if you retry this purchase
const response = await fetch(`${BASE_URL}/buy`, {
method: "POST",
headers: {
...HEADERS,
"Content-Type": "application/json",
"Idempotency-Key": idempotencyKey,
},
body: JSON.stringify({
receiver_address: "TReceiverAddress...",
resource_amount: 100000,
}),
});
const data = await response.json();
if (response.status === 201) {
console.log(`Order created: ${data.order_id} (${data.status})`);
console.log(`Cost: ${data.total_price_trx} TRX`);
console.log(`Remaining balance: ${data.balance_after_sun} SUN`); // integer SUN, no float math
} else {
const detail = data.detail;
if (detail && typeof detail === "object" && !Array.isArray(detail)) {
const code = detail.error ?? detail.code; // amount limits use "code"
if (code === "insufficient_balance") {
console.log(`Not enough balance. Have: ${detail.current_balance} SUN, need: ${detail.required_amount} SUN`);
} else if (code === "duplicate_request") {
console.log("Still processing - retry with the same Idempotency-Key in a few seconds");
} else {
console.error(`Error ${response.status} ${code}: ${detail.message ?? ""}`);
}
} else {
// plain-string detail (401, 429, ...) or a 422 list of field errors
console.error(`Error ${response.status}:`, detail);
}
}
Check Order Status
Retrieve order details. Poll in a loop to wait for completion — orders typically resolve within seconds. Statuses are upper-case; COMPLETED and FAILED are final.
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']}") # may be empty for some deliveries
else:
print(f"Error: {order['error_message']}") # FAILED orders are refunded automatically
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}`); // may be empty for some deliveries
} else {
console.log(`Error: ${order.error_message}`); // FAILED orders are refunded automatically
}