wallet/broadcasthex
Broadcast a signed transaction in hexadecimal format to the TRON network.
Endpoint
POST /wallet/broadcasthex
Parameters
Required Parameters
Parameter | Type | Description |
---|---|---|
transaction | string | Signed transaction in hexadecimal format |
Response
Returns broadcast result including:
result
- Boolean indicating successcode
- Error code if failedmessage
- Error message if failedtxid
- Transaction ID if successful
Important Notes
Transaction Format
- Must be signed: Transaction must be properly signed before broadcasting
- Hex encoded: Entire signed transaction must be hex encoded
- Valid expiration: Transaction must not be expired
- Proper structure: Must follow TRON transaction format
Common Use Cases
- Broadcasting pre-signed transactions
- Offline transaction signing
- Multi-signature transactions
- Hardware wallet integrations
Implementation Examples
- JavaScript
- Python
- cURL
// Broadcast signed transaction hex
const response = await fetch('https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/broadcasthex', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
transaction: '0a85010a0227f02208c89fc99c0f53e5c940c8fbe4f62d5a67080112630a2d747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e5472616e73666572436f6e747261637412320a1541e552f6487911a8245ef73158f8eb5dd3343dc2121541d1e7a6bc354106cb410e65ff8b181c600ff1429218c0843d70f5bce4f62d124138cb1c9a31f44e0e929e44e3f6e4e33a056eb92e4e4c94db2e5892a2834ae0ed8010e1bd7bc5cf5fa100'
}),
});
const result = await response.json();
if (result.result) {
console.log('Transaction broadcast successfully!');
console.log('Transaction ID:', result.txid);
} else {
console.error('Broadcast failed:', result.message);
console.error('Error code:', result.code);
}
// Function to prepare and broadcast transaction
async function broadcastSignedTransaction(signedTxHex) {
try {
const response = await fetch('https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/broadcasthex', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
transaction: signedTxHex
}),
});
const result = await response.json();
if (result.result) {
return {
success: true,
txid: result.txid,
message: 'Transaction broadcast successfully'
};
} else {
return {
success: false,
code: result.code,
message: result.message || 'Unknown error'
};
}
} catch (error) {
return {
success: false,
message: `Network error: ${error.message}`
};
}
}
// Example: Offline signing workflow
async function offlineSigningWorkflow() {
// Step 1: Create transaction offline
const unsignedTx = {
// Transaction details created offline
raw_data: {
contract: [...],
expiration: Date.now() + 60000,
timestamp: Date.now()
}
};
// Step 2: Sign transaction offline (using private key)
// This would typically be done on an air-gapped machine
const signedTx = signTransaction(unsignedTx, privateKey);
// Step 3: Convert to hex
const txHex = Buffer.from(JSON.stringify(signedTx)).toString('hex');
// Step 4: Broadcast online
const result = await broadcastSignedTransaction(txHex);
if (result.success) {
console.log(`Transaction broadcast: ${result.txid}`);
} else {
console.error(`Broadcast failed: ${result.message}`);
}
}
import requests
import json
def broadcast_hex_transaction(hex_transaction, api_key):
"""Broadcast a signed transaction in hex format"""
url = f"https://api-tron-mainnet.n.dwellir.com/{api_key}/wallet/broadcasthex"
payload = {
"transaction": hex_transaction
}
response = requests.post(url, json=payload)
result = response.json()
if result.get('result'):
return {
'success': True,
'txid': result.get('txid'),
'message': 'Transaction broadcast successfully'
}
else:
return {
'success': False,
'code': result.get('code'),
'message': result.get('message', 'Unknown error')
}
# Example usage
def main():
api_key = "YOUR_API_KEY"
# Example signed transaction hex (replace with actual signed tx)
signed_tx_hex = "0a85010a0227f02208c89fc99c0f53e5c940c8fbe4f62d5a67080112630a2d747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e5472616e73666572436f6e747261637412320a1541e552f6487911a8245ef73158f8eb5dd3343dc2121541d1e7a6bc354106cb410e65ff8b181c600ff1429218c0843d70f5bce4f62d124138cb1c9a31f44e0e929e44e3f6e4e33a056eb92e4e4c94db2e5892a2834ae0ed8010e1bd7bc5cf5fa100"
# Broadcast transaction
result = broadcast_hex_transaction(signed_tx_hex, api_key)
if result['success']:
print(f"✅ Transaction broadcast successfully!")
print(f"Transaction ID: {result['txid']}")
else:
print(f"❌ Broadcast failed!")
print(f"Error: {result['message']}")
if result.get('code'):
print(f"Error code: {result['code']}")
# Offline signing example
def offline_signing_example():
"""Example workflow for offline transaction signing"""
# Step 1: Prepare transaction data offline
transaction_data = {
"to": "TRecipientAddress...",
"amount": 1000000, # 1 TRX in SUN
"from": "TSenderAddress..."
}
# Step 2: Create and sign transaction offline
# (This would be done on an air-gapped machine)
# signed_tx = sign_transaction_offline(transaction_data, private_key)
# Step 3: Convert to hex
# tx_hex = signed_tx.hex()
# Step 4: Transfer hex to online machine and broadcast
# result = broadcast_hex_transaction(tx_hex, "YOUR_API_KEY")
print("Offline signing workflow completed")
# Multi-signature example
def multisig_broadcast_example():
"""Example for broadcasting multi-signature transaction"""
api_key = "YOUR_API_KEY"
# After collecting all required signatures offline
fully_signed_tx_hex = "..." # Hex of fully signed multi-sig transaction
result = broadcast_hex_transaction(fully_signed_tx_hex, api_key)
if result['success']:
print(f"Multi-sig transaction broadcast: {result['txid']}")
else:
print(f"Multi-sig broadcast failed: {result['message']}")
if __name__ == "__main__":
main()
# Broadcast signed transaction hex
curl -X POST https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/broadcasthex \
-H "Content-Type: application/json" \
-d '{
"transaction": "0a85010a0227f02208c89fc99c0f53e5c940c8fbe4f62d5a67080112630a2d747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e5472616e73666572436f6e747261637412320a1541e552f6487911a8245ef73158f8eb5dd3343dc2121541d1e7a6bc354106cb410e65ff8b181c600ff1429218c0843d70f5bce4f62d124138cb1c9a31f44e0e929e44e3f6e4e33a056eb92e4e4c94db2e5892a2834ae0ed8010e1bd7bc5cf5fa100"
}'
# Check result with jq
curl -X POST https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/broadcasthex \
-H "Content-Type: application/json" \
-d '{
"transaction": "YOUR_SIGNED_TX_HEX"
}' | jq '.result, .txid, .message'
Example Response
Success Response
{
"result": true,
"txid": "7c2d4206c03a883dd9066d6c839d0deaef32dc5a0d9b15f6d06e506906c90332"
}
Error Response
{
"result": false,
"code": "TRANSACTION_EXPIRATION_ERROR",
"message": "Transaction expired"
}
Error Codes
Code | Description | Solution |
---|---|---|
TRANSACTION_EXPIRATION_ERROR | Transaction has expired | Create new transaction with longer expiration |
DUP_TRANSACTION_ERROR | Transaction already broadcast | Transaction already in mempool or confirmed |
TAPOS_ERROR | Invalid block reference | Update reference block in transaction |
TOO_BIG_TRANSACTION_ERROR | Transaction size too large | Reduce transaction data size |
TRANSACTION_SIGN_ERROR | Invalid signature | Verify signature is correct |
ACCOUNT_NOT_EXIST_ERROR | Account doesn't exist | Ensure account is activated |
NOT_ENOUGH_BANDWIDTH | Insufficient bandwidth | Stake TRX for bandwidth or burn TRX |
NOT_ENOUGH_ENERGY | Insufficient energy | Stake TRX for energy or burn TRX |
Advanced Usage
class TransactionBroadcaster {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = `https://api-tron-mainnet.n.dwellir.com/${apiKey}`;
}
// Broadcast with retry logic
async broadcastWithRetry(hexTx, maxRetries = 3) {
let lastError;
for (let i = 0; i < maxRetries; i++) {
try {
const response = await fetch(`${this.baseUrl}/wallet/broadcasthex`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ transaction: hexTx })
});
const result = await response.json();
if (result.result) {
return {
success: true,
txid: result.txid,
attempts: i + 1
};
}
// Check if error is retryable
if (result.code === 'DUP_TRANSACTION_ERROR') {
// Transaction already broadcast, consider it success
return {
success: true,
message: 'Transaction already broadcast',
attempts: i + 1
};
}
if (result.code === 'TRANSACTION_EXPIRATION_ERROR') {
// Don't retry expired transactions
throw new Error('Transaction expired, cannot retry');
}
lastError = result;
// Wait before retry
await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
} catch (error) {
lastError = error;
}
}
return {
success: false,
error: lastError,
attempts: maxRetries
};
}
// Validate hex transaction before broadcasting
validateHexTransaction(hexTx) {
try {
// Check if valid hex
if (!/^[0-9a-fA-F]+$/.test(hexTx)) {
return { valid: false, error: 'Invalid hex format' };
}
// Check minimum length (rough estimate)
if (hexTx.length < 100) {
return { valid: false, error: 'Transaction too short' };
}
// Check maximum length
if (hexTx.length > 65536 * 2) { // 64KB in hex
return { valid: false, error: 'Transaction too large' };
}
return { valid: true };
} catch (error) {
return { valid: false, error: error.message };
}
}
// Batch broadcast multiple transactions
async batchBroadcast(hexTransactions) {
const results = [];
for (const hexTx of hexTransactions) {
// Validate before broadcasting
const validation = this.validateHexTransaction(hexTx);
if (!validation.valid) {
results.push({
success: false,
error: validation.error
});
continue;
}
// Broadcast with retry
const result = await this.broadcastWithRetry(hexTx);
results.push(result);
// Small delay between broadcasts
await new Promise(resolve => setTimeout(resolve, 100));
}
return results;
}
}
// Example usage
async function advancedBroadcast() {
const broadcaster = new TransactionBroadcaster('YOUR_API_KEY');
// Single transaction with retry
const txHex = 'YOUR_SIGNED_TX_HEX';
const result = await broadcaster.broadcastWithRetry(txHex);
if (result.success) {
console.log(`Transaction broadcast after ${result.attempts} attempts`);
console.log(`TX ID: ${result.txid}`);
} else {
console.error('Broadcast failed:', result.error);
}
// Batch broadcast
const transactions = [
'SIGNED_TX_HEX_1',
'SIGNED_TX_HEX_2',
'SIGNED_TX_HEX_3'
];
const batchResults = await broadcaster.batchBroadcast(transactions);
batchResults.forEach((result, index) => {
if (result.success) {
console.log(`TX ${index + 1}: Success - ${result.txid}`);
} else {
console.log(`TX ${index + 1}: Failed - ${result.error}`);
}
});
}
Best Practices
1. Validation
- Validate hex format before broadcasting
- Check transaction expiration
- Verify sufficient resources
2. Error Handling
- Implement retry logic for network errors
- Handle duplicate transaction errors gracefully
- Log all broadcast attempts
3. Security
- Never expose private keys
- Use secure channels for hex transmission
- Verify transaction details before broadcasting
4. Optimization
- Batch transactions when possible
- Monitor network congestion
- Set appropriate expiration times
Use Cases
- Offline Signing: Sign transactions on air-gapped devices
- Multi-Signature: Collect signatures offline, broadcast online
- Hardware Wallets: Integrate with Ledger, Trezor, etc.
- Transaction Relaying: Relay pre-signed transactions
- Automated Systems: Broadcast pre-prepared transactions
Related Methods
- wallet/broadcasttransaction - Broadcast JSON transaction
- wallet/gettransactionbyid - Check transaction status
- wallet/gettransactioninfobyid - Get transaction receipt