# TRON API and RPC: HTTP, JSON-RPC and Solidity Endpoints

## TRON RPC plans and rate limits

- **Free plan:** 20 responses per second, up to 100,000 responses a day.
- **Plans:** $49/mo, $299/mo, $999/mo with 25M, 150M, and 500M included responses. Overages billed at $5/$3/$2 per million responses respectively.
- **Paid rate limits:** 100 to 5,000 responses per second (bursts from 500 to 10,000), no daily limit.
- **Billing:** 1 response = 1 API credit on every shared plan, over HTTPS or WebSocket (WSS) where TRON supports it.

Details: [Pricing](https://www.dwellir.com/docs/getting-started/pricing) · [Rate limits](https://www.dwellir.com/docs/getting-started/rate-limits) · [Authentication](https://www.dwellir.com/docs/getting-started/authentication) · [Archive nodes](https://www.dwellir.com/docs/getting-started/archive-nodes)

## Why Build on TRON?

TRON is a high-performance blockchain platform designed for mass adoption with 2000+ TPS, free daily bandwidth, and a thriving ecosystem of DeFi, gaming, and entertainment dApps.

### **Unmatched Performance**

- **2000+ TPS** - Process thousands of transactions per second
- **3-second blocks** - Near-instant transaction finality
- **Free bandwidth** - 600 bytes a day per account, enough for one USDT transfer
- **Energy for contract calls** - A USDT transfer uses 64,285 energy, or 130,285 to a wallet with no USDT ([measured costs](https://www.dwellir.com/blog/tron-energy-usdt-transfers))

### **Massive Adoption**

- **200M+ accounts** - One of the largest blockchain user bases
- **8B+ transactions** - Proven scalability in production
- **$15B+ TVL** - Thriving DeFi ecosystem
- **USDT dominance** - 50%+ of all USDT circulates on TRON

### **Developer Friendly**

- **Solidity support** - Deploy Ethereum smart contracts with minimal changes
- **TVM compatibility** - TRON Virtual Machine based on EVM
- **Energy & Bandwidth** - Unique resource model for gas optimization
- **Multi-signature** - Native support for complex wallet operations

## Quick Start with TRON

Connect to TRON's high-performance network with Dwellir's optimized endpoints:

- **Wallet & HTTP APIs** (e.g. `/wallet/getnowblock`) use `https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/<method>`.
- **JSON-RPC methods** (all `eth_*`, `net_*`, `web3_*`) should target `https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/jsonrpc`.
  All JSON-RPC requests must be sent as POST calls with a JSON body. Replace `YOUR_API_KEY` with your key before using the examples.

### Installation & Setup

TronWeb
JavaScript (Fetch)
Python

```javascript
const TronWeb = require('tronweb');

// Initialize TronWeb with Dwellir endpoint
const tronWeb = new TronWeb({
  fullHost: 'https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY',
  headers: { "TRON-PRO-API-KEY": 'YOUR_API_KEY' },
  privateKey: 'your-private-key'
});

// Get account information
const account = await tronWeb.trx.getAccount('TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN');
console.log('Balance:', tronWeb.fromSun(account.balance), 'TRX');

// Send TRX transaction
const tx = await tronWeb.trx.sendTransaction(
  'TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN',
  1000000, // Amount in SUN (1 TRX = 1,000,000 SUN)
  'your-private-key'
);
console.log('Transaction:', tx.txid);
```

```javascript
// Direct HTTP API calls
const TRON_HTTP_API = 'https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY';
const TRON_JSON_RPC = 'https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/jsonrpc';

// Get account balance
async function getBalance(address) {
  const response = await fetch(`${TRON_HTTP_API}/wallet/getaccount`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      address: address,
      visible: true
    })
  });

  const data = await response.json();
  return data.balance / 1000000; // Convert SUN to TRX
}

// Get latest block
async function getLatestBlock() {
  const response = await fetch(`${TRON_HTTP_API}/wallet/getnowblock`);
  return response.json();
}

// Call a JSON-RPC method
async function getBlockNumber() {
  const response = await fetch(TRON_JSON_RPC, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      jsonrpc: '2.0',
      method: 'eth_blockNumber',
      params: [],
      id: 1,
    }),
  });

  const data = await response.json();
  return parseInt(data.result, 16);
}
```

```python
from tronpy import Tron
from tronpy.keys import PrivateKey

# Connect to TRON mainnet via Dwellir
client = Tron(network='mainnet')
client.provider.endpoint_uri = 'https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY'

# Get account information
account = client.get_account('TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN')
print(f"Balance: {account.balance / 1_000_000} TRX")

# Send TRX transaction
priv_key = PrivateKey(bytes.fromhex("your_private_key_hex"))
txn = (
    client.trx.transfer("from_address", "to_address", 1_000_000)
    .memo("Transaction memo")
    .build()
    .sign(priv_key)
)
result = txn.broadcast()
print(f"Transaction ID: {result['txid']}")
```

## Network Information

### Mainnet Configuration

| Parameter      | Value                                     | Details |
| -------------- | ----------------------------------------- | ------- |
| Network Name   | TRON Mainnet                              |         |
| Chain ID       | `728126428` (0x2B6653DC)                  |         |
| Currency       | TRX                                       |         |
| Decimal        | 6 (1 TRX = 1,000,000 SUN)                 |         |
| Block Explorer | [TronScan Explorer](https://tronscan.org) |         |
| Official Site  | [TRON Website](https://tron.network)      |         |

### Address Format

TRON uses Base58 encoded addresses starting with 'T':

| Parameter | Value                                | Details         |
| --------- | ------------------------------------ | --------------- |
| Example   | `TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN` |                 |
| Length    | 34 characters                        |                 |
| Checksum  | Built-in                             | Error detection |

## Core RPC Methods

### Account & Wallet Methods

#### wallet/getaccount

Get account information including balance, resources, and tokens:

```javascript
const account = await fetch(`${TRON_API}/wallet/getaccount`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    address: 'TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN',
    visible: true
  })
});
```

#### wallet/getaccountresource

Get bandwidth and energy resources:

```javascript
const resources = await fetch(`${TRON_API}/wallet/getaccountresource`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    address: 'TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN',
    visible: true
  })
});
```

### Transaction Methods

#### wallet/createtransaction

Create a TRX transfer transaction:

```javascript
const transaction = await fetch(`${TRON_API}/wallet/createtransaction`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    to_address: 'TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN',
    owner_address: 'TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh',
    amount: 1000000, // 1 TRX in SUN
    visible: true
  })
});
```

#### wallet/broadcasttransaction

Broadcast a signed transaction:

```javascript
const broadcast = await fetch(`${TRON_API}/wallet/broadcasttransaction`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(signedTransaction)
});
```

### Block Methods

#### wallet/getnowblock

Get the latest block:

```javascript
const latestBlock = await fetch(`${TRON_API}/wallet/getnowblock`);
const block = await latestBlock.json();
console.log('Block number:', block.block_header.raw_data.number);
```

#### wallet/getblock

Get block by hash or number:

```javascript
const block = await fetch(`${TRON_API}/wallet/getblock`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    id_or_num: "0000000002FAB1B8", // Block hash or number
    detail: true
  })
});
```

### Smart Contract Methods

#### wallet/triggersmartcontract

Call a smart contract function:

```javascript
const contractCall = await fetch(`${TRON_API}/wallet/triggersmartcontract`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    contract_address: 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t', // USDT contract
    function_selector: 'balanceOf(address)',
    parameter: '0000000000000000000000004142b5e01c8c59a25d78acdbec2bfc7e89e5e863',
    owner_address: 'TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh',
    visible: true
  })
});
```

## TRC20 Token Operations

### Working with USDT and Other TRC20 Tokens

```javascript
// TRC20 USDT Contract
const USDT_CONTRACT = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t';

// Get USDT balance
async function getUSDTBalance(address) {
  const { constant_result } = await tronWeb.transactionBuilder.triggerConstantContract(
    USDT_CONTRACT,
    'balanceOf(address)',
    {},
    [{type: 'address', value: address}]
  );

  return tronWeb.toDecimal('0x' + constant_result[0]) / 1e6;
}

// Transfer USDT
async function transferUSDT(to, amount) {
  const contract = await tronWeb.contract().at(USDT_CONTRACT);
  const tx = await contract.transfer(to, amount * 1e6).send();
  return tx;
}
```

### Popular TRC20 Tokens

| Token | Contract Address                   | Decimals |
| ----- | ---------------------------------- | -------- |
| USDT  | TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t | 6        |
| USDC  | TEkxiTehnzSmSe2XqrBj4w32RUN966rdz8 | 6        |
| TUSD  | TUpMhErZL2fhh4sVNULAbNKLokS4GjC1F4 | 18       |
| WTRX  | TNUC9Qb1rRpS5CbWLmNMxXBjyFoydXjWFR | 6        |
| JST   | TCFLL5dx5ZJdKnWuesXxi1VPwjLVmWZZy9 | 18       |

## Energy & Bandwidth System

### Understanding TRON Resources

TRON uses a unique resource model instead of gas fees:

1. **Bandwidth Points** - For normal transactions
2. **Energy** - For smart contract execution
3. **TRX Fee** - Fallback when resources are exhausted

```javascript
// Freeze TRX for energy
async function freezeForEnergy(amount) {
  const tx = await tronWeb.transactionBuilder.freezeBalance(
    amount * 1e6, // Amount in SUN
    3, // Duration in days
    'ENERGY',
    ownerAddress
  );
  const signed = await tronWeb.trx.sign(tx);
  return await tronWeb.trx.broadcast(signed);
}

// Get account resources
async function getResources(address) {
  const resources = await tronWeb.trx.getAccountResources(address);
  return {
    bandwidth: resources.freeNetLimit + (resources.NetLimit || 0),
    energy: resources.EnergyLimit || 0,
    freeTransactions: resources.freeNetUsed < resources.freeNetLimit
  };
}
```

### Resource Optimization Tips

1. **Free Bandwidth** - Every activated account gets 600 free bandwidth a day (`getFreeNetLimit`), enough for the 345 bytes of one USDT transfer. Energy has no free allowance
2. **Stake TRX** - Freeze TRX to get energy for smart contracts
3. **Energy Rental** - Rent energy from platforms like JustLend
4. **Multi-signature** - Combine resources from multiple accounts

## DeFi Integration

### Connecting to TRON DeFi Protocols

```javascript
// JustSwap V2 Router
const JUSTSWAP_ROUTER = 'TKzxdSv2FZKQrEqkKVgp5DcwEXBEKMg2Ax';

// Swap TRX for USDT
async function swapTRXforUSDT(amountTRX) {
  const contract = await tronWeb.contract().at(JUSTSWAP_ROUTER);

  const path = [
    'TNUC9Qb1rRpS5CbWLmNMxXBjyFoydXjWFR', // WTRX
    'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'  // USDT
  ];

  const tx = await contract.swapExactETHForTokens(
    0, // Min amount out
    path,
    userAddress,
    Date.now() + 60000 // Deadline
  ).send({
    callValue: amountTRX * 1e6
  });

  return tx;
}
```

### Popular TRON DeFi Protocols

| Protocol | Category | TVL    | Contract                           |
| -------- | -------- | ------ | ---------------------------------- |
| JustLend | Lending  | $5B+   | Multiple contracts                 |
| SUN.io   | DEX      | $2B+   | TKkeiboTkxXKJpbmVFbv4a8ov5rAfRDMf9 |
| JustSwap | AMM DEX  | $500M+ | TKzxdSv2FZKQrEqkKVgp5DcwEXBEKMg2Ax |

## Transaction Signing

### Signing Transactions with Private Key

```javascript
// Sign transaction locally
async function signTransaction(transaction, privateKey) {
  const tronWeb = new TronWeb({
    fullHost: 'https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY',
    privateKey: privateKey
  });

  const signedTx = await tronWeb.trx.sign(transaction);
  return signedTx;
}

// Multi-signature transaction
async function multiSigTransaction(transaction, privateKeys) {
  let signedTx = transaction;

  for (const key of privateKeys) {
    const tronWeb = new TronWeb({
      fullHost: 'https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY',
      privateKey: key
    });
    signedTx = await tronWeb.trx.multiSign(signedTx);
  }

  return signedTx;
}
```

## Best Practices

### Error Handling

```javascript
class TronAPIError extends Error {
  constructor(message, code) {
    super(message);
    this.code = code;
  }
}

async function safeAPICall(url, options) {
  try {
    const response = await fetch(url, options);
    const data = await response.json();

    if (data.Error) {
      throw new TronAPIError(data.Error, data.code);
    }

    return data;
  } catch (error) {
    if (error.code === 'BANDWIDTH_ERROR') {
      console.error('Insufficient bandwidth. Consider freezing TRX.');
    } else if (error.code === 'CONTRACT_VALIDATE_ERROR') {
      console.error('Smart contract validation failed.');
    }
    throw error;
  }
}
```

### Rate Limiting

```javascript
class RateLimiter {
  constructor(maxRequests = 10, interval = 1000) {
    this.maxRequests = maxRequests;
    this.interval = interval;
    this.requests = [];
  }

  async throttle() {
    const now = Date.now();
    this.requests = this.requests.filter(time => now - time < this.interval);

    if (this.requests.length >= this.maxRequests) {
      const waitTime = this.interval - (now - this.requests[0]);
      await new Promise(resolve => setTimeout(resolve, waitTime));
      return this.throttle();
    }

    this.requests.push(now);
  }
}

const limiter = new RateLimiter(100, 1000); // 100 requests per second

async function apiCall(endpoint, options) {
  await limiter.throttle();
  return fetch(endpoint, options);
}
```

## Performance Optimization

### Batch Operations

```javascript
// Batch transfer to multiple addresses
async function batchTransfer(transfers) {
  const transactions = [];

  for (const { to, amount } of transfers) {
    const tx = await tronWeb.transactionBuilder.sendTrx(
      to,
      amount * 1e6,
      fromAddress
    );
    transactions.push(tx);
  }

  // Sign all transactions
  const signedTxs = await Promise.all(
    transactions.map(tx => tronWeb.trx.sign(tx))
  );

  // Broadcast all transactions
  const results = await Promise.all(
    signedTxs.map(tx => tronWeb.trx.broadcast(tx))
  );

  return results;
}
```

### Caching Strategies

```javascript
class TronCache {
  constructor(ttl = 60000) { // 1 minute default TTL
    this.cache = new Map();
    this.ttl = ttl;
  }

  set(key, value) {
    this.cache.set(key, {
      value,
      expiry: Date.now() + this.ttl
    });
  }

  get(key) {
    const item = this.cache.get(key);
    if (!item) return null;

    if (Date.now() > item.expiry) {
      this.cache.delete(key);
      return null;
    }

    return item.value;
  }
}

const cache = new TronCache();

async function getCachedBalance(address) {
  const cached = cache.get(`balance:${address}`);
  if (cached) return cached;

  const balance = await getBalance(address);
  cache.set(`balance:${address}`, balance);
  return balance;
}
```

## Security Best Practices

### Private Key Management

```javascript
// Never expose private keys in code
const privateKey = process.env.TRON_PRIVATE_KEY;

// Use hardware wallets for production
import TronStation from 'tronstation';

async function signWithHardware(transaction) {
  const tronStation = new TronStation();
  const signed = await tronStation.signTransaction(transaction);
  return signed;
}

// Validate addresses
function isValidTronAddress(address) {
  try {
    return TronWeb.isAddress(address);
  } catch {
    return false;
  }
}
```

## Common Use Cases

### NFT Minting (TRC721)

```javascript
async function mintNFT(contractAddress, recipient, tokenURI) {
  const contract = await tronWeb.contract().at(contractAddress);

  const tx = await contract.mint(
    recipient,
    tokenURI
  ).send({
    feeLimit: 100_000_000, // 100 TRX max fee
    shouldPollResponse: true
  });

  return tx;
}
```

### Stablecoin Payments

```javascript
async function acceptUSDTPayment(amount, memo) {
  // Generate unique payment address
  const paymentAddress = await generatePaymentAddress();

  // Monitor for incoming USDT
  const interval = setInterval(async () => {
    const balance = await getUSDTBalance(paymentAddress);

    if (balance >= amount) {
      clearInterval(interval);
      await processPayment(paymentAddress, amount, memo);
    }
  }, 3000); // Check every 3 seconds

  return paymentAddress;
}
```

### DAO Voting

```javascript
async function castVote(proposalId, support, reason) {
  const daoContract = await tronWeb.contract().at(DAO_CONTRACT);

  const tx = await daoContract.castVoteWithReason(
    proposalId,
    support,
    reason
  ).send({
    feeLimit: 50_000_000
  });

  return tx;
}
```

## Migration from Ethereum

### Key Differences

| Feature               | Ethereum     | TRON                                                     |
| --------------------- | ------------ | -------------------------------------------------------- |
| Address Format        | 0x... (hex)  | T... (base58)                                            |
| Gas Model             | ETH for gas  | Bandwidth + Energy                                       |
| Block Time            | \~12 seconds | 3 seconds                                                |
| Free Transactions     | No           | Bandwidth only (600 per day); contract calls need energy |
| Native Token Decimals | 18           | 6                                                        |

### Contract Migration

```solidity
// Ethereum contract
contract EthereumToken {
    mapping(address => uint256) balances;

    function transfer(address to, uint256 amount) public {
        require(balances[msg.sender] >= amount);
        balances[msg.sender] -= amount;
        balances[to] += amount;
    }
}

// TRON contract (minimal changes)
contract TronToken {
    mapping(address => uint256) balances;

    function transfer(address to, uint256 amount) public {
        require(balances[msg.sender] >= amount);
        balances[msg.sender] = balances[msg.sender].sub(amount);
        balances[to] = balances[to].add(amount);
    }
}
```

## Support & Resources

### Official Resources

- **Documentation**: [TRON developer docs](https://developers.tron.network)
- **GitHub**: [TRON protocol GitHub](https://github.com/tronprotocol)
- **Discord**: [TRON Discord](https://discord.gg/tron)
- **Twitter**: [@trondao](https://twitter.com/trondao)
- **TronScan**: [TronScan](https://tronscan.org)

### Development Tools

- **TronWeb**: Official JavaScript library
- **TronBox**: Development framework
- **TronGrid**: API service
- **TronStation**: Wallet SDK

### Dwellir Support

- **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com)
- **Status Page**: [status.dwellir.com](https://status.dwellir.com)
- **Support**: <support@dwellir.com>
- **Documentation**: [Dwellir documentation](https://www.dwellir.com/docs)

### Related Reading

- [Best Tron RPC Providers 2026](https://www.dwellir.com/blog/best-tron-rpc-providers)

## Start Building on TRON

Ready to leverage TRON's high performance and massive user base? Get started with Dwellir's optimized infrastructure:

Launch Your TRON dApp Today
Access TRON's 2000+ TPS network with enterprise-grade RPC endpoints

Get Your Free API Key

***

*Need help? Check our [API reference](https://www.dwellir.com/docs/tron/wallet-getaccount) or [contact support](mailto:support@dwellir.com).*
