Skip to content

Repository files navigation

Tron Energy Rental via API

Node.js SDK by TronZap.com

English | Español | Português | Русский

Official Node.js SDK for the TronZap API. This SDK allows you to easily integrate with TronZap services for TRON energy rental.

TronZap.com allows you to buy TRON energy, making USDT (TRC20) transfers cheaper by significantly reducing transaction fees.

👉 Register for an API key to start using TronZap API and integrate it via the SDK.

Installation

npm install tronzap-sdk
# or
yarn add tronzap-sdk
# or
pnpm add tronzap-sdk

Check out at npm: https://www.npmjs.com/package/tronzap-sdk

Platform Support

This SDK is designed to work across multiple JavaScript/TypeScript platforms:

  • Node.js: 20 or higher
  • Bun: 1.x
  • Deno: 2.x

The tests run on all of them in CI. The SDK has no runtime dependencies and uses the built-in fetch.

Quick Start

import { TronZapClient } from 'tronzap-sdk';

// Initialize the client
const client = new TronZapClient({
  apiToken: 'your_api_token',
  apiSecret: 'your_api_secret',
  // Optional: base URL, timeout in milliseconds (30000 by default) and your own fetch
  // baseUrl: 'https://api.tronzap.com',
  // timeout: 30_000,
  // fetch: myFetch,
});

// Get available services
const services = await client.getServices();
console.log(services);

// Get account balance
const balance = await client.getBalance();
console.log(balance);

// Get address info (resources and balances)
const addressInfo = await client.getAddressInfo('TRX_ADDRESS');
console.log(addressInfo);

// Estimate energy amount for a USDT (TRC20) transfer; pass a token contract address as the third argument for another token
const estimate = await client.estimateEnergy(
  'FROM_TRX_ADDRESS',
  'TO_TRX_ADDRESS'
);
console.log(estimate);

// Calculate energy cost
const calculation = await client.calculate(
  'TRON_WALLET_ADDRESS',
  65000  // Energy amount
);
console.log(calculation);

// Create energy transaction
const transaction = await client.createEnergyTransaction(
  'TRON_WALLET_ADDRESS',
  65000, // Energy amount
  1, // Duration (hours): one of the durations getServices() lists
  'my-tx-id',  // Optional external ID
  true        // Optional: activate address if needed
);
console.log(transaction);

// Buy bandwidth
const bandwidth = await client.createBandwidthTransaction(
  'TRON_WALLET_ADDRESS',
  345,
  'bandwidth-1'
);
console.log(bandwidth);

// Buy a resource bundle (energy + bandwidth in one transaction)
const bundle = await client.createResourceBundleTransaction(
  'TRON_WALLET_ADDRESS',
  65000, // energy amount
  345,   // bandwidth amount
  1,     // duration (hours)
  'bundle-1', // optional external ID
  true        // optional: activate address
);
console.log(bundle);

// Check transaction status
const status = await client.checkTransaction('TRANSACTION_ID');
console.log(status);

// Create AML check
const amlCheck = await client.createAmlCheck(
  'address',
  'TRX',
  'TRON_WALLET_ADDRESS'
);
console.log(amlCheck);

// Check AML status
const amlStatus = await client.checkAmlStatus(amlCheck.id);
console.log(amlStatus);

// Get direct recharge information
const rechargeInfo = await client.getDirectRechargeInfo();
console.log(rechargeInfo);

// Every method takes request options as its last argument: a timeout or an AbortSignal
// Aborting with controller.abort() rejects the call with the signal's reason
const controller = new AbortController();
const quickBalance = await client.getBalance({ timeout: 5_000, signal: controller.signal });

Features

  • Full TypeScript support
  • Cross-platform compatibility (Node.js, Bun, Deno)
  • Request timeouts and cancellation with AbortSignal
  • Get available services
  • Get AML services
  • Get account balance
  • Get address info (resources and balances)
  • Calculate energy cost
  • Create address activation transactions
  • Create energy purchase transactions
  • Create bandwidth purchase transactions
  • Create resource bundle transactions (energy + bandwidth in one purchase)
  • Create and track AML checks
  • Check transaction status
  • Get direct recharge information
  • List subscription plans, start, check and stop subscriptions, subscription history

Requirements

  • Node.js 20 or higher, Bun 1.x or Deno 2.x

AML Checks

const addressCheck = await client.createAmlCheck('address', 'TRX', 'TRON_WALLET_ADDRESS');

// or a transaction hash: network, recipient address, hash and direction
const hashCheck = await client.createAmlCheck('hash', 'BTC', 'BTC_RECIPIENT_ADDRESS', 'TX_HASH', 'withdrawal');

For a hash check, address is the recipient address of the transaction, where the funds were received, and the direction says which side you are on: 'deposit' if the funds were sent to your address (address is your address), 'withdrawal' if you sent them (address is the external recipient's address). The risk is scored for the counterparty: the sender of a deposit, the recipient of a withdrawal. When the direction is omitted, the SDK sends 'deposit'.

Subscriptions

A subscription keeps an address supplied with energy for every transaction until it is stopped or runs out of days or transactions. Pick a plan from getSubscriptions(), an object keyed by plan in the API's order, and pass its key, such as 'unlimited_energy', not the plan's numeric id. Starting a subscription charges the plan's initial price.

const plans = await client.getSubscriptions();
for (const [subscriptionId, plan] of Object.entries(plans)) {
  console.log(subscriptionId, plan.initial_price, plan.price);
}

const subscription = await client.startSubscription(
  'unlimited_energy',
  'TRON_WALLET_ADDRESS',
  30, // 0 for no time limit
  0,  // 0 for no limit
  'subscription-42' // optional external ID
);

await client.checkSubscription(undefined, 'subscription-42');
await client.stopSubscription(subscription.id);

const history = await client.getSubscriptionHistory(1, 10, 'active');

durationDays (in days, unlike the hours of transactions) and transactionsLimit default to 0, which means no limit. checkSubscription and stopSubscription take the subscription id, its externalId, or both, like checkTransaction. History paging defaults to page 1 with 10 items.

Start, check and stop return the subscription with its params; the history items carry the usage counters transactions_used, energy_used and total_price instead. A subscription with a transactions limit cannot be stopped (ErrorCode.CANNOT_STOP_SUBSCRIPTION).

Error Handling

The SDK uses a hierarchy of error classes for precise error handling:

TronZapError
├── ApiError             — API-level errors (response code != 0)
├── InvalidRequestError  — Invalid arguments, rejected before sending
├── NetworkError         — Network/connectivity errors
│   ├── ConnectionError  — Could not connect to server
│   ├── TimeoutError     — Request timed out
│   └── SslError         — SSL/TLS errors
└── HttpError            — HTTP non-2xx responses
    ├── RateLimitError   — HTTP 429 Too Many Requests
    ├── UnauthorizedError — HTTP 401/403
    └── ServerError      — HTTP 5xx errors

Example

import {
  TronZapClient,
  ApiError,
  HttpError,
  InvalidRequestError,
  NetworkError,
  RateLimitError,
  ServerError,
  SslError,
  TimeoutError,
  TronZapError,
  UnauthorizedError,
  ErrorCode,
} from 'tronzap-sdk';

const client = new TronZapClient({
  apiToken: 'your_api_token',
  apiSecret: 'your_api_secret',
});

try {
  const transaction = await client.createEnergyTransaction('TRX_ADDRESS', 65000, 1);
} catch (error) {
  if (error instanceof ApiError) {
    // API-level error (invalid params, insufficient funds, etc.)
    console.error(`API error [${error.code}]: ${error.message}`);

    // Error key alias, e.g. "invalid_tron_address" or "invalid_tron_address.from_address"
    if (error.errorKey) {
      console.error(`Error key: ${error.errorKey}`);
    }

    // Quote it when contacting support
    console.error(`Request ID: ${error.requestId ?? '-'}`);

    if (error.code === ErrorCode.INVALID_TRON_ADDRESS) {
      console.error('Check the TRON address format.');
    }
  } else if (error instanceof InvalidRequestError) {
    console.error(`Invalid arguments: ${error.message}`);
  } else if (error instanceof RateLimitError) {
    console.error('Too many requests, please slow down.');
  } else if (error instanceof UnauthorizedError) {
    console.error('Invalid API token or signature.');
  } else if (error instanceof ServerError) {
    console.error(`TronZap server error [${error.statusCode}].`);
  } else if (error instanceof HttpError) {
    console.error(`HTTP error [${error.statusCode}]: ${error.message}`);
  } else if (error instanceof TimeoutError) {
    console.error('Request timed out.');
  } else if (error instanceof SslError) {
    console.error(`SSL error: ${error.message}`);
  } else if (error instanceof NetworkError) {
    console.error(`Network error: ${error.message}`);
  } else if (error instanceof TronZapError) {
    console.error(`Error [${error.code}]: ${error.message}`);
  } else {
    console.error('Unexpected error:', error);
  }
}

API Error Codes

Code Constant Description
1 AUTH_ERROR Authentication error – Invalid API token or signature
2 INVALID_SERVICE_OR_PARAMS Invalid service or parameters
5 WALLET_NOT_FOUND Internal wallet not found. Contact support.
6 INSUFFICIENT_FUNDS Insufficient funds
10 INVALID_TRON_ADDRESS Invalid TRON address, or the address already has an active subscription
11 INVALID_ENERGY_AMOUNT Invalid energy amount
12 INVALID_DURATION Invalid duration
20 TRANSACTION_NOT_FOUND Transaction/subscription not found
21 CANNOT_STOP_SUBSCRIPTION Cannot stop subscription, e.g. it has a transactions limit
24 ADDRESS_NOT_ACTIVATED Address not activated
25 ADDRESS_ALREADY_ACTIVATED Address already activated
30 AML_CHECK_NOT_FOUND AML check not found
35 SERVICE_NOT_AVAILABLE Service not available
50 INVALID_BANDWIDTH_AMOUNT Invalid bandwidth amount
500 INTERNAL_SERVER_ERROR Internal server error – Contact support

Development

# Install dependencies
npm ci

# Run tests
npm test

# Lint code
npm run lint

# The same tests on Bun and Deno, if they are installed
npm run test:bun
npm run test:deno

The tests run against a local HTTP/TLS server and never call the real API. examples/basic-usage.ts is a smoke test against a real environment (npm run example); the instructions are at the top of the file.

Support

For support, please contact us on Telegram: @tronzap_bot

License

This project is licensed under the MIT License - see the LICENSE file for details.

Releases

Used by

Contributors

Languages