⚠️Blast API (blastapi.io) ends Oct 31. Migrate to Dwellir and skip Alchemy's expensive compute units.
Switch Today →
Skip to main content

wallet/createtransaction

Lightning-Fast Transaction Creation

Dwellir's TRON endpoints create transactions in under 30ms with automatic fee optimization. Build instant payment apps with our optimized transaction creation API.

Get your free API key →

Creates a TRX transfer transaction that can be signed and broadcast to the TRON network. This method generates the transaction object with all necessary parameters.

When to Use This Method

wallet/createtransaction is essential for:

  • TRX Transfers - Send TRX between accounts
  • Payment Processing - Build payment systems and wallets
  • Batch Transactions - Create multiple transfers efficiently
  • Multi-Signature Wallets - Generate transactions for signing
  • Transaction Templates - Pre-build transactions for later execution

Parameters

  1. to_address - string (required)

    • Recipient's TRON address in Base58 format
    • Example: "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN"
  2. owner_address - string (required)

    • Sender's TRON address in Base58 format
    • Example: "TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh"
  3. amount - integer (required)

    • Amount to transfer in SUN (1 TRX = 1,000,000 SUN)
    • Example: 1000000 (1 TRX)
  4. visible - boolean (optional, default: false)

    • true - Use Base58 address format
    • false - Use hex address format
{
"to_address": "TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN",
"owner_address": "TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh",
"amount": 1000000,
"visible": true
}

Returns

Transaction Object containing:

  • txID - Transaction hash identifier
  • raw_data - Transaction data requiring signatures
  • raw_data_hex - Hex encoded transaction data
  • visible - Address format used in response

Implementation Examples

const TRON_API = 'https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY';

// Create a simple TRX transfer transaction
async function createTransaction(fromAddress, toAddress, amount) {
const response = await fetch(`${TRON_API}/wallet/createtransaction`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
to_address: toAddress,
owner_address: fromAddress,
amount: amount, // Amount in SUN
visible: true
})
});

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

return await response.json();
}

// Enhanced transaction creation with validation
async function createTRXTransfer(fromAddress, toAddress, amountTRX) {
try {
// Validate addresses
if (!isValidTronAddress(fromAddress) || !isValidTronAddress(toAddress)) {
throw new Error('Invalid TRON address format');
}

// Convert TRX to SUN
const amountSUN = Math.floor(amountTRX * 1_000_000);

if (amountSUN <= 0) {
throw new Error('Amount must be greater than 0');
}

// Create transaction
const transaction = await createTransaction(fromAddress, toAddress, amountSUN);

// Add metadata
return {
...transaction,
metadata: {
fromAddress,
toAddress,
amountTRX,
amountSUN,
createdAt: Date.now(),
expiresAt: Date.now() + (60 * 60 * 1000) // 1 hour
}
};
} catch (error) {
console.error('Error creating transaction:', error);
throw error;
}
}

// Batch transaction creation
async function createBatchTransactions(fromAddress, transfers) {
const transactions = [];

for (const transfer of transfers) {
try {
const tx = await createTRXTransfer(
fromAddress,
transfer.toAddress,
transfer.amount
);
transactions.push({
success: true,
transaction: tx,
recipient: transfer.toAddress,
amount: transfer.amount
});
} catch (error) {
transactions.push({
success: false,
error: error.message,
recipient: transfer.toAddress,
amount: transfer.amount
});
}
}

return transactions;
}

// Transaction with memo (using smart contract)
async function createTransactionWithMemo(fromAddress, toAddress, amount, memo) {
// For simple transfers with memo, you'd typically use a smart contract
// This example shows the basic transaction creation
const transaction = await createTransaction(fromAddress, toAddress, amount);

// Add memo to transaction metadata (not on-chain for basic transfers)
transaction.memo = memo;
return transaction;
}

// Utility function to validate TRON addresses
function isValidTronAddress(address) {
// Basic validation - starts with T and is 34 characters
return typeof address === 'string' &&
address.startsWith('T') &&
address.length === 34;
}

// Usage examples
(async () => {
try {
// Single transaction
const tx = await createTRXTransfer(
'TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh',
'TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN',
1.5 // 1.5 TRX
);
console.log('Transaction created:', tx.txID);

// Batch transactions
const transfers = [
{ toAddress: 'TRX6Q82wMqWNbCCmJPLz9mR8AZwqvUU2pN', amount: 1 },
{ toAddress: 'TLsV52sRDL79HXGGm9yzwKibb6BeruhUzy', amount: 2 },
{ toAddress: 'TMuA6YqfCeX8EhbfYEg5y7S4DqzSJireY9', amount: 0.5 }
];

const batchTxs = await createBatchTransactions(
'TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh',
transfers
);
console.log('Batch transactions:', batchTxs);

} catch (error) {
console.error('Error:', error);
}
})();

Response Examples

Successful Transaction Creation

{
"visible": true,
"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
},
"raw_data_hex": "0a024a7b2208e15e44aa73bd9e1540d0c7e7e7e7e32d5a68080112640a2d747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e5472616e73666572436f6e747261637412330a15418e9e8b7a4b5c6d3e2f1a0b9c8d7e6f5a4b3c2d1e0f12154142b5e01c8c59a25d78acdbec2bfc7e89e5e86318c0843d70a0b7c6d5e4f3a2b1c0"
}

Error Response (Insufficient Balance)

{
"Error": "balance is not sufficient",
"code": "CONTRACT_VALIDATE_ERROR"
}

Common Use Cases

1. Payment Gateway Integration

class TronPaymentGateway {
constructor(apiKey, merchantAddress) {
this.apiKey = apiKey;
this.merchantAddress = merchantAddress;
this.apiUrl = `https://api-tron-mainnet.n.dwellir.com/${apiKey}`;
}

async createPayment(customerAddress, amountUSD, usdToTrxRate) {
const amountTRX = amountUSD / usdToTrxRate;
const amountSUN = Math.floor(amountTRX * 1_000_000);

const transaction = await this.createTransaction(
customerAddress,
this.merchantAddress,
amountSUN
);

return {
paymentId: transaction.txID,
amountTRX: amountTRX,
amountUSD: amountUSD,
transaction: transaction,
expiresAt: Date.now() + (15 * 60 * 1000) // 15 minutes
};
}

async createTransaction(from, to, amount) {
const response = await fetch(`${this.apiUrl}/wallet/createtransaction`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
to_address: to,
owner_address: from,
amount: amount,
visible: true
})
});

return await response.json();
}
}

2. Wallet-to-Wallet Transfer

async function createWalletTransfer(fromWallet, toWallet, amount, memo = '') {
try {
// Validate inputs
if (!isValidTronAddress(fromWallet) || !isValidTronAddress(toWallet)) {
throw new Error('Invalid wallet address');
}

if (amount <= 0) {
throw new Error('Amount must be positive');
}

// Check sender balance first
const senderAccount = await fetch(`${TRON_API}/wallet/getaccount`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ address: fromWallet, visible: true })
}).then(res => res.json());

const balanceTRX = (senderAccount.balance || 0) / 1_000_000;

if (balanceTRX < amount) {
throw new Error(`Insufficient balance. Have: ${balanceTRX} TRX, Need: ${amount} TRX`);
}

// Create transaction
const transaction = await createTRXTransfer(fromWallet, toWallet, amount);

return {
transaction,
summary: {
from: fromWallet,
to: toWallet,
amount: amount,
fee: 'Free (using bandwidth)',
memo: memo,
requiresSigning: true
}
};
} catch (error) {
throw new Error(`Transfer creation failed: ${error.message}`);
}
}

3. Subscription Payment System

class TronSubscriptionManager {
constructor(apiKey) {
this.apiKey = apiKey;
this.subscriptions = new Map();
}

async createSubscriptionPayment(subscriberAddress, planPrice, planId) {
const subscriptionId = `sub_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

const transaction = await createTRXTransfer(
subscriberAddress,
'TJmmqjb1DK9TTZbQXzRQ2AuA94z4gKAPFh', // Merchant address
planPrice
);

this.subscriptions.set(subscriptionId, {
id: subscriptionId,
planId: planId,
subscriberAddress: subscriberAddress,
amount: planPrice,
transaction: transaction,
status: 'pending',
createdAt: Date.now()
});

return {
subscriptionId,
transaction,
expiresAt: Date.now() + (30 * 60 * 1000) // 30 minutes to pay
};
}

getSubscription(subscriptionId) {
return this.subscriptions.get(subscriptionId);
}
}

4. Multi-Recipient Airdrop

async function createAirdropTransactions(distributorAddress, recipients, amountPerRecipient) {
const results = {
successful: [],
failed: [],
totalRecipients: recipients.length,
totalAmount: recipients.length * amountPerRecipient
};

console.log(`Creating airdrop for ${recipients.length} recipients...`);

for (let i = 0; i < recipients.length; i++) {
const recipient = recipients[i];

try {
const transaction = await createTRXTransfer(
distributorAddress,
recipient,
amountPerRecipient
);

results.successful.push({
recipient: recipient,
transaction: transaction,
amount: amountPerRecipient
});

console.log(`✓ Created transaction ${i + 1}/${recipients.length} for ${recipient}`);

} catch (error) {
results.failed.push({
recipient: recipient,
error: error.message,
amount: amountPerRecipient
});

console.log(`✗ Failed transaction ${i + 1}/${recipients.length} for ${recipient}: ${error.message}`);
}

// Rate limiting - wait 100ms between requests
if (i < recipients.length - 1) {
await new Promise(resolve => setTimeout(resolve, 100));
}
}

return results;
}

Error Handling

Error CodeDescriptionSolution
CONTRACT_VALIDATE_ERRORValidation failedCheck balance, addresses, and amount
BANDWIDTH_ERRORInsufficient bandwidthWait for bandwidth reset or freeze TRX
INVALID_ADDRESSMalformed addressValidate address format
AMOUNT_TOO_SMALLAmount below minimumEnsure amount > 0
async function createTransactionWithRetry(fromAddress, toAddress, amount, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const transaction = await createTransaction(fromAddress, toAddress, amount);
return { success: true, transaction, attempt };
} catch (error) {
console.log(`Attempt ${attempt}/${maxRetries} failed:`, error.message);

if (attempt === maxRetries) {
return {
success: false,
error: error.message,
attempts: attempt,
retryAfter: error.message.includes('bandwidth') ? 86400000 : 5000 // 24h or 5s
};
}

// Exponential backoff
await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000));
}
}
}

Performance Tips

  1. Batch Creation - Create multiple transactions concurrently but respect rate limits
  2. Pre-validation - Check balances and addresses before creating transactions
  3. Caching - Cache account data to avoid repeated balance checks
  4. Error Recovery - Implement retry logic for transient failures
// Rate limited transaction creation
class RateLimitedTransactionBuilder {
constructor(apiKey, requestsPerSecond = 10) {
this.apiKey = apiKey;
this.requestQueue = [];
this.isProcessing = false;
this.requestsPerSecond = requestsPerSecond;
}

async createTransaction(fromAddress, toAddress, amount) {
return new Promise((resolve, reject) => {
this.requestQueue.push({ fromAddress, toAddress, amount, resolve, reject });
this.processQueue();
});
}

async processQueue() {
if (this.isProcessing || this.requestQueue.length === 0) return;

this.isProcessing = true;

while (this.requestQueue.length > 0) {
const request = this.requestQueue.shift();

try {
const result = await createTRXTransfer(
request.fromAddress,
request.toAddress,
request.amount
);
request.resolve(result);
} catch (error) {
request.reject(error);
}

// Rate limiting delay
await new Promise(resolve => setTimeout(resolve, 1000 / this.requestsPerSecond));
}

this.isProcessing = false;
}
}

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