Deploy and Interact with Smart Contracts on TRON Using JavaScript

Posted By : Mudit

Jun 26, 2024

TRC-20 is a standard for smart contract development and fungible token development on the TRON blockchain. It is similar to Ethereum's ERC-20 standard but tailored for the TRON network. TRC-20 ensures that all tokens created on TRON can work seamlessly with various decentralized applications (dApps) and other smart contracts within the TRON ecosystem

Setup

Deploying a TRC-20 token on the TRON blockchain involves several steps, from setting up the development environment to writing, compiling, and deploying the smart contract. Here's a comprehensive guide to help you through the process.

Install the following dependencies to set up your project:

  • Hardhat: For project management and to compile the Solidity code, which then provides us with the ABI and bytecode necessary for contract deployment and interaction 
  • TronWeb: For interacting with the TRON blockchain and deploying our contract. It is also used to interact with the contract by creating its instance.
  • OpenZeppelin Contracts: It provides secure and reliable smart contract libraries that follow industry best practices, and it simplifies the development process by offering well-tested, reusable components.
  • dotenv: For managing environment variables securely, such as the private key, which is of utmost importance to be kept securely.

You may also like | How to Transfer SOL and SPL Tokens Using Anchor

TRC-20 Token

This Solidity code defines a TRC-20 token smart contract for the TRON blockchain, following the ERC-20 standard. Named TRC20Token, it inherits from OpenZeppelin's ERC20 contract. The constructor accepts the token's name, symbol, and initial supply as parameters, setting these values and minting the total supply to the deployer's address with 18 decimal places. 18 decimal places are defined in the ERC-20 token standard.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract TRC20Token is ERC20 {
    constructor(
        string memory name,
        string memory symbol,
        uint256 initialSupply
    ) ERC20(name, symbol) {
        _mint(msg.sender, initialSupply * (10 ** uint256(decimals())));
    }
}

Also, Check |  How to Develop Programmable Non-Fungible Tokens on Solana

Deploy

To deploy a TRC-20 token smart contract on the TRON blockchain using TronWeb, we start by writing the smart contract in Solidity. After that, we use Hardhat to compile the contract, which generates the ABI (Application Binary Interface) and bytecode necessary for deployment. We run npx hardhat compile to get these compiled files. In our deployment script, we first set up TronWeb with the necessary full node, solidity node, event server, and private key for the TRON network.

We then define the ABI and bytecode of our contract using the compiled artifacts. When deploying the contract, we pass the parameters for the token's name ('TRC20'), symbol ('TRC'), and initial supply (1,000,000 tokens). These parameters are specified in the parameters array of the deployment configuration. Additionally, we set other deployment options such as feeLimit, callValue, userFreePercentage and originalEnergyLimit 

TronWeb handles the deployment process and, once the contract is successfully deployed, provides the contract address. In our script, we retrieve both the hexadecimal address and the Base58Check address of the deployed contract. Finally, we console log these addresses to display the deployed token's address. This way, we can verify and interact with our deployed TRC-20 token on the TRON blockchain.

require('dotenv').config();
const TronWeb = require('tronweb');
const artifacts = require('../artifacts/contracts/TRC20Token.sol/TRC20Token.json');

const fullNode = 'https://api.nileex.io';
const solidityNode = 'https://api.nileex.io';
const eventServer = 'https://api.nileex.io';
const privateKey = process.env.PRIVATEKEY;

const tronWeb = new TronWeb(fullNode, solidityNode, eventServer, privateKey);

const contractABI = artifacts.abi;
const contractBytecode = artifacts.bytecode;

async function deployContract() {
  const contract = await tronWeb.contract().new({
    abi: contractABI,
    bytecode: contractBytecode,
    feeLimit: 1000000000,
    callValue: 0,
    userFeePercentage: 30,
    originEnergyLimit: 10000000,
    parameters: ['TRC20', 'TRC', 1000000],
  });

  const hexAddress = contract.address;
  const base58Address = tronWeb.address.fromHex(hexAddress);

  console.log('Contract deployed at address:');
  console.log('Hexadecimal: ', hexAddress);
  console.log('Base58Check: ', base58Address);
}

deployContract()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

Also, Explore | Creating a Staking Smart Contract on Solana using Anchor

Interacting with the Contract

The provided code shows how to interact with a TRC-20 token smart contract on the TRON blockchain using TronWeb. It begins by configuring TronWeb with the necessary settings for the Nile testnet, including full node, solidity node, event server, and a private key. The contract's ABI and address are used to create a contract instance. The getTokenDetails function then calls the smart contract methods to fetch the token's decimals, name, symbol, and total supply. These details are printed to the console, demonstrating how to retrieve and display essential information about a TRC-20 token deployed on the TRON network.

When executed, the script logs the following values to the console:

  • Decimals: 18
  • Name: TRC20
  • Symbol: TRC
  • Total Supply: 1000000000000000000000000

This output shows that the token has 18 decimal places, is named "TRC20," has the symbol "TRC," and has a total supply of 1,000,000 tokens (accounting for the 18 decimal places). This script is useful for anyone needing to interact with and understand the properties of their TRC-20 token.

require('dotenv').config();
const TronWeb = require('tronweb');
const artifacts = require('../artifacts/contracts/TRC20Token.sol/TRC20Token.json');

// TronWeb configuration for Nile testnet
const fullNode = 'https://api.nileex.io';
const solidityNode = 'https://api.nileex.io';
const eventServer = 'https://api.nileex.io';
const privateKey = process.env.PRIVATE_KEY;

const tronWeb = new TronWeb(fullNode, solidityNode, eventServer, privateKey);

const contractAddress = 'TQtBkgDaQUKrpt2aiYYaACpDGjigJkUTum';

async function getTokenDetails() {
  try {
    const contract = await tronWeb.contract().at(contractAddress);

    const decimals = await contract.decimals().call();
    const name = await contract.name().call();
    const symbol = await contract.symbol().call();
    const totalSupply = await contract.totalSupply().call();

    console.log('Decimals:', decimals.toString());
    console.log('Name:', name);
    console.log('Symbol:', symbol);
    console.log('Total Supply:', tronWeb.toBigNumber(totalSupply).toString());
  } catch (error) {
    console.error('Error fetching token details:', error);
  }
}

getTokenDetails()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

Also, Discover | How To Create My Scalping Bot Using Node.js

Conclusion

Deploying and interacting with a TRC-20 token on the TRON blockchain is a clear process. You can easily create and manage your token by setting up the right tools and writing a compliant smart contract. Using Hardhat to compile and TronWeb to deploy ensures your token works well within the TRON ecosystem. TronWeb also lets you interact with your deployed contract to retrieve important token details, simplifying management. Whether you are a developer or a business, the TRC-20 standard provides a reliable framework for token creation and management on TRON. Looking to build your project on the Tron Blockchain? Get started by connecting with our experienced blockchain developers.

Leave a

Comment

Name is required

Invalid Name

Comment is required

Recaptcha is required.

blog-detail

November 19, 2024 at 11:41 am

Your comment is awaiting moderation.

By using this site, you allow our use of cookies. For more information on the cookies we use and how to delete or block them, please read our cookie notice.

Chat with Us
Telegram Button
Youtube Button

Contact Us

Oodles | Blockchain Development Company

Name is required

Please enter a valid Name

Please enter a valid Phone Number

Please remove URL from text