> ## Documentation Index
> Fetch the complete documentation index at: https://docs.chainstack.com/llms.txt
> Use this file to discover all available pages before exploring further.

<AgentInstructions>

## Submitting Feedback

If you encounter incorrect, outdated, or confusing documentation on this page, submit feedback:

POST https://docs.chainstack.com/feedback

```json
{
  "path": "/docs/tron-tooling",
  "feedback": "Description of the issue"
}
```

Only submit feedback when you have something specific and actionable to report.

</AgentInstructions>

# TRON tooling

> TRON blockchain development tools guide. Use TronWeb.js, gRPC, web3.py, Hardhat, and Foundry with Chainstack TRON nodes and endpoints.

<Info>
  ### `/jsonrpc`, `/wallet`, `/walletsolidity`, and gRPC support

  Chainstack supports all TRON API endpoints:

  * `/jsonrpc` — Ethereum-compatible JSON-RPC (read-only operations)
  * `/wallet` — TRON HTTP API (full node operations including transactions)
  * `/walletsolidity` — TRON HTTP API (confirmed data from solidity node)
  * **gRPC** — high-performance binary protocol for efficient data access

  Note that the TRON nodes provided are full only (non-archive), which makes some of the methods unsupported.
</Info>

Get started with a [reliable TRON RPC endpoint](https://chainstack.com/build-better-with-tron/) to use the tools below.

For the full API reference, see the official [TRON API Reference](https://developers.tron.network/reference/).

<Warning>
  ### Ethereum tooling limitations

  TRON's `/jsonrpc` endpoint provides limited Ethereum compatibility for **read operations only**. Methods required for transaction submission (`eth_sendRawTransaction`, `eth_getTransactionCount`) are not available.

  This means Ethereum-native tools like **Foundry**, **Hardhat**, and **web3.py** cannot deploy contracts or send transactions to TRON directly. For write operations, use **TronWeb.js** with the `/wallet` endpoint.

  You can still use Foundry or Hardhat for **compilation and testing**, then deploy with TronWeb.js. See the [hybrid workflow](#hybrid-workflow) section.
</Warning>

<Note>
  ### WebSocket event subscription not available

  TRON nodes currently do not support WebSocket connections for event subscriptions. If you need to subscribe to events, please vote and follow the feature request at [TRON event plugin support](https://ideas.chainstack.com/p/implement-tron-event-plugin).
</Note>

## gRPC API

TRON nodes on Chainstack support gRPC for high-performance access. gRPC uses HTTP/2 and Protocol Buffers for efficient binary serialization, making it ideal for high-throughput applications and data indexing.

### Endpoint format

Your TRON gRPC endpoints are available at:

* **Mainnet**: `tron-mainnet.core.chainstack.com:443`
* **Nile Testnet**: `tron-nile.core.chainstack.com:443`

### Authentication

gRPC endpoints use x-token authentication. Pass your token in the request metadata:

* **x-token** — your authentication token from the Chainstack console

<Info>
  Find your gRPC endpoint and x-token in the Chainstack console under your TRON node's **Access and credentials** section.
</Info>

### Proto files

TRON gRPC does not support server reflection, so you need the protocol buffer definitions to make calls. Get them from the official TRON protocol repository:

```shell theme={"system"}
git clone https://github.com/tronprotocol/protocol.git
```

The main service definitions are in:

* `api/api.proto` — Wallet service with methods like `GetNowBlock`, `GetBlockByNum`, `GetAccount`
* `core/Tron.proto` — Core data types (blocks, transactions, accounts)

### Generate client code

To use gRPC with TRON, generate client code from the proto files.

<Tabs>
  <Tab title="Python">
    Install dependencies and generate the Python stubs:

    ```shell theme={"system"}
    pip install grpcio grpcio-tools
    ```

    ```shell theme={"system"}
    # Clone proto files
    git clone https://github.com/tronprotocol/protocol.git
    mkdir -p googleapis/google/api

    # Download Google API dependencies
    curl -sL https://raw.githubusercontent.com/googleapis/googleapis/master/google/api/annotations.proto \
      -o googleapis/google/api/annotations.proto
    curl -sL https://raw.githubusercontent.com/googleapis/googleapis/master/google/api/http.proto \
      -o googleapis/google/api/http.proto

    # Generate Python code
    python -m grpc_tools.protoc \
      -I./protocol \
      -I./googleapis \
      --python_out=./generated \
      --grpc_python_out=./generated \
      $(find ./protocol -name "*.proto")
    ```
  </Tab>

  <Tab title="Node.js">
    Install dependencies:

    ```shell theme={"system"}
    npm install @grpc/grpc-js @grpc/proto-loader
    ```

    Clone the proto files:

    ```shell theme={"system"}
    git clone https://github.com/tronprotocol/protocol.git
    ```
  </Tab>

  <Tab title="Go">
    Install the protoc compiler and Go plugins:

    ```shell theme={"system"}
    go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
    go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
    ```

    Clone and generate:

    ```shell theme={"system"}
    git clone https://github.com/tronprotocol/protocol.git

    protoc --go_out=. --go-grpc_out=. \
      -I./protocol \
      protocol/api/api.proto protocol/core/Tron.proto
    ```
  </Tab>
</Tabs>

### Usage examples

<CodeGroup>
  ```python Python theme={"system"}
  import grpc
  import sys
  sys.path.insert(0, './generated')

  from api import api_pb2, api_pb2_grpc

  ENDPOINT = "tron-mainnet.core.chainstack.com:443"
  X_TOKEN = "YOUR_X_TOKEN"

  def get_now_block():
      # Create secure channel with TLS
      credentials = grpc.ssl_channel_credentials()
      channel = grpc.secure_channel(ENDPOINT, credentials)

      # Create stub
      stub = api_pb2_grpc.WalletStub(channel)

      # Add x-token to metadata
      metadata = [("x-token", X_TOKEN)]

      # Call GetNowBlock
      response = stub.GetNowBlock(
          api_pb2.EmptyMessage(),
          metadata=metadata,
          timeout=15
      )

      print(f"Block number: {response.block_header.raw_data.number}")
      print(f"Transactions: {len(response.transactions)}")

      channel.close()

  get_now_block()
  ```

  ```javascript Node.js theme={"system"}
  const grpc = require('@grpc/grpc-js');
  const protoLoader = require('@grpc/proto-loader');
  const path = require('path');

  const ENDPOINT = 'tron-mainnet.core.chainstack.com:443';
  const X_TOKEN = 'YOUR_X_TOKEN';

  // Load proto files
  const packageDefinition = protoLoader.loadSync(
    path.join(__dirname, 'protocol/api/api.proto'),
    {
      keepCase: true,
      longs: String,
      enums: String,
      defaults: true,
      oneofs: true,
      includeDirs: [
        path.join(__dirname, 'protocol'),
        path.join(__dirname, 'googleapis')
      ]
    }
  );

  const proto = grpc.loadPackageDefinition(packageDefinition);

  // Create credentials with TLS
  const credentials = grpc.credentials.createSsl();

  // Create client
  const client = new proto.protocol.Wallet(ENDPOINT, credentials);

  // Add x-token to metadata
  const metadata = new grpc.Metadata();
  metadata.add('x-token', X_TOKEN);

  // Call GetNowBlock
  client.GetNowBlock({}, metadata, (error, response) => {
    if (error) {
      console.error('Error:', error);
      return;
    }
    console.log('Block number:', response.block_header.raw_data.number);
    console.log('Transactions:', response.transactions.length);
  });
  ```

  ```go Go theme={"system"}
  package main

  import (
      "context"
      "fmt"
      "log"

      "google.golang.org/grpc"
      "google.golang.org/grpc/credentials"
      "google.golang.org/grpc/metadata"

      // Import your generated proto packages
      pb "your-module/api"
  )

  const (
      endpoint = "tron-mainnet.core.chainstack.com:443"
      xToken   = "YOUR_X_TOKEN"
  )

  func main() {
      // Create TLS credentials
      creds := credentials.NewTLS(nil)

      // Connect to gRPC endpoint
      conn, err := grpc.Dial(endpoint, grpc.WithTransportCredentials(creds))
      if err != nil {
          log.Fatalf("Failed to connect: %v", err)
      }
      defer conn.Close()

      // Create client
      client := pb.NewWalletClient(conn)

      // Add x-token to context
      ctx := metadata.AppendToOutgoingContext(
          context.Background(),
          "x-token", xToken,
      )

      // Call GetNowBlock
      response, err := client.GetNowBlock(ctx, &pb.EmptyMessage{})
      if err != nil {
          log.Fatalf("GetNowBlock failed: %v", err)
      }

      fmt.Printf("Block number: %d\n", response.BlockHeader.RawData.Number)
      fmt.Printf("Transactions: %d\n", len(response.Transactions))
  }
  ```
</CodeGroup>

where YOUR\_X\_TOKEN is your authentication token from the Chainstack console.

For the full list of available gRPC methods, see the official [TRON gRPC documentation](https://developers.tron.network/docs/trons-grpc-calls).

## TronWeb.js

[TronWeb](https://tronweb.network/) is the official JavaScript library for TRON. It supports all TRON operations including contract deployment and transactions.

### Get balance

```js theme={"system"}
const { TronWeb } = require('tronweb');

const tronWeb = new TronWeb({
    fullHost: 'YOUR_CHAINSTACK_ENDPOINT'
});

const address = 'TWiEv2wfqQ8FkbAJ6bXt1uA2Uav9ZWvXip';

async function getBalance() {
    try {
        const balanceInSun = await tronWeb.trx.getBalance(address);
        const balanceInTRX = tronWeb.fromSun(balanceInSun);

        console.log(`Address: ${address}`);
        console.log(`Balance in SUN: ${balanceInSun}`);
        console.log(`Balance in TRX: ${balanceInTRX}`);
    } catch (error) {
        console.error('Error getting balance:', error);
    }
}

getBalance();
```

where YOUR\_CHAINSTACK\_ENDPOINT is your TRON node **base** endpoint without the `/jsonrpc`, `/wallet`, or `/walletsolidity` postfixes.

### Deploy a contract

```js theme={"system"}
const { TronWeb } = require('tronweb');

const tronWeb = new TronWeb({
    fullHost: 'YOUR_CHAINSTACK_ENDPOINT',
    privateKey: 'YOUR_PRIVATE_KEY'
});

// Contract ABI and bytecode
const abi = [/* your contract ABI */];
const bytecode = 'your_contract_bytecode';

async function deployContract() {
    try {
        console.log('Deploying contract...');
        console.log('From address:', tronWeb.defaultAddress.base58);

        const transaction = await tronWeb.transactionBuilder.createSmartContract({
            abi: abi,
            bytecode: bytecode,
            feeLimit: 100000000,
            callValue: 0,
            userFeePercentage: 100,
            originEnergyLimit: 10000000
        }, tronWeb.defaultAddress.base58);

        const signedTx = await tronWeb.trx.sign(transaction);
        const result = await tronWeb.trx.sendRawTransaction(signedTx);

        if (result.result) {
            console.log('Contract deployed!');
            console.log('Transaction ID:', result.txid);
            console.log('Contract address:', tronWeb.address.fromHex(result.transaction.contract_address));
        }
    } catch (error) {
        console.error('Deployment error:', error.message || error);
    }
}

deployContract();
```

where

* YOUR\_CHAINSTACK\_ENDPOINT — your TRON node **base** endpoint without the `/jsonrpc`, `/wallet`, or `/walletsolidity` postfixes
* YOUR\_PRIVATE\_KEY — the private key of the account that you use to deploy the contract

See also [node access details](/docs/manage-your-node#view-node-access-and-credentials).

## web3.py

<Note>
  web3.py can only perform **read operations** on TRON through the `/jsonrpc` endpoint. For contract deployment and transactions, use [TronWeb.js](#tronwebjs).
</Note>

Build DApps using [web3.py](https://github.com/ethereum/web3.py) and TRON nodes deployed with Chainstack.

1. Install [web3.py](https://web3py.readthedocs.io/).

2. Connect over HTTP.

### HTTP

Use the `HTTPProvider` to connect to your node endpoint and get the latest block number.

<CodeGroup>
  ```python Key protected theme={"system"}
  from web3 import Web3

  web3 = Web3(Web3.HTTPProvider('YOUR_CHAINSTACK_ENDPOINT'))
  print(web3.eth.block_number)
  ```

  ```python Password protected theme={"system"}
  from web3 import Web3

  web3 = Web3(Web3.HTTPProvider('https://%s:%s@%s'% ("USERNAME", "PASSWORD", "HOSTNAME")))
  print(web3.eth.block_number)
  ```
</CodeGroup>

where YOUR\_CHAINSTACK\_ENDPOINT is your node HTTPS endpoint with the `/jsonrpc` postfix, protected either with the key or password.

See also [node access details](/docs/manage-your-node#view-node-access-and-credentials).

## Hardhat

<Note>
  Hardhat can only perform **read operations** on TRON through the `/jsonrpc` endpoint. For contract deployment, use the [hybrid workflow](#hybrid-workflow) or [TronWeb.js](#tronwebjs) directly.
</Note>

Configure [Hardhat](https://hardhat.org/) to compile contracts and perform read operations through your TRON nodes.

1. Install [Hardhat](https://hardhat.org/) and create a project.

2. Create a new environment in `hardhat.config.js`:

   ```javascript theme={"system"}
   require("@nomiclabs/hardhat-waffle");
   ...
   module.exports = {
     solidity: "0.8.19",
     networks: {
       tron: {
           url: "YOUR_CHAINSTACK_ENDPOINT",
       },
     }
   };
   ```

   where YOUR\_CHAINSTACK\_ENDPOINT is your node HTTPS endpoint with the `/jsonrpc` postfix, protected either with the key or password. See [node access details](/docs/manage-your-node#view-node-access-and-credentials).

3. Compile your contracts with `npx hardhat compile`, then deploy using TronWeb.js.

## Foundry

<Note>
  Foundry can only perform **read operations** on TRON through the `/jsonrpc` endpoint. For contract deployment, use the [hybrid workflow](#hybrid-workflow) below.
</Note>

1. Install [Foundry](https://getfoundry.sh/).

2. Use `--rpc-url` to run read operations through your Chainstack node.

### Cast

Use `cast` to query the network.

To get the latest block number:

```shell theme={"system"}
cast block-number --rpc-url YOUR_CHAINSTACK_ENDPOINT
```

To get an account balance:

```shell theme={"system"}
cast balance 0xYOUR_HEX_ADDRESS --rpc-url YOUR_CHAINSTACK_ENDPOINT
```

where YOUR\_CHAINSTACK\_ENDPOINT is your node HTTPS endpoint with the `/jsonrpc` postfix, protected either with the key or password.

## Hybrid workflow

Use Foundry for fast compilation and testing, then deploy to TRON with TronWeb.js.

### Set up the project

1. Initialize a Foundry project:

   ```shell theme={"system"}
   forge init my-tron-project
   cd my-tron-project
   ```

2. Write your contract in `src/`:

   ```solidity theme={"system"}
   // src/MyContract.sol
   // SPDX-License-Identifier: MIT
   pragma solidity ^0.8.19;

   contract MyContract {
       string public message;

       constructor(string memory _message) {
           message = _message;
       }

       function setMessage(string memory _message) public {
           message = _message;
       }
   }
   ```

3. Compile with Foundry:

   ```shell theme={"system"}
   forge build
   ```

   The compiled artifacts are in `out/MyContract.sol/MyContract.json`.

### Deploy with TronWeb.js

1. Install TronWeb:

   ```shell theme={"system"}
   npm init -y
   npm install tronweb
   ```

2. Create a deployment script `deploy.js`:

   ```js theme={"system"}
   const { TronWeb } = require('tronweb');
   const fs = require('fs');

   const tronWeb = new TronWeb({
       fullHost: 'YOUR_CHAINSTACK_ENDPOINT',
       privateKey: 'YOUR_PRIVATE_KEY'
   });

   // Load Foundry artifacts
   const artifact = JSON.parse(
       fs.readFileSync('./out/MyContract.sol/MyContract.json', 'utf8')
   );

   async function deploy() {
       try {
           console.log('Deploying from:', tronWeb.defaultAddress.base58);

           const transaction = await tronWeb.transactionBuilder.createSmartContract({
               abi: artifact.abi,
               bytecode: artifact.bytecode.object,
               feeLimit: 150000000,
               callValue: 0,
               userFeePercentage: 100,
               originEnergyLimit: 10000000,
               parameters: ['Hello TRON!']  // Constructor arguments
           }, tronWeb.defaultAddress.base58);

           const signedTx = await tronWeb.trx.sign(transaction);
           const result = await tronWeb.trx.sendRawTransaction(signedTx);

           if (result.result) {
               console.log('Contract deployed!');
               console.log('Transaction ID:', result.txid);
               console.log('Contract address:', tronWeb.address.fromHex(result.transaction.contract_address));
           }
       } catch (error) {
           console.error('Error:', error.message || error);
       }
   }

   deploy();
   ```

3. Run the deployment:

   ```shell theme={"system"}
   node deploy.js
   ```

where

* YOUR\_CHAINSTACK\_ENDPOINT — your TRON node **base** endpoint without the `/jsonrpc`, `/wallet`, or `/walletsolidity` postfixes
* YOUR\_PRIVATE\_KEY — the private key of the account that you use to deploy the contract

See also [node access details](/docs/manage-your-node#view-node-access-and-credentials).
