wallet/triggerconstantcontract
Zero-Cost Contract Reads
Dwellir's TRON infrastructure enables instant contract state queries without consuming energy or bandwidth. Read smart contract data in real-time without transaction fees.
Execute smart contract view/pure functions without creating a blockchain transaction. Perfect for reading contract state, calculating values, or retrieving stored data.
Use Cases
wallet/triggerconstantcontract
is essential for:
- Token Balance Queries - Check TRC20 token balances
- Price Feeds - Read oracle price data
- Game State - Query game contract states
- DeFi Positions - Check liquidity pool shares
- Contract Verification - Test function outputs
Parameters
Parameter | Type | Required | Description |
---|---|---|---|
contract_address | string | Yes | Smart contract address (Base58 or Hex) |
function_selector | string | Yes | Function signature (e.g., "balanceOf(address)") |
parameter | string | No | Encoded function parameters (hex) |
owner_address | string | No | Address calling the function |
call_value | number | No | TRX amount in SUN (for payable functions) |
call_token_value | number | No | TRC10 token amount |
token_id | number | No | TRC10 token ID |
visible | boolean | No | Use Base58 format (default: true) |
Request Example
{
"contract_address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
"function_selector": "balanceOf(address)",
"parameter": "000000000000000000000000a614f803b6fd780986a42c78ec9c7f77e6ded13c",
"owner_address": "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN",
"visible": true
}
Response Fields
Field | Type | Description |
---|---|---|
result | object | Execution result |
result.result | boolean | Whether execution succeeded |
result.code | string | Response code |
result.message | string | Error message if failed |
energy_used | number | Estimated energy consumption |
constant_result | array | Return values (hex encoded) |
transaction | object | Simulated transaction object |
Implementation Examples
- JavaScript
- Python
- cURL
const TRON_API = 'https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY';
// Basic contract call
async function callContractView(contractAddress, functionSelector, parameter) {
const response = await fetch(`${TRON_API}/wallet/triggerconstantcontract`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
contract_address: contractAddress,
function_selector: functionSelector,
parameter: parameter,
visible: true
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
}
// TRC20 Token Interface
class TRC20Contract {
constructor(apiKey, contractAddress) {
this.apiUrl = `https://api-tron-mainnet.n.dwellir.com/${apiKey}`;
this.contractAddress = contractAddress;
this.decimals = null;
}
async callView(functionSelector, parameter = '') {
const response = await fetch(`${this.apiUrl}/wallet/triggerconstantcontract`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
contract_address: this.contractAddress,
function_selector: functionSelector,
parameter: parameter,
visible: true
})
});
const result = await response.json();
if (!result.result?.result) {
throw new Error(result.result?.message || 'Contract call failed');
}
return result.constant_result?.[0] || '0x';
}
// Encode address for parameter
encodeAddress(address) {
// Remove 'T' prefix and decode base58 to hex
// This is simplified - actual implementation needs base58 decoder
if (address.startsWith('T')) {
// Convert Base58 to hex (placeholder)
const hex = address.substring(1).toLowerCase();
return '000000000000000000000000' + hex.padEnd(40, '0').substring(0, 40);
}
return address;
}
// Decode uint256 result
decodeUint256(hex) {
if (!hex || hex === '0x') return '0';
const cleaned = hex.replace('0x', '');
return BigInt('0x' + cleaned).toString();
}
// Get token balance
async balanceOf(address) {
const parameter = this.encodeAddress(address);
const result = await this.callView('balanceOf(address)', parameter);
const balance = this.decodeUint256(result);
// Get decimals if not cached
if (this.decimals === null) {
this.decimals = await this.getDecimals();
}
return {
raw: balance,
formatted: this.formatUnits(balance, this.decimals)
};
}
// Get token decimals
async getDecimals() {
const result = await this.callView('decimals()');
return parseInt(this.decodeUint256(result));
}
// Get token symbol
async symbol() {
const result = await this.callView('symbol()');
return this.decodeString(result);
}
// Get token name
async name() {
const result = await this.callView('name()');
return this.decodeString(result);
}
// Get total supply
async totalSupply() {
const result = await this.callView('totalSupply()');
const supply = this.decodeUint256(result);
if (this.decimals === null) {
this.decimals = await this.getDecimals();
}
return {
raw: supply,
formatted: this.formatUnits(supply, this.decimals)
};
}
// Get allowance
async allowance(owner, spender) {
const parameter = this.encodeAddress(owner) + this.encodeAddress(spender);
const result = await this.callView('allowance(address,address)', parameter);
return this.decodeUint256(result);
}
// Format units with decimals
formatUnits(value, decimals) {
const divisor = BigInt(10) ** BigInt(decimals);
const quotient = BigInt(value) / divisor;
const remainder = BigInt(value) % divisor;
if (remainder === 0n) {
return quotient.toString();
}
const remainderStr = remainder.toString().padStart(decimals, '0');
const trimmed = remainderStr.replace(/0+$/, '');
return `${quotient}.${trimmed}`;
}
// Decode string from hex
decodeString(hex) {
if (!hex || hex === '0x') return '';
try {
// Remove 0x prefix
const cleaned = hex.replace('0x', '');
// Skip first 64 chars (offset) and next 64 chars (length)
const dataStart = 128;
const lengthHex = cleaned.substring(64, 128);
const length = parseInt(lengthHex, 16) * 2;
const stringHex = cleaned.substring(dataStart, dataStart + length);
// Convert hex to string
let result = '';
for (let i = 0; i < stringHex.length; i += 2) {
result += String.fromCharCode(parseInt(stringHex.substr(i, 2), 16));
}
return result;
} catch (error) {
console.error('String decode error:', error);
return '';
}
}
}
// DeFi Protocol Reader
class DeFiProtocolReader {
constructor(apiKey) {
this.apiKey = apiKey;
this.apiUrl = `https://api-tron-mainnet.n.dwellir.com/${apiKey}`;
}
async readContract(address, method, params = '') {
const response = await fetch(`${this.apiUrl}/wallet/triggerconstantcontract`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
contract_address: address,
function_selector: method,
parameter: params,
visible: true
})
});
return await response.json();
}
// Read lending protocol data
async getLendingPosition(protocol, userAddress) {
const params = this.encodeAddress(userAddress);
const [
supplyBalance,
borrowBalance,
collateralRatio
] = await Promise.all([
this.readContract(protocol, 'getSupplyBalance(address)', params),
this.readContract(protocol, 'getBorrowBalance(address)', params),
this.readContract(protocol, 'getCollateralRatio(address)', params)
]);
return {
supplied: this.decodeResult(supplyBalance),
borrowed: this.decodeResult(borrowBalance),
collateralRatio: this.decodeResult(collateralRatio),
healthFactor: this.calculateHealthFactor(
this.decodeResult(supplyBalance),
this.decodeResult(borrowBalance),
this.decodeResult(collateralRatio)
)
};
}
// Read DEX pool data
async getPoolInfo(poolAddress) {
const [
reserves,
totalSupply,
fee
] = await Promise.all([
this.readContract(poolAddress, 'getReserves()'),
this.readContract(poolAddress, 'totalSupply()'),
this.readContract(poolAddress, 'fee()')
]);
const reserveData = this.decodeReserves(reserves.constant_result?.[0]);
return {
token0Reserve: reserveData.reserve0,
token1Reserve: reserveData.reserve1,
totalSupply: this.decodeResult(totalSupply),
fee: this.decodeResult(fee),
price: this.calculatePrice(reserveData.reserve0, reserveData.reserve1)
};
}
// Read oracle price
async getOraclePrice(oracleAddress, pairId) {
const params = this.encodeUint256(pairId);
const result = await this.readContract(
oracleAddress,
'getLatestPrice(uint256)',
params
);
const price = this.decodeResult(result);
return {
price: price,
formatted: this.formatPrice(price),
timestamp: Date.now()
};
}
encodeAddress(address) {
// Simplified encoding
return '000000000000000000000000' + address.replace('T', '').substring(0, 40);
}
encodeUint256(value) {
const hex = BigInt(value).toString(16);
return hex.padStart(64, '0');
}
decodeResult(response) {
const hex = response.constant_result?.[0] || '0x0';
return BigInt('0x' + hex.replace('0x', '')).toString();
}
decodeReserves(hex) {
if (!hex) return { reserve0: '0', reserve1: '0' };
const cleaned = hex.replace('0x', '');
const reserve0 = BigInt('0x' + cleaned.substring(0, 64)).toString();
const reserve1 = BigInt('0x' + cleaned.substring(64, 128)).toString();
return { reserve0, reserve1 };
}
calculatePrice(reserve0, reserve1) {
if (reserve1 === '0') return '0';
return (BigInt(reserve0) * BigInt(1e18) / BigInt(reserve1)).toString();
}
calculateHealthFactor(supply, borrow, ratio) {
if (borrow === '0') return 'Infinite';
const factor = (BigInt(supply) * BigInt(ratio)) / BigInt(borrow);
return (factor / BigInt(100)).toString();
}
formatPrice(price) {
const priceNum = Number(price) / 1e18;
return priceNum.toFixed(6);
}
}
// Usage examples
(async () => {
try {
// USDT Contract
const usdt = new TRC20Contract('YOUR_API_KEY', 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t');
// Get token info
const [name, symbol, decimals, totalSupply] = await Promise.all([
usdt.name(),
usdt.symbol(),
usdt.getDecimals(),
usdt.totalSupply()
]);
console.log(`Token: ${name} (${symbol})`);
console.log(`Decimals: ${decimals}`);
console.log(`Total Supply: ${totalSupply.formatted}`);
// Check balance
const balance = await usdt.balanceOf('TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN');
console.log(`Balance: ${balance.formatted} ${symbol}`);
// DeFi Protocol Reader
const defi = new DeFiProtocolReader('YOUR_API_KEY');
// Read lending position
const position = await defi.getLendingPosition(
'TLendingProtocolAddress',
'TUserAddress'
);
console.log('Lending Position:', position);
// Get oracle price
const price = await defi.getOraclePrice('TOracleAddress', 1);
console.log(`Oracle Price: $${price.formatted}`);
} catch (error) {
console.error('Error:', error);
}
})();
import requests
import json
from typing import Dict, Optional, Any
from web3 import Web3
class TronContractReader:
def __init__(self, api_key: str):
self.base_url = f"https://api-tron-mainnet.n.dwellir.com/{api_key}"
self.headers = {'Content-Type': 'application/json'}
self.w3 = Web3() # For encoding/decoding
def trigger_constant_contract(
self,
contract_address: str,
function_selector: str,
parameter: str = '',
owner_address: Optional[str] = None,
visible: bool = True
) -> Dict:
"""
Call a view/pure function on a smart contract
"""
url = f"{self.base_url}/wallet/triggerconstantcontract"
payload = {
"contract_address": contract_address,
"function_selector": function_selector,
"parameter": parameter,
"visible": visible
}
if owner_address:
payload["owner_address"] = owner_address
response = requests.post(url, headers=self.headers, json=payload)
response.raise_for_status()
return response.json()
def encode_address(self, address: str) -> str:
"""
Encode TRON address for function parameter
"""
# Remove T prefix for Base58 addresses
if address.startswith('T'):
# Simplified - actual implementation needs base58 decoder
hex_addr = address[1:].lower()[:40].zfill(40)
return '000000000000000000000000' + hex_addr
return address.zfill(64)
def encode_uint256(self, value: int) -> str:
"""
Encode integer as uint256
"""
return format(value, '064x')
def decode_uint256(self, hex_value: str) -> int:
"""
Decode uint256 from hex
"""
if not hex_value or hex_value == '0x':
return 0
cleaned = hex_value.replace('0x', '')
return int(cleaned, 16)
def decode_address(self, hex_value: str) -> str:
"""
Decode address from hex result
"""
if not hex_value or len(hex_value) < 64:
return ''
cleaned = hex_value.replace('0x', '')
# Get last 40 characters (20 bytes)
return '41' + cleaned[-40:]
def decode_string(self, hex_value: str) -> str:
"""
Decode string from hex result
"""
if not hex_value or hex_value == '0x':
return ''
try:
cleaned = hex_value.replace('0x', '')
# Skip offset (first 32 bytes)
# Read length (next 32 bytes)
if len(cleaned) < 128:
return ''
length = int(cleaned[64:128], 16) * 2
string_hex = cleaned[128:128 + length]
# Convert hex to string
result = bytes.fromhex(string_hex).decode('utf-8')
return result.rstrip('\x00')
except:
return ''
def decode_bool(self, hex_value: str) -> bool:
"""
Decode boolean from hex result
"""
return self.decode_uint256(hex_value) != 0
class TRC20Token(TronContractReader):
"""
TRC20 Token Interface
"""
def __init__(self, api_key: str, contract_address: str):
super().__init__(api_key)
self.contract_address = contract_address
self._decimals = None
self._symbol = None
self._name = None
def call_view(self, function: str, params: str = '') -> str:
"""
Call a view function on the token contract
"""
result = self.trigger_constant_contract(
self.contract_address,
function,
params
)
if not result.get('result', {}).get('result'):
raise Exception(f"Contract call failed: {result.get('result', {}).get('message')}")
return result.get('constant_result', ['0x'])[0]
def balance_of(self, address: str) -> Dict:
"""
Get token balance of an address
"""
params = self.encode_address(address)
result = self.call_view('balanceOf(address)', params)
raw_balance = self.decode_uint256(result)
decimals = self.decimals()
formatted = self.format_units(raw_balance, decimals)
return {
'raw': str(raw_balance),
'formatted': formatted,
'decimals': decimals
}
def decimals(self) -> int:
"""
Get token decimals (cached)
"""
if self._decimals is None:
result = self.call_view('decimals()')
self._decimals = self.decode_uint256(result)
return self._decimals
def symbol(self) -> str:
"""
Get token symbol (cached)
"""
if self._symbol is None:
result = self.call_view('symbol()')
self._symbol = self.decode_string(result)
return self._symbol
def name(self) -> str:
"""
Get token name (cached)
"""
if self._name is None:
result = self.call_view('name()')
self._name = self.decode_string(result)
return self._name
def total_supply(self) -> Dict:
"""
Get total supply
"""
result = self.call_view('totalSupply()')
raw_supply = self.decode_uint256(result)
decimals = self.decimals()
formatted = self.format_units(raw_supply, decimals)
return {
'raw': str(raw_supply),
'formatted': formatted
}
def allowance(self, owner: str, spender: str) -> Dict:
"""
Get allowance
"""
params = self.encode_address(owner) + self.encode_address(spender)
result = self.call_view('allowance(address,address)', params)
raw_allowance = self.decode_uint256(result)
decimals = self.decimals()
formatted = self.format_units(raw_allowance, decimals)
return {
'raw': str(raw_allowance),
'formatted': formatted
}
def format_units(self, value: int, decimals: int) -> str:
"""
Format value with decimals
"""
if decimals == 0:
return str(value)
divisor = 10 ** decimals
quotient = value // divisor
remainder = value % divisor
if remainder == 0:
return str(quotient)
remainder_str = str(remainder).zfill(decimals).rstrip('0')
return f"{quotient}.{remainder_str}"
class DeFiProtocol(TronContractReader):
"""
DeFi Protocol Reader
"""
def __init__(self, api_key: str):
super().__init__(api_key)
def get_pool_reserves(self, pool_address: str) -> Dict:
"""
Get DEX pool reserves
"""
result = self.trigger_constant_contract(
pool_address,
'getReserves()'
)
if not result.get('constant_result'):
return {'reserve0': 0, 'reserve1': 0}
hex_result = result['constant_result'][0].replace('0x', '')
reserve0 = int(hex_result[0:64], 16)
reserve1 = int(hex_result[64:128], 16)
return {
'reserve0': reserve0,
'reserve1': reserve1,
'price': self.calculate_price(reserve0, reserve1),
'liquidity': (reserve0 * reserve1) ** 0.5
}
def get_lending_position(self, protocol: str, user: str) -> Dict:
"""
Get lending protocol position
"""
params = self.encode_address(user)
# Get multiple values in parallel
supply_result = self.trigger_constant_contract(
protocol, 'getSupplyBalance(address)', params
)
borrow_result = self.trigger_constant_contract(
protocol, 'getBorrowBalance(address)', params
)
supply = self.decode_uint256(supply_result.get('constant_result', ['0'])[0])
borrow = self.decode_uint256(borrow_result.get('constant_result', ['0'])[0])
return {
'supplied': supply,
'borrowed': borrow,
'net_position': supply - borrow,
'utilization': (borrow / supply * 100) if supply > 0 else 0
}
def get_oracle_price(self, oracle: str, pair_id: int) -> Dict:
"""
Get price from oracle
"""
params = self.encode_uint256(pair_id)
result = self.trigger_constant_contract(
oracle,
'getLatestPrice(uint256)',
params
)
price = self.decode_uint256(result.get('constant_result', ['0'])[0])
return {
'price': price,
'formatted': price / 1e18, # Assuming 18 decimals
'pair_id': pair_id
}
def calculate_price(self, reserve0: int, reserve1: int) -> float:
"""
Calculate price from reserves
"""
if reserve1 == 0:
return 0
return reserve0 / reserve1
class MultiContractReader:
"""
Read multiple contracts efficiently
"""
def __init__(self, api_key: str):
self.api_key = api_key
self.reader = TronContractReader(api_key)
def batch_token_info(self, token_addresses: list) -> list:
"""
Get info for multiple tokens
"""
results = []
for address in token_addresses:
try:
token = TRC20Token(self.api_key, address)
info = {
'address': address,
'name': token.name(),
'symbol': token.symbol(),
'decimals': token.decimals(),
'total_supply': token.total_supply()
}
results.append(info)
except Exception as e:
results.append({
'address': address,
'error': str(e)
})
return results
def portfolio_balance(self, user: str, token_list: list) -> Dict:
"""
Get user's token portfolio
"""
portfolio = []
for token_addr in token_list:
try:
token = TRC20Token(self.api_key, token_addr)
balance = token.balance_of(user)
if int(balance['raw']) > 0:
portfolio.append({
'token': token_addr,
'symbol': token.symbol(),
'balance': balance['formatted'],
'raw': balance['raw']
})
except:
continue
return {
'address': user,
'tokens': portfolio,
'token_count': len(portfolio)
}
# Usage examples
if __name__ == "__main__":
# Initialize clients
reader = TronContractReader('YOUR_API_KEY')
# USDT Token
usdt = TRC20Token('YOUR_API_KEY', 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t')
try:
# Get token info
print(f"Token: {usdt.name()} ({usdt.symbol()})")
print(f"Decimals: {usdt.decimals()}")
total_supply = usdt.total_supply()
print(f"Total Supply: {total_supply['formatted']} {usdt.symbol()}")
# Check balance
address = 'TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN'
balance = usdt.balance_of(address)
print(f"\nBalance of {address[:10]}...")
print(f" {balance['formatted']} {usdt.symbol()}")
# DeFi operations
defi = DeFiProtocol('YOUR_API_KEY')
# Get pool reserves (example)
pool = 'TPoolAddress'
reserves = defi.get_pool_reserves(pool)
print(f"\nPool Reserves:")
print(f" Reserve0: {reserves['reserve0']}")
print(f" Reserve1: {reserves['reserve1']}")
print(f" Price: {reserves['price']:.6f}")
# Multi-contract reader
multi = MultiContractReader('YOUR_API_KEY')
# Check multiple tokens
tokens = [
'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t', # USDT
'TNUC9Qb1rRpS5CbWLmNMxXBjyFoydXjWFR' # WTRX
]
token_info = multi.batch_token_info(tokens)
print(f"\nToken Information:")
for info in token_info:
if 'error' not in info:
print(f" {info['symbol']}: {info['total_supply']['formatted']}")
# Get portfolio
portfolio = multi.portfolio_balance(address, tokens)
print(f"\nPortfolio for {address[:10]}...")
for holding in portfolio['tokens']:
print(f" {holding['symbol']}: {holding['balance']}")
except Exception as e:
print(f"Error: {e}")
# Call TRC20 balanceOf function
curl -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/triggerconstantcontract" \
-H "Content-Type: application/json" \
-d '{
"contract_address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
"function_selector": "balanceOf(address)",
"parameter": "000000000000000000000000a614f803b6fd780986a42c78ec9c7f77e6ded13c",
"visible": true
}'
# Get token name
curl -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/triggerconstantcontract" \
-H "Content-Type: application/json" \
-d '{
"contract_address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
"function_selector": "name()",
"visible": true
}'
# Get token symbol
curl -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/triggerconstantcontract" \
-H "Content-Type: application/json" \
-d '{
"contract_address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
"function_selector": "symbol()",
"visible": true
}'
# Get total supply
curl -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/triggerconstantcontract" \
-H "Content-Type: application/json" \
-d '{
"contract_address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
"function_selector": "totalSupply()",
"visible": true
}'
# Parse balance result with jq
curl -s -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/triggerconstantcontract" \
-H "Content-Type: application/json" \
-d '{
"contract_address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
"function_selector": "balanceOf(address)",
"parameter": "000000000000000000000000a614f803b6fd780986a42c78ec9c7f77e6ded13c",
"visible": true
}' | jq '{
success: .result.result,
energy_used: .energy_used,
balance_hex: .constant_result[0],
balance_decimal: (.constant_result[0] | ltrimstr("0x") |
if . == "" then "0" else . end |
tonumber | tostring)
}'
# Script to check multiple token balances
#!/bin/bash
API_KEY="YOUR_API_KEY"
USER_ADDRESS_HEX="000000000000000000000000a614f803b6fd780986a42c78ec9c7f77e6ded13c"
TOKENS=(
"TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t:USDT"
"TNUC9Qb1rRpS5CbWLmNMxXBjyFoydXjWFR:WTRX"
)
for token_info in "${TOKENS[@]}"; do
IFS=':' read -r addr symbol <<< "$token_info"
echo "Checking $symbol balance..."
response=$(curl -s -X POST \
"https://api-tron-mainnet.n.dwellir.com/$API_KEY/wallet/triggerconstantcontract" \
-H "Content-Type: application/json" \
-d "{
\"contract_address\": \"$addr\",
\"function_selector\": \"balanceOf(address)\",
\"parameter\": \"$USER_ADDRESS_HEX\",
\"visible\": true
}")
balance=$(echo "$response" | jq -r '.constant_result[0]')
if [ "$balance" != "null" ] && [ "$balance" != "" ]; then
# Convert hex to decimal (simplified)
echo " Raw: $balance"
else
echo " Error or zero balance"
fi
echo ""
done
Response Example
Successful Response
{
"result": {
"result": true,
"code": "SUCCESS",
"message": ""
},
"energy_used": 968,
"constant_result": [
"0000000000000000000000000000000000000000000000000000000005f5e100"
],
"transaction": {
"visible": true,
"txID": "abc123...",
"raw_data": {
"contract": [
{
"parameter": {
"value": {
"data": "70a08231000000000000000000000000a614f803b6fd780986a42c78ec9c7f77e6ded13c",
"owner_address": "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN",
"contract_address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
},
"type_url": "type.googleapis.com/protocol.TriggerSmartContract"
},
"type": "TriggerSmartContract"
}
],
"ref_block_bytes": "7ac7",
"ref_block_hash": "4d9bb8f8c9c59ac3",
"expiration": 1702456849000,
"timestamp": 1702456789000
}
}
}
Failed Response
{
"result": {
"result": false,
"code": "CONTRACT_VALIDATE_ERROR",
"message": "No contract or not a valid smart contract"
}
}
Common Use Cases
1. Token Balance Checker
async function checkTokenBalance(tokenAddress, userAddress) {
const token = new TRC20Contract('API_KEY', tokenAddress);
try {
const [symbol, decimals, balance] = await Promise.all([
token.symbol(),
token.getDecimals(),
token.balanceOf(userAddress)
]);
return {
token: symbol,
balance: balance.formatted,
decimals: decimals,
hasBalance: BigInt(balance.raw) > 0n
};
} catch (error) {
return {
error: 'Failed to fetch token data',
details: error.message
};
}
}
2. DEX Price Monitor
async function monitorDexPrice(poolAddress) {
const getPrice = async () => {
const result = await callContractView(
poolAddress,
'getReserves()'
);
const reserves = parseReserves(result.constant_result[0]);
return calculatePrice(reserves.token0, reserves.token1);
};
return setInterval(async () => {
const price = await getPrice();
console.log(`Current price: ${price}`);
}, 10000); // Check every 10 seconds
}
3. Multi-Call Pattern
async function getCompleteTokenInfo(tokenAddress) {
const functions = [
'name()',
'symbol()',
'decimals()',
'totalSupply()'
];
const results = await Promise.all(
functions.map(fn =>
callContractView(tokenAddress, fn)
)
);
return {
name: decodeString(results[0].constant_result[0]),
symbol: decodeString(results[1].constant_result[0]),
decimals: decodeUint256(results[2].constant_result[0]),
totalSupply: decodeUint256(results[3].constant_result[0])
};
}
Error Handling
Error Code | Description | Solution |
---|---|---|
CONTRACT_VALIDATE_ERROR | Invalid contract address | Verify contract exists |
OUT_OF_ENERGY | Insufficient energy for call | Add energy estimation |
REVERT | Function reverted | Check function requirements |
INVALID_METHOD | Function doesn't exist | Verify function signature |
async function safeContractCall(address, method, params) {
try {
const result = await callContractView(address, method, params);
if (!result.result?.result) {
return {
success: false,
error: result.result?.message || 'Unknown error',
code: result.result?.code
};
}
return {
success: true,
data: result.constant_result?.[0] || '0x',
energyUsed: result.energy_used
};
} catch (error) {
return {
success: false,
error: error.message,
code: 'NETWORK_ERROR'
};
}
}
Best Practices
- Cache Results - Cache view function results appropriately
- Batch Calls - Group multiple calls for efficiency
- Handle Errors - Always check result.result for success
- Estimate Energy - Monitor energy_used for optimization
- Validate Input - Ensure parameters are properly encoded
Related Methods
- wallet/triggersmartcontract - Execute state-changing functions
- wallet/getcontract - Get contract information
- wallet/estimateenergy - Estimate energy consumption
Need help? Contact support or visit our TRON documentation.