Skip to main content

wallet/broadcasttransaction

Instant Transaction Broadcasting

Dwellir's TRON endpoints broadcast transactions to the network in under 100ms with real-time confirmation tracking. Get instant feedback on transaction success and network inclusion.

Start broadcasting now →

Broadcasts a signed transaction to the TRON network for execution. This is the final step after creating and signing a transaction.

When to Use This Method#

wallet/broadcasttransaction is essential for:

  • Transaction Execution - Submit signed transactions to the network
  • Payment Processing - Complete payment transactions in real-time
  • Smart Contract Calls - Execute signed contract interactions
  • Multi-Signature Operations - Broadcast fully-signed multi-sig transactions
  • Batch Processing - Submit multiple transactions efficiently

Parameters#

Signed Transaction Object - Complete transaction with signatures

  • txID - Transaction identifier
  • raw_data - Original transaction data
  • raw_data_hex - Hex encoded transaction data
  • signature - Array of signatures (hex strings)
  • visible - Address format indicator
{
"txID": "94eea63bb6774c8fc4f4c9d1b62c1e8c2f7c8c2e4d3a2b1c0d9e8f7a6b5c4d3e2f1",
"raw_data": {
"contract": [
{
"parameter": {
"value": {
"amount": 1000000,
"owner_address": "TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh",
"to_address": "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN"
},
"type_url": "type.googleapis.com/protocol.TransferContract"
},
"type": "TransferContract"
}
],
"ref_block_bytes": "4a7b",
"ref_block_hash": "e15e44aa73bd9e15",
"expiration": 1734567890000,
"timestamp": 1734567830000
},
"signature": ["c8f8f8e8d8c8b8a898887878686858484838281807060504030201"]
}

Returns#

Broadcast Result containing:

  • result - Boolean indicating broadcast success
  • txid - Transaction ID (if successful)
  • code - Error code (if failed)
  • message - Error message (if failed)

Implementation Examples#

# Basic transaction broadcast
curl -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/broadcasttransaction" \
-H "Content-Type: application/json" \
-d '{
"txID": "94eea63bb6774c8fc4f4c9d1b62c1e8c2f7c8c2e4d3a2b1c0d9e8f7a6b5c4d3e2f1",
"raw_data": {
"contract": [{
"parameter": {
"value": {
"amount": 1000000,
"owner_address": "TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh",
"to_address": "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN"
},
"type_url": "type.googleapis.com/protocol.TransferContract"
},
"type": "TransferContract"
}],
"ref_block_bytes": "4a7b",
"ref_block_hash": "e15e44aa73bd9e15",
"expiration": 1734567890000,
"timestamp": 1734567830000
},
"signature": ["c8f8f8e8d8c8b8a898887878686858484838281807060504030201"]
}'

# Broadcast and check result
curl -s -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/broadcasttransaction" \
-H "Content-Type: application/json" \
-d @signed_transaction.json | jq '{
success: .result,
txid: .txid,
error: .message
}'

# Script with retry logic
#!/bin/bash
API_KEY="YOUR_API_KEY"
SIGNED_TX_FILE="signed_transaction.json"
MAX_RETRIES=3

broadcast_with_retry() {
local attempt=1

while [ $attempt -le $MAX_RETRIES ]; do
echo "Broadcasting transaction (attempt $attempt/$MAX_RETRIES)..."

RESULT=$(curl -s -X POST "https://api-tron-mainnet.n.dwellir.com/$API_KEY/wallet/broadcasttransaction" \
-H "Content-Type: application/json" \
-d @"$SIGNED_TX_FILE")

SUCCESS=$(echo "$RESULT" | jq -r '.result // false')

if [ "$SUCCESS" = "true" ]; then
TXID=$(echo "$RESULT" | jq -r '.txid')
echo "✓ Transaction broadcast successful: $TXID"
return 0
else
ERROR=$(echo "$RESULT" | jq -r '.message // "Unknown error"')
echo "✗ Attempt $attempt failed: $ERROR"

if [ $attempt -eq $MAX_RETRIES ]; then
echo "Transaction broadcast failed after $MAX_RETRIES attempts"
return 1
fi

# Exponential backoff
DELAY=$((2 ** (attempt - 1)))
echo "Waiting ${DELAY}s before retry..."
sleep $DELAY
fi

((attempt++))
done
}

# Check transaction confirmation
check_confirmation() {
local txid=$1
local timeout=${2:-30}
local start_time=$(date +%s)

echo "Waiting for confirmation of $txid..."

while true; do
current_time=$(date +%s)
elapsed=$((current_time - start_time))

if [ $elapsed -ge $timeout ]; then
echo "Confirmation timeout after ${timeout}s"
return 1
fi

TX_INFO=$(curl -s -X POST "https://api-tron-mainnet.n.dwellir.com/$API_KEY/wallet/gettransactionbyid" \
-H "Content-Type: application/json" \
-d "{\"value\": \"$txid\", \"visible\": true}")

BLOCK_NUM=$(echo "$TX_INFO" | jq -r '.blockNumber // null')

if [ "$BLOCK_NUM" != "null" ]; then
echo "✓ Transaction confirmed in block $BLOCK_NUM"
return 0
fi

echo "Checking confirmation... (${elapsed}s elapsed)"
sleep 3
done
}

# Batch broadcasting script
batch_broadcast() {
local tx_files=("$@")
local successful=0
local failed=0

echo "Broadcasting ${#tx_files[@]} transactions..."

for tx_file in "${tx_files[@]}"; do
echo "Processing $tx_file..."

if broadcast_with_retry "$tx_file"; then
((successful++))
else
((failed++))
fi

# Rate limiting
sleep 0.1
done

echo "Batch complete: $successful successful, $failed failed"
}

# Usage
if [ "$1" = "single" ]; then
broadcast_with_retry && check_confirmation "$(echo "$RESULT" | jq -r '.txid')"
elif [ "$1" = "batch" ]; then
shift
batch_broadcast "$@"
else
echo "Usage: $0 {single|batch} [tx_files...]"
fi

Response Examples#

Successful Broadcast#

{
"result": true,
"txid": "94eea63bb6774c8fc4f4c9d1b62c1e8c2f7c8c2e4d3a2b1c0d9e8f7a6b5c4d3e2f1"
}

Failed Broadcast (Insufficient Energy)#

{
"result": false,
"code": "CONTRACT_VALIDATE_ERROR",
"message": "account does not have enough energy"
}

Network Error#

{
"result": false,
"code": "SERVER_BUSY",
"message": "Server is busy, please try again later"
}

Common Use Cases#

1. Payment Gateway Completion#

class PaymentProcessor {
constructor(apiKey) {
this.apiKey = apiKey;
this.broadcaster = new TronBroadcaster(apiKey);
}

async processPayment(paymentRequest) {
try {
const { signedTransaction, paymentId, amount, customer } = paymentRequest;

console.log(`Processing payment ${paymentId} for ${amount} TRX`);

// Broadcast with monitoring
const result = await this.broadcaster.broadcast_with_monitoring(
signedTransaction,
{
maxRetries: 5,
waitForConfirmation: true,
confirmationTimeout: 60000
}
);

if (result.result && result.confirmation?.confirmed) {
// Payment successful
await this.updatePaymentStatus(paymentId, 'completed', result.txid);
await this.notifyCustomer(customer, 'payment_success', result.txid);

return {
status: 'completed',
txId: result.txid,
blockNumber: result.confirmation.blockNumber,
fee: result.confirmation.fee
};
} else {
throw new Error('Payment confirmation failed');
}

} catch (error) {
await this.updatePaymentStatus(paymentId, 'failed', null, error.message);
await this.notifyCustomer(customer, 'payment_failed', error.message);
throw error;
}
}

async updatePaymentStatus(paymentId, status, txId = null, error = null) {
// Update payment in database
console.log(`Payment ${paymentId} status: ${status}`);
}

async notifyCustomer(customer, event, data) {
// Send notification to customer
console.log(`Notifying ${customer}: ${event} - ${data}`);
}
}

2. Multi-Signature Transaction Execution#

async function executeMultiSigTransaction(multiSigTransaction, requiredSignatures) {
try {
// Verify we have enough signatures
if (multiSigTransaction.signature.length < requiredSignatures) {
throw new Error(`Insufficient signatures: ${multiSigTransaction.signature.length}/${requiredSignatures}`);
}

console.log(`Executing multi-sig transaction with ${multiSigTransaction.signature.length} signatures`);

const result = await broadcastWithMonitoring(multiSigTransaction, {
maxRetries: 3,
waitForConfirmation: true
});

return {
executed: true,
txId: result.txid,
signatures: multiSigTransaction.signature.length,
confirmation: result.confirmation
};

} catch (error) {
console.error('Multi-sig execution failed:', error);
return {
executed: false,
error: error.message,
signatures: multiSigTransaction.signature?.length || 0
};
}
}

3. Automated Trading Bot#

class TronTradingBot {
constructor(apiKey, strategy) {
this.apiKey = apiKey;
this.strategy = strategy;
this.broadcaster = new TronBroadcaster(apiKey);
this.pendingTrades = new Map();
}

async executeTrade(tradeSignal) {
try {
const { action, amount, price, signedTransaction } = tradeSignal;

console.log(`Executing ${action} trade: ${amount} TRX at ${price}`);

// Broadcast trade transaction
const result = await this.broadcaster.broadcast_with_monitoring(
signedTransaction,
{
maxRetries: 2,
waitForConfirmation: false // Don't wait for DEX trades
}
);

if (result.result) {
// Track pending trade
this.pendingTrades.set(result.txid, {
action,
amount,
price,
timestamp: Date.now(),
status: 'pending'
});

// Monitor in background
this.monitorTradeConfirmation(result.txid);

return {
success: true,
tradeId: result.txid,
action,
amount,
price
};
} else {
throw new Error(`Trade broadcast failed: ${result.message}`);
}

} catch (error) {
console.error('Trade execution failed:', error);
return {
success: false,
error: error.message,
action: tradeSignal.action
};
}
}

async monitorTradeConfirmation(txId) {
// Background monitoring
setTimeout(async () => {
try {
const confirmation = await this.broadcaster.wait_for_confirmation(txId, 30000);
const trade = this.pendingTrades.get(txId);

if (confirmation.confirmed && trade) {
trade.status = 'confirmed';
trade.blockNumber = confirmation.blockNumber;
console.log(`Trade ${txId} confirmed in block ${confirmation.blockNumber}`);

// Update strategy
this.strategy.onTradeConfirmed(trade);
}
} catch (error) {
console.error(`Trade monitoring failed for ${txId}:`, error);
}
}, 1000);
}
}

4. Subscription Payment Processing#

class SubscriptionManager {
constructor(apiKey) {
this.broadcaster = new TronBroadcaster(apiKey);
this.subscriptions = new Map();
}

async processSubscriptionPayment(subscriptionId, signedTransaction) {
try {
const subscription = this.subscriptions.get(subscriptionId);
if (!subscription) {
throw new Error('Subscription not found');
}

console.log(`Processing subscription payment for ${subscriptionId}`);

const result = await this.broadcaster.broadcast_with_monitoring(
signedTransaction,
{
maxRetries: 3,
waitForConfirmation: true,
confirmationTimeout: 45000
}
);

if (result.result && result.confirmation?.confirmed) {
// Update subscription status
subscription.status = 'active';
subscription.lastPayment = Date.now();
subscription.nextBilling = Date.now() + (30 * 24 * 60 * 60 * 1000); // 30 days
subscription.txId = result.txid;

await this.activateSubscription(subscriptionId);
await this.scheduleNextBilling(subscriptionId);

return {
success: true,
subscriptionId,
txId: result.txid,
nextBilling: subscription.nextBilling
};
} else {
throw new Error('Payment confirmation failed');
}

} catch (error) {
console.error(`Subscription payment failed for ${subscriptionId}:`, error);

// Update subscription status
const subscription = this.subscriptions.get(subscriptionId);
if (subscription) {
subscription.status = 'payment_failed';
subscription.lastError = error.message;
}

throw error;
}
}

async activateSubscription(subscriptionId) {
console.log(`Activating subscription ${subscriptionId}`);
// Activate user's subscription features
}

async scheduleNextBilling(subscriptionId) {
const subscription = this.subscriptions.get(subscriptionId);
if (subscription) {
console.log(`Next billing for ${subscriptionId}: ${new Date(subscription.nextBilling)}`);
// Schedule next payment reminder
}
}
}

Error Handling#

Error CodeDescriptionSolution
CONTRACT_VALIDATE_ERRORTransaction validation failedCheck balance, signatures, and transaction data
BANDWIDTH_ERRORInsufficient bandwidthWait for bandwidth reset or use TRX for fees
ENERGY_ERRORInsufficient energyFreeze TRX for energy or rent energy
SIGNATURE_ERRORInvalid signatureRe-sign transaction with correct private key
EXPIRED_ERRORTransaction expiredCreate new transaction with updated timestamp
SERVER_BUSYNetwork congestionRetry with exponential backoff
// Comprehensive error handling
async function robustBroadcast(signedTransaction, options = {}) {
const errors = {
CONTRACT_VALIDATE_ERROR: 'Transaction validation failed',
BANDWIDTH_ERROR: 'Insufficient bandwidth - wait 24h or freeze TRX',
ENERGY_ERROR: 'Insufficient energy - freeze TRX or rent energy',
SIGNATURE_ERROR: 'Invalid signature - check private key',
EXPIRED_ERROR: 'Transaction expired - create new transaction',
SERVER_BUSY: 'Network busy - retrying...'
};

try {
const result = await broadcastWithMonitoring(signedTransaction, options);
return { success: true, result };
} catch (error) {
const errorCode = error.message.includes('CONTRACT_VALIDATE_ERROR') ? 'CONTRACT_VALIDATE_ERROR' :
error.message.includes('bandwidth') ? 'BANDWIDTH_ERROR' :
error.message.includes('energy') ? 'ENERGY_ERROR' :
error.message.includes('signature') ? 'SIGNATURE_ERROR' :
error.message.includes('expired') ? 'EXPIRED_ERROR' :
error.message.includes('busy') ? 'SERVER_BUSY' : 'UNKNOWN_ERROR';

return {
success: false,
errorCode,
errorMessage: errors[errorCode] || error.message,
retryable: ['SERVER_BUSY', 'BANDWIDTH_ERROR'].includes(errorCode),
originalError: error.message
};
}
}

Performance Tips#

  1. Parallel Processing - Broadcast multiple transactions concurrently with rate limiting
  2. Retry Strategy - Implement exponential backoff for failed broadcasts
  3. Confirmation Polling - Use efficient polling intervals for transaction confirmation
  4. Error Recovery - Handle different error types with appropriate recovery strategies
// Performance-optimized batch broadcaster
class OptimizedBroadcaster {
constructor(apiKey, options = {}) {
this.apiKey = apiKey;
this.maxConcurrency = options.maxConcurrency || 10;
this.rateLimitPerSecond = options.rateLimitPerSecond || 20;
this.queue = [];
this.processing = false;
}

async addToBroadcastQueue(signedTransaction, priority = 'normal') {
return new Promise((resolve, reject) => {
this.queue.push({
transaction: signedTransaction,
priority,
resolve,
reject,
timestamp: Date.now()
});

this.processQueue();
});
}

async processQueue() {
if (this.processing) return;
this.processing = true;

// Sort by priority
this.queue.sort((a, b) => {
const priorities = { high: 3, normal: 2, low: 1 };
return priorities[b.priority] - priorities[a.priority];
});

while (this.queue.length > 0) {
const batch = this.queue.splice(0, this.maxConcurrency);

const promises = batch.map(async (item, index) => {
// Stagger requests to respect rate limits
await new Promise(resolve =>
setTimeout(resolve, (index * 1000) / this.rateLimitPerSecond)
);

try {
const result = await broadcastWithMonitoring(item.transaction);
item.resolve(result);
} catch (error) {
item.reject(error);
}
});

await Promise.allSettled(promises);
}

this.processing = false;
}
}

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