Docs
Docs
Home
Getting Started
Agent Tooling
CLI
Supported Chains
Acala
Aptos
Arbitrum
Arc
Asset Hub
Astar
Avalanche
Base
Berachain
Bifrost
Binance Smart Chain
Bittensor
Blast
Boba Network
Bridge Hub
Celo
Centrifuge
Chiliz
Cronos
Enjin
Ethereum
Etherlink
Flow EVM Gateway
Gnosis
Hydration
Hyperliquid
Immutable
Ink
IoTeX
Kusama
Linea
LISK
Manta Atlantic
Manta Pacific
Mantle
MegaETH
Monad
Movement
Neuroweb
opBNB
Optimism
Plasma
Polkadot
Polygon
Pulsechain
Robinhood
Ronin
Scroll
Sonic
Starknet
Taiko
Tempo
Sui
TRON
Unichain
Viction
World Chain
XDC Network
XX Network
Zetachain
zkSync Era
Zora
Supported ChainsTRONTRON HTTP API

wallet/triggersmartcontract - Execute TRON Smar...

Execute TRON smart contract functions, read contract state, and interact with TRC20 tokens via Dwellir's optimized smart contract RPC endpoints.

TRON RPC endpoint: endpoint URLs, plans and pricing.

Lightning-Fast Smart Contract Calls

Dwellir's TRON endpoints execute smart contract calls in under 30ms with comprehensive error handling. Build powerful DeFi and Web3 applications with our optimized contract interaction API.

Start building with smart contracts

Executes smart contract functions on the TRON network. Use this method to call contract functions, read contract state, and interact with TRC20/TRC721 tokens.

When to Use This Method

wallet/triggersmartcontract is essential for:

  • TRC20 Token Operations - Transfer, approve, check balances
  • DeFi Protocol Interactions - Swap, stake, lend, borrow
  • NFT Operations - Mint, transfer, query TRC721 tokens
  • Contract State Queries - Read public variables and view functions
  • Smart Contract Execution - Call payable and non-payable functions
JSON-RPC request
{
  "contract_address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
  "function_selector": "balanceOf(address)",
  "parameter": "0000000000000000000000004142b5e01c8c59a25d78acdbec2bfc7e89e5e863",
  "owner_address": "TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh",
  "visible": true
}

Implementation Examples

Response Examples

Successful View Function Call (balanceOf)

JSON
{
  "result": {
    "result": true
  },
  "energy_used": 345,
  "constant_result": [
    "0000000000000000000000000000000000000000000000000000000005f5e100"
  ],
  "transaction": {
    "ret": [{}],
    "visible": true,
    "txID": "70c8e5b0b4e13a7e5a1b0e8d7c6b5a4a39291807f6e5d4c3b2a19080f0e0d0c0b0",
    "raw_data": {
      "contract": [
        {
          "parameter": {
            "value": {
              "data": "70a082310000000000000000000000004142b5e01c8c59a25d78acdbec2bfc7e89e5e863",
              "owner_address": "TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh",
              "contract_address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
            },
            "type_url": "type.googleapis.com/protocol.TriggerSmartContract"
          },
          "type": "TriggerSmartContract"
        }
      ],
      "ref_block_bytes": "4a7b",
      "ref_block_hash": "e15e44aa73bd9e15",
      "expiration": 1734567890000,
      "timestamp": 1734567830000
    }
  }
}

Failed Contract Call

JSON
{
  "result": {
    "result": false,
    "code": "REVERT",
    "message": "REVERT opcode executed"
  },
  "energy_used": 250
}

State-Changing Function Call (Transfer)

JSON
{
  "result": {
    "result": true
  },
  "energy_used": 13326,
  "energy_penalty": 0,
  "transaction": {
    "visible": true,
    "txID": "a1b2c3d4e5f6789012345678901234567890123456789012345678901234567890",
    "raw_data": {
      "contract": [
        {
          "parameter": {
            "value": {
              "data": "a9059cbb0000000000000000000000004142b5e01c8c59a25d78acdbec2bfc7e89e5e86300000000000000000000000000000000000000000000000000000000000f4240",
              "owner_address": "TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh",
              "contract_address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
            },
            "type_url": "type.googleapis.com/protocol.TriggerSmartContract"
          },
          "type": "TriggerSmartContract"
        }
      ],
      "ref_block_bytes": "4a7b",
      "ref_block_hash": "e15e44aa73bd9e15",
      "expiration": 1734567890000,
      "timestamp": 1734567830000
    }
  }
}

Common Use Cases

1. Portfolio Tracker

JavaScript
class TronPortfolioTracker {
  constructor(apiKey) {
    this.manager = new TronContractManager(apiKey);
    this.supportedTokens = {
      'USDT': 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
      'USDC': 'TEkxiTehnzSmSe2XqrBj4w32RUN966rdz8',
      'JST': 'TCFLL5dx5ZJdKnWuesXxi1VPwjLVmWZZy9',
      'WTRX': 'TNUC9Qb1rRpS5CbWLmNMxXBjyFoydXjWFR',
      'TUSD': 'TUpMhErZL2fhh4sVNULAbNKLokS4GjC1F4'
    };
  }
  
  async getPortfolio(walletAddress, includeMetadata = true) {
    const portfolio = {
      address: walletAddress,
      tokens: {},
      totalValueUSD: 0,
      lastUpdated: new Date().toISOString()
    };
    
    for (const [symbol, contractAddress] of Object.entries(this.supportedTokens)) {
      try {
        const token = this.manager.getToken(contractAddress);
        const balanceInfo = await token.getFormattedBalance(walletAddress);
        
        portfolio.tokens[symbol] = {
          ...balanceInfo,
          contractAddress,
          valueUSD: await this.getTokenValueUSD(symbol, balanceInfo.formatted)
        };
        
        if (includeMetadata) {
          const [name, totalSupply] = await Promise.all([
            token.getName(),
            token.getTotalSupply()
          ]);
          
          portfolio.tokens[symbol].name = name;
          portfolio.tokens[symbol].totalSupply = totalSupply;
        }
        
        portfolio.totalValueUSD += portfolio.tokens[symbol].valueUSD;
        
      } catch (error) {
        portfolio.tokens[symbol] = {
          error: error.message,
          contractAddress
        };
      }
    }
    
    return portfolio;
  }
  
  async getTokenValueUSD(symbol, amount) {
    // Simplified - would integrate with price API
    const prices = {
      'USDT': 1.00,
      'USDC': 1.00,
      'TUSD': 1.00,
      'JST': 0.025,
      'WTRX': 0.065
    };
    
    return (prices[symbol] || 0) * amount;
  }
}

2. DeFi Yield Farming Interface

JavaScript
class TronYieldFarming {
  constructor(apiKey, farmContractAddress) {
    this.contract = new TronSmartContract(apiKey, farmContractAddress);
    this.tokenManager = new TronContractManager(apiKey);
  }
  
  async getFarmInfo() {
    try {
      const [poolLength, rewardPerBlock, startBlock] = await Promise.all([
        this.contract.call('poolLength()'),
        this.contract.call('rewardPerBlock()'),
        this.contract.call('startBlock()')
      ]);
      
      return {
        totalPools: this.contract.decodeResult(poolLength.constant_result[0], 'uint256'),
        rewardPerBlock: this.contract.decodeResult(rewardPerBlock.constant_result[0], 'uint256'),
        startBlock: this.contract.decodeResult(startBlock.constant_result[0], 'uint256')
      };
    } catch (error) {
      console.error('Error getting farm info:', error);
      throw error;
    }
  }
  
  async getPoolInfo(poolId) {
    try {
      const encodedPoolId = this.contract.encodeUint256(poolId);
      const result = await this.contract.call('poolInfo(uint256)', encodedPoolId);
      
      if (result.result?.result && result.constant_result?.[0]) {
        const poolData = result.constant_result[0];
        return {
          lpToken: poolData.slice(24, 64), // Extract address
          allocPoint: this.contract.decodeResult(poolData.slice(64, 128), 'uint256'),
          lastRewardBlock: this.contract.decodeResult(poolData.slice(128, 192), 'uint256'),
          accRewardPerShare: this.contract.decodeResult(poolData.slice(192, 256), 'uint256')
        };
      }
      
      throw new Error('Failed to get pool info');
    } catch (error) {
      console.error('Error getting pool info:', error);
      throw error;
    }
  }
  
  async getUserStakeInfo(poolId, userAddress) {
    try {
      const encodedPoolId = this.contract.encodeUint256(poolId);
      const encodedUser = this.contract.encodeAddress(userAddress);
      const parameters = encodedPoolId + encodedUser;
      
      const result = await this.contract.call('userInfo(uint256,address)', parameters, userAddress);
      
      if (result.result?.result && result.constant_result?.[0]) {
        const userData = result.constant_result[0];
        return {
          amount: this.contract.decodeResult(userData.slice(0, 64), 'uint256'),
          rewardDebt: this.contract.decodeResult(userData.slice(64, 128), 'uint256')
        };
      }
      
      return { amount: '0', rewardDebt: '0' };
    } catch (error) {
      console.error('Error getting user stake info:', error);
      throw error;
    }
  }
  
  async getPendingRewards(poolId, userAddress) {
    try {
      const encodedPoolId = this.contract.encodeUint256(poolId);
      const encodedUser = this.contract.encodeAddress(userAddress);
      const parameters = encodedPoolId + encodedUser;
      
      const result = await this.contract.call('pendingReward(uint256,address)', parameters, userAddress);
      
      if (result.result?.result && result.constant_result?.[0]) {
        return this.contract.decodeResult(result.constant_result[0], 'uint256');
      }
      
      return '0';
    } catch (error) {
      console.error('Error getting pending rewards:', error);
      return '0';
    }
  }
  
  async createStakeTransaction(poolId, amount, userAddress) {
    try {
      const encodedPoolId = this.contract.encodeUint256(poolId);
      const encodedAmount = this.contract.encodeUint256(amount);
      const parameters = encodedPoolId + encodedAmount;
      
      const result = await this.contract.call('deposit(uint256,uint256)', parameters, userAddress);
      
      if (result.result?.result) {
        return result.transaction;
      }
      
      throw new Error(`Stake transaction creation failed: ${result.result?.message || 'Unknown error'}`);
    } catch (error) {
      console.error('Error creating stake transaction:', error);
      throw error;
    }
  }
}

3. NFT Marketplace Integration

JavaScript
class TronNFTMarketplace {
  constructor(apiKey, nftContractAddress) {
    this.contract = new TronSmartContract(apiKey, nftContractAddress);
  }
  
  async getNFTInfo(tokenId) {
    try {
      const encodedTokenId = this.contract.encodeUint256(tokenId);
      
      const [owner, tokenURI, approved] = await Promise.all([
        this.contract.call('ownerOf(uint256)', encodedTokenId),
        this.contract.call('tokenURI(uint256)', encodedTokenId),
        this.contract.call('getApproved(uint256)', encodedTokenId)
      ]);
      
      return {
        tokenId: tokenId,
        owner: this.contract.decodeResult(owner.constant_result[0], 'address'),
        tokenURI: this.contract.decodeResult(tokenURI.constant_result[0], 'string'),
        approved: this.contract.decodeResult(approved.constant_result[0], 'address')
      };
    } catch (error) {
      console.error('Error getting NFT info:', error);
      throw error;
    }
  }
  
  async getTokenBalance(owner) {
    try {
      const encodedOwner = this.contract.encodeAddress(owner);
      const result = await this.contract.call('balanceOf(address)', encodedOwner, owner);
      
      if (result.result?.result && result.constant_result?.[0]) {
        return this.contract.decodeResult(result.constant_result[0], 'uint256');
      }
      
      return '0';
    } catch (error) {
      console.error('Error getting token balance:', error);
      return '0';
    }
  }
  
  async createTransferTransaction(from, to, tokenId) {
    try {
      const encodedFrom = this.contract.encodeAddress(from);
      const encodedTo = this.contract.encodeAddress(to);
      const encodedTokenId = this.contract.encodeUint256(tokenId);
      const parameters = encodedFrom + encodedTo + encodedTokenId;
      
      const result = await this.contract.call(
        'transferFrom(address,address,uint256)', 
        parameters, 
        from
      );
      
      if (result.result?.result) {
        return result.transaction;
      }
      
      throw new Error(`Transfer creation failed: ${result.result?.message || 'Unknown error'}`);
    } catch (error) {
      console.error('Error creating transfer transaction:', error);
      throw error;
    }
  }
}

4. Automated Trading Bot

JavaScript
class TronTradingBot {
  constructor(apiKey, dexContractAddress) {
    this.dex = new TronSmartContract(apiKey, dexContractAddress);
    this.tokenManager = new TronContractManager(apiKey);
    this.strategies = new Map();
  }
  
  async getTokenPrice(tokenAddress, baseTokenAddress = 'TNUC9Qb1rRpS5CbWLmNMxXBjyFoydXjWFR') {
    try {
      const encodedToken = this.dex.encodeAddress(tokenAddress);
      const encodedBase = this.dex.encodeAddress(baseTokenAddress);
      const parameters = encodedToken + encodedBase;
      
      const result = await this.dex.call('getPrice(address,address)', parameters);
      
      if (result.result?.result && result.constant_result?.[0]) {
        return this.dex.decodeResult(result.constant_result[0], 'uint256');
      }
      
      return '0';
    } catch (error) {
      console.error('Error getting token price:', error);
      return '0';
    }
  }
  
  async createSwapTransaction(tokenA, tokenB, amountIn, minAmountOut, userAddress) {
    try {
      const encodedTokenA = this.dex.encodeAddress(tokenA);
      const encodedTokenB = this.dex.encodeAddress(tokenB);
      const encodedAmountIn = this.dex.encodeUint256(amountIn);
      const encodedMinOut = this.dex.encodeUint256(minAmountOut);
      const encodedUser = this.dex.encodeAddress(userAddress);
      
      const parameters = encodedTokenA + encodedTokenB + encodedAmountIn + encodedMinOut + encodedUser;
      
      const result = await this.dex.call(
        'swapExactTokensForTokens(address,address,uint256,uint256,address)', 
        parameters, 
        userAddress
      );
      
      if (result.result?.result) {
        return result.transaction;
      }
      
      throw new Error(`Swap creation failed: ${result.result?.message || 'Unknown error'}`);
    } catch (error) {
      console.error('Error creating swap transaction:', error);
      throw error;
    }
  }
  
  addStrategy(name, strategy) {
    this.strategies.set(name, strategy);
  }
  
  async executeStrategy(strategyName, params) {
    const strategy = this.strategies.get(strategyName);
    if (!strategy) {
      throw new Error(`Strategy ${strategyName} not found`);
    }
    
    return await strategy.execute(this, params);
  }
}

Performance Tips

  1. Batch Contract Calls - Group multiple read operations together
  2. Cache Results - Cache contract state that doesn't change frequently
  3. Optimize Parameters - Pre-encode parameters to reduce processing time
  4. Energy Management - Monitor energy usage and optimize contract interactions
JavaScript
// Optimized contract interaction with caching
class OptimizedContractClient {
  constructor(apiKey, contractAddress) {
    this.contract = new TronSmartContract(apiKey, contractAddress);
    this.cache = new Map();
    this.cacheTimeout = 60000; // 1 minute
  }
  
  async callWithCache(functionSelector, parameters, cacheKey, ttl = this.cacheTimeout) {
    const cached = this.cache.get(cacheKey);
    if (cached && Date.now() - cached.timestamp < ttl) {
      return cached.result;
    }
    
    const result = await this.contract.call(functionSelector, parameters);
    
    this.cache.set(cacheKey, {
      result,
      timestamp: Date.now()
    });
    
    return result;
  }
  
  clearCache() {
    this.cache.clear();
  }
}

Need help? Contact our support team or check the TRON documentation.

wallet/getblockbylatestnum

Get multiple recent TRON blocks by specifying a range from the latest block via Dwellir's high-performance RPC endpoint.

wallet/triggerconstantcontract

Call smart contract view functions without creating transactions, read contract state data instantly via Dwellir's optimized TRON RPC endpoint.

On this page

When to Use This MethodImplementation ExamplesResponse ExamplesSuccessful View Function Call (balanceOf)Failed Contract CallState-Changing Function Call (Transfer)Common Use Cases1. Portfolio Tracker2. DeFi Yield Farming Interface3. NFT Marketplace Integration4. Automated Trading BotPerformance Tips