# PowerSun — Complete AI Agent Guide > Full reference for integrating with the TRON Energy & Bandwidth marketplace and DEX swap aggregator. > For a shorter overview, see /llms.txt ## Overview PowerSun lets AI agents buy and sell TRON network resources (Energy and Bandwidth) and swap tokens on SunSwap DEX with automatic energy delegation. Energy is required to execute smart contracts on TRON. Renting it saves 50-80% vs burning TRX. Token swaps use SunSwap V2 Smart Router — PowerSun delegates energy for the swap transaction, so you only pay the energy rental cost instead of burning TRX. ## Base URL https://powersun.vip ## Authentication Methods ### 1. API Key (recommended for repeat usage) ``` # Step 1: Register POST /api/v2/agent/register Content-Type: application/json {"address": "TYourTronAddress..."} # Response: {"challenge": "Sign this message: powersun-...", "expiresAt": "..."} # Step 2: Verify signature POST /api/v2/agent/verify {"address": "TYourTronAddress...", "signature": "0x...hex..."} # Response: {"apiKey": "ps_...", "address": "T..."} # Step 3: Use API key in all requests X-API-Key: ps_... ``` #### Funding an API-key balance - For a direct top-up of the shared API balance address without an active PowerSun payment intent, send TRX from the registered TRON address. - An exchange transfer without an active PowerSun payment intent may appear on-chain from the exchange hot wallet and may not be credited automatically. - This sender-matching warning applies to the shared API balance address. It does not apply to a personal deposit address shown in the PowerSun Telegram Mini App. - If a transfer is not credited, contact @powersun_vip with the registered address and transaction ID: https://t.me/powersun_vip ### 2. HTTP 402 Pay-per-use (TRX, no registration) ``` # Step 1: Request without API key POST /api/v2/agent/buy-energy {"targetAddress": "T...", "energyAmount": 65000, "duration": "1h"} # Response: 402 Payment Required # Body includes: intentId, depositAddress, requiredAmountTrx, expiresAt # Step 2: Send exactly requiredAmountTrx once to depositAddress # If the request included senderAddress, the confirmed transaction must have that # exact on-chain sender. If senderAddress was omitted, a different sender, including # an exchange hot wallet, can match only by the exact unique amount. # The transaction must be confirmed and found by PowerSun before expiresAt. # Step 3: Poll for completion GET /api/v2/agent/payment-status/{intentId} ``` Do not reuse expired payment details. If the payment is not matched, do not send again; contact @powersun_vip with the intent ID and transaction ID: https://t.me/powersun_vip ### 3. x402 v2 USDC on Base (buy-energy only, no registration) ``` # Step 1: Request a two-minute quote POST /api/v2/agent/buy-energy {"targetAddress": "T...", "txCount": 1, "txType": "trc20_transfer", "durationMinutes": 60} # Response 402: x402Version: 2, resource, accepts[] # accepts[0]: scheme "exact", network "eip155:8453", # asset "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", # amount (USDC atomic units), payTo, maxTimeoutSeconds: 120, # extra: {name: "USD Coin", version: "2", intentId: "pi_x402_0123456789abcdef"} # Step 2: Sign EIP-3009 using the exact quote and USD Coin / 2 domain on Base # Base64-encode {x402Version: 2, resource, accepted: accepts[0], # payload: {signature, authorization: {from, to, value, validAfter, validBefore, nonce}}} # Preserve accepted.extra.intentId and all original requirements. # Step 3: Resend the original request POST /api/v2/agent/buy-energy PAYMENT-SIGNATURE: {"targetAddress": "T...", "txCount": 1, "txType": "trc20_transfer", "durationMinutes": 60} # HTTP 200: final result, with order or order: null if credited without delivery # HTTP 202: pending; poll checkStatusUrl using the same intent ID # Do not sign another payment or pay again while confirmation is pending. ``` ## API Endpoints ### POST /api/v2/agent/estimate Estimate cost before buying. ``` Request: {"targetAddress": "T...", "energyAmount": 65000, "duration": "1h"} Response: {"estimate": {"totalCostSun": 3250000, "totalCostTrx": 3.25, "pricePerUnit": 50, ...}} ``` ### POST /api/v2/agent/buy-energy Purchase energy delegation. ``` Request: {"targetAddress": "T...", "energyAmount": 65000, "duration": "1h"} Headers: X-API-Key: ps_... Response: {"order": {"orderId": "uuid", "status": "pending", ...}} ``` ### GET /api/v2/agent/balance Check account balance and deposit info. ``` Headers: X-API-Key: ps_... Response: {"address": "T...", "balanceTrx": 15.5, "balanceSun": 15500000, ...} ``` ### GET /api/v2/agent/order/{orderId} Track order status and delegation progress. ### GET /api/v2/agent/payment-status/{intentId} Poll 402 payment intent status (no auth needed). ### POST /api/v2/agent/broadcast Broadcast a pre-signed TRON transaction with automatic energy delegation. Use an API key for balance deduction, or request without authentication for TRX 402 instructions. USDC x402 is supported only by /buy-energy. \`\`\` Request body: Pre-signed TRON transaction object {txID, raw_data, raw_data_hex, signature} With X-API-Key: broadcasts immediately, cost deducted from balance Without auth: 402 response with energy cost estimate and TRX payment instructions \`\`\` ### POST /api/v2/agent/swap Get swap quote for SunSwap DEX with energy cost estimate. \`\`\` Request: {"fromToken": "TRX", "toToken": "USDT", "amountIn": "10000000", "slippageBps": 100} Headers: X-API-Key: ps_... Response: { "quote": {"fromSymbol": "TRX", "toSymbol": "USDT", "expectedAmountOut": "...", "amountOutMin": "...", "route": [...]}, "energy": {"estimatedUnits": 350000, "costSun": 17500000, "costTrx": 17.5}, "unsignedTx": {...}, "nextAction": {"action": "sign_and_broadcast", "broadcastUrl": "/api/v2/agent/broadcast"} } \`\`\` Supported tokens: TRX, USDT, USDC, USDD, SUN, BTT, WIN, JST, or any TRC-20 contract address. ## Wallet Integration — pay-per-transaction broadcast (Paygo, partner API) For wallet products: end users send TRC-20 tokens cheaper than the protocol burn fee, with no PowerSun account, no deposit, and no custody. The user pays per transfer, in TRX, from their own wallet. Both transactions are signed inside the wallet; PowerSun supplies energy/bandwidth and broadcasts server-side. Requires a partner API key enabled for wallet integration (fees are set per partner) — contact partnerships@powersun.vip. Docs: https://powersun.vip/api-docs (Wallet Integration tab). ### Flow (one transfer) 1. Before signing, call POST /api/v1/paygo/estimate — an EXACT fee for this sender→recipient pair, computed by live simulation on the TRON node (a first-ever token transfer to a fresh recipient costs ~2x the energy and is priced in). The quote is a final price with a 10-minute lifetime. 2. The user confirms once; the wallet signs TWO transactions: the token transfer (expiration must be ≥ 5 minutes — in TronWeb call extendExpiration BEFORE signing) and a TRX payment of exactly feeTrx to payTo. POST /api/v1/paygo/submit hands both over; the wallet broadcasts nothing itself. 3. PowerSun executes server-side: payment first, then resource delegation and the transfer broadcast. Poll GET /api/v1/paygo/order/{orderId} (2-3s): received → paying → paid → delegating → broadcasting → confirmed → completed. Transfer confirms on-chain in ~15-25 seconds. ### Example \`\`\` POST /api/v1/paygo/estimate Headers: X-API-Key: Request: {"from": "TSender…", "to": "TRecipient…", "tokenContract": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "amount": "25000000"} Response: {"estimateId": "pe_7c11d9a0", "energy": 64285, "bandwidth": 613, "burnCostTrx": "6.7735", "feeTrx": "5.6332", "payTo": "TPowerSun…", "validUntil": "…", "recipientInitialized": true} POST /api/v1/paygo/submit Request: {"estimateId": "pe_7c11d9a0", "signedTransaction": {…}, "signedPayment": {…}} Response: {"orderId": "po_31bb02e4", "status": "received"} \`\`\` (Numbers illustrative — fees are agreed per partner.) ### Guarantees - The payment is ALWAYS broadcast first. Failure before the payment confirms = the user's funds never moved. - Any failure AFTER a confirmed payment triggers an automatic full on-chain refund (usually within a minute, exactly once; refund txId in the order status; refund bandwidth is on PowerSun). - feeTrx is final: no surcharges and no "estimate vs actual" adjustments after execution. - Estimates also reject transfers that would fail on-chain (insufficient balance, blacklist) BEFORE anyone signs. - Idempotent submit: re-sending the same signed pair returns the existing order. ## MCP Tools (27 total) Connect: POST /mcp (Streamable HTTP transport) Optional auth: X-API-Key header (or use register + verify_registration to get one) ### Onboarding Tools (public, no auth needed to start): - **register** — Start agent registration with TRON address, get challenge to sign - **verify_registration** — Verify signed challenge, receive API key, session upgraded in-place - **build_permission_transaction** — Build unsigned AccountPermissionUpdate tx for granting platform permissions (auth required) - **broadcast_signed_permission_tx** — Broadcast signed permission tx and verify on-chain (auth required) ### Market Tools (public, no auth): - **get_prices** — Current energy/bandwidth prices for all duration tiers - **estimate_cost** — Calculate cost for a specific energy/bandwidth amount and duration - **get_available_resources** — Check available energy/bandwidth in the marketplace - **get_market_overview** — Full market snapshot (prices + availability + order stats) ### Buyer Tools (auth required): - **get_balance** — Account balance, shared deposit address, sender-matching policy, and support contact - **buy_energy** — Purchase energy delegation for a target address - **broadcast_transaction** — Broadcast pre-signed TRON tx with energy - **get_orders** — List your recent orders - **get_order_status** — Detailed order status with fills - **get_deposit_info** — Get the shared deposit address, safe top-up instructions, and support contact ### Swap Tools (auth required): - **get_swap_quote** — Get price quote and unsigned TX for SunSwap DEX token swap (TRX, USDT, USDC, SUN, BTT, WIN, JST, any TRC-20) - **execute_swap** — Execute pre-signed swap TX with automatic energy delegation ### Seller Tools (auth required): - **register_pool** — Register TRON address as a selling pool - **get_pool_stats** — Pool performance and delegation stats - **get_earnings** — Earnings breakdown and history - **get_auto_selling_config** — Current auto-selling configuration - **configure_auto_selling** — Enable/disable auto-selling with price settings - **get_pool_delegations** — Active delegations from your pool - **withdraw_earnings** — MCP withdrawal execution is unavailable; use the withdrawal flow at https://powersun.vip - **get_onchain_status** — Live blockchain state (balance, frozen, votes, rewards) - **check_pool_permissions** — Verify platform has required on-chain permissions - **trigger_vote** — Vote for Super Representative to earn staking rewards - **get_auto_action_history** — View auto-action execution logs (stake, vote, claim) ## Pricing - Energy: from 50 SUN per unit per day - Typical TRC20 transfer: ~65,000 energy (~3 TRX for 1 hour) - DEX swap: ~350,000 energy (~0.3 TRX energy cost), no extra commission - Savings: 50-80% compared to TRX burn - Available durations: 1h, 3h, 6h, 12h, 1d, 3d, 7d, 14d, 30d ## Rate Limits - Authenticated: 100 req/min - Unauthenticated: 20 req/min - MCP sessions: no hard limit (fair use) ## Error Codes - 400: Bad request (missing/invalid parameters) - 401: Unauthorized (invalid or missing API key) - 402: Payment Required (use 402 flow or x402) - 404: Resource not found - 429: Rate limit exceeded - 500: Internal server error ## Supported Networks - TRON mainnet (tron:mainnet) — TRX native transfers - Base (eip155:8453) — USDC via x402 v2 for buy-energy only (contract: 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913) ## SDKs & Integrations ### TypeScript (npm) \`\`\`bash npm install @powersun/mcp-client \`\`\` \`\`\`typescript import { PowerSun, PaymentRequiredError } from '@powersun/mcp-client'; const ps = new PowerSun({ apiKey: 'ps_...' }); // Market data (no auth) const prices = await ps.market.getPrices(); const estimate = await ps.market.estimateCost({ txCount: 10, durationMinutes: 60 }); // Buy energy const order = await ps.buyer.buyEnergy({ targetAddress: 'T...', txCount: 5, durationMinutes: 60 }); // HTTP 402 flow (no API key) const ps402 = new PowerSun(); try { await ps402.buyer.buyEnergy({ targetAddress: 'T...', txCount: 1 }); } catch (err) { if (err instanceof PaymentRequiredError) { // err.payment.depositAddress, err.payment.requiredAmountTrx } } \`\`\` ### LangChain (PyPI) \`\`\`bash pip install langchain-powersun \`\`\` \`\`\`python from langchain_powersun import PowerSunToolkit tools = PowerSunToolkit(api_key="ps_...").get_tools() # 12 tools # Use with create_react_agent or create_tool_calling_agent \`\`\` ### CrewAI (PyPI) \`\`\`bash pip install crewai-powersun \`\`\` \`\`\`python from crewai_powersun import PowerSunBuyEnergyTool, PowerSunEstimateCostTool # Use directly in CrewAI Agent tools=[...] # Supports POWERSUN_API_KEY env var \`\`\` ### GitHub Action \`\`\`yaml - uses: Hovsteder/tron-energy-action@v1 with: target-address: ${{ secrets.DEPLOYER_ADDRESS }} tx-count: '10' api-key: ${{ secrets.POWERSUN_API_KEY }} \`\`\` ## Discovery Files - OpenAPI spec: /openapi.json - Short LLM guide: /llms.txt - Full LLM guide: /llms-full.txt (this file) - Agent descriptor: /.well-known/agents.json - AI plugin manifest: /.well-known/ai-plugin.json ## SDK Links - Support: https://t.me/powersun_vip (@powersun_vip) - npm: https://www.npmjs.com/package/@powersun/mcp-client - PyPI (LangChain): https://pypi.org/project/langchain-powersun/ - PyPI (CrewAI): https://pypi.org/project/crewai-powersun/ - GitHub Action: https://github.com/Hovsteder/tron-energy-action - GitHub MCP Server: https://github.com/Hovsteder/powersun-tron-mcp