wallet/delegateresource
Delegate staked bandwidth or energy resources to another TRON account.
Endpoint
POST /wallet/delegateresource
Parameters
Required Parameters
Parameter | Type | Description |
---|---|---|
owner_address | string | Account address delegating resources (base58) |
receiver_address | string | Account receiving delegated resources (base58) |
balance | number | Amount to delegate in SUN (1 TRX = 1,000,000 SUN) |
resource | string | Resource type: "BANDWIDTH" or "ENERGY" |
Optional Parameters
Parameter | Type | Description |
---|---|---|
lock | boolean | Lock delegation for 3 days (default: false) |
lock_period | number | Custom lock period in seconds (if lock=true) |
permission_id | number | Permission ID for multi-signature (default: 0) |
visible | boolean | Return base58 addresses (default: false returns hex) |
Response
Returns unsigned transaction containing the delegation operation. Transaction must be signed and broadcast.
Response Fields
txID
- Transaction hashraw_data
- Transaction raw datacontract
- Delegation contract detailsexpiration
- Transaction expiration timestamptimestamp
- Transaction creation timestamp
visible
- Address format indicator
Important Notes
Delegation Rules
- Must Stake First: Resources must be staked before delegation
- Immediate Effect: Delegation takes effect immediately after transaction confirmation
- Lock Period: Optional 3-day lock prevents immediate reclaim
- Resource Ownership: Delegated resources remain owned by delegator
- Reclaim Process: Use
undelegateresource
to reclaim delegated resources
Resource Calculations
- Energy delegation helps with smart contract execution
- Bandwidth delegation helps with transactions and transfers
- Receiver pays no TRX but can use delegated resources
Implementation Examples
- JavaScript
- Python
- cURL
class TronDelegationManager {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = `https://api-tron-mainnet.n.dwellir.com/${apiKey}`;
}
// Create delegation transaction
async delegateResources(ownerAddress, receiverAddress, amountTRX, resourceType, lock = false) {
const response = await fetch(`${this.baseUrl}/wallet/delegateresource`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
owner_address: ownerAddress,
receiver_address: receiverAddress,
balance: amountTRX * 1000000, // Convert TRX to SUN
resource: resourceType,
lock: lock,
lock_period: lock ? 3 * 24 * 3600 : undefined, // 3 days in seconds
visible: true
})
});
if (!response.ok) {
throw new Error(`Delegation failed: ${response.statusText}`);
}
return response.json();
}
// Check delegated resources for an account
async getDelegatedResources(address) {
const response = await fetch(`${this.baseUrl}/wallet/getdelegatedresourceaccountindex`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
value: address,
visible: true
})
});
const data = await response.json();
// Get detailed info for each delegation
const delegations = [];
if (data.toAccounts) {
for (const account of data.toAccounts) {
const detail = await this.getDelegationDetail(address, account);
delegations.push(detail);
}
}
return delegations;
}
// Get detailed delegation info between two accounts
async getDelegationDetail(from, to) {
const response = await fetch(`${this.baseUrl}/wallet/getdelegatedresource`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
fromAddress: from,
toAddress: to,
visible: true
})
});
return response.json();
}
// Calculate optimal delegation based on receiver's needs
async calculateOptimalDelegation(receiverAddress, contractAddress = null) {
// Get receiver's current resources
const resourceResponse = await fetch(`${this.baseUrl}/wallet/getaccountresource`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
address: receiverAddress,
visible: true
})
});
const resources = await resourceResponse.json();
// Estimate energy needs if contract address provided
let energyNeeded = 0;
if (contractAddress) {
const contractResponse = await fetch(`${this.baseUrl}/wallet/triggerconstantcontract`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
owner_address: receiverAddress,
contract_address: contractAddress,
function_selector: 'estimateEnergy()',
visible: true
})
});
const contractData = await contractResponse.json();
energyNeeded = contractData.energy_used || 50000; // Default 50k energy
}
// Calculate delegation amounts
const currentEnergy = resources.EnergyLimit || 0;
const currentBandwidth = resources.NetLimit || 0;
const freeNetUsed = resources.freeNetUsed || 0;
return {
energy: {
current: currentEnergy,
needed: energyNeeded,
delegate: Math.max(0, energyNeeded - currentEnergy),
delegateTRX: Math.ceil((energyNeeded - currentEnergy) / 28.5) // Approximate ratio
},
bandwidth: {
current: currentBandwidth,
dailyUsage: freeNetUsed,
delegate: Math.max(0, 5000 - currentBandwidth), // Aim for 5000 bandwidth
delegateTRX: Math.max(0, 5000 - currentBandwidth) // 1 TRX = 1 bandwidth
}
};
}
// Batch delegate to multiple receivers
async batchDelegate(ownerAddress, delegations) {
const transactions = [];
for (const delegation of delegations) {
const tx = await this.delegateResources(
ownerAddress,
delegation.receiver,
delegation.amount,
delegation.resource,
delegation.lock || false
);
transactions.push({
receiver: delegation.receiver,
resource: delegation.resource,
amount: delegation.amount,
txID: tx.txID,
transaction: tx
});
}
return transactions;
}
}
// Advanced delegation strategies
class DelegationStrategy {
constructor(manager) {
this.manager = manager;
}
// Delegate to DApp users based on usage patterns
async delegateForDApp(ownerAddress, dappUsers) {
const delegations = [];
for (const user of dappUsers) {
// Calculate needs based on historical usage
const optimal = await this.manager.calculateOptimalDelegation(
user.address,
user.primaryContract
);
if (optimal.energy.delegate > 0) {
delegations.push({
receiver: user.address,
resource: 'ENERGY',
amount: optimal.energy.delegateTRX,
lock: true // Lock for stability
});
}
if (optimal.bandwidth.delegate > 0) {
delegations.push({
receiver: user.address,
resource: 'BANDWIDTH',
amount: optimal.bandwidth.delegateTRX,
lock: false // Flexible bandwidth
});
}
}
return this.manager.batchDelegate(ownerAddress, delegations);
}
// Dynamic delegation based on real-time needs
async dynamicDelegation(ownerAddress, receiverAddress, threshold = 0.8) {
const interval = setInterval(async () => {
try {
// Check receiver's resource usage
const resourceResponse = await fetch(
`${this.manager.baseUrl}/wallet/getaccountresource`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
address: receiverAddress,
visible: true
})
}
);
const resources = await resourceResponse.json();
// Check energy usage
const energyUsage = resources.EnergyUsed / resources.EnergyLimit;
if (energyUsage > threshold) {
console.log(`High energy usage detected: ${(energyUsage * 100).toFixed(1)}%`);
// Delegate additional energy
const additionalEnergy = Math.ceil(resources.EnergyLimit * 0.5);
const tx = await this.manager.delegateResources(
ownerAddress,
receiverAddress,
additionalEnergy / 28.5, // Convert to TRX
'ENERGY',
false
);
console.log(`Delegated additional energy: TX ${tx.txID}`);
}
// Check bandwidth usage
const netUsage = resources.NetUsed / resources.NetLimit;
if (netUsage > threshold) {
console.log(`High bandwidth usage detected: ${(netUsage * 100).toFixed(1)}%`);
// Delegate additional bandwidth
const additionalBandwidth = Math.ceil(resources.NetLimit * 0.5);
const tx = await this.manager.delegateResources(
ownerAddress,
receiverAddress,
additionalBandwidth,
'BANDWIDTH',
false
);
console.log(`Delegated additional bandwidth: TX ${tx.txID}`);
}
} catch (error) {
console.error('Dynamic delegation error:', error);
}
}, 60000); // Check every minute
return interval;
}
}
// Example usage
async function manageDelegation() {
const manager = new TronDelegationManager('YOUR_API_KEY');
const strategy = new DelegationStrategy(manager);
try {
// Simple delegation
const simpleTx = await manager.delegateResources(
'TOwnerAddress...',
'TReceiverAddress...',
1000, // 1000 TRX
'ENERGY',
true // Lock for 3 days
);
console.log('Simple delegation TX:', simpleTx.txID);
// Calculate optimal delegation
const optimal = await manager.calculateOptimalDelegation(
'TReceiverAddress...',
'TContractAddress...'
);
console.log('Optimal delegation:', optimal);
// Batch delegation to multiple users
const dappUsers = [
{ address: 'TUser1...', primaryContract: 'TContract1...' },
{ address: 'TUser2...', primaryContract: 'TContract2...' }
];
const batchTxs = await strategy.delegateForDApp('TOwnerAddress...', dappUsers);
console.log('Batch delegations:', batchTxs);
// Start dynamic delegation monitoring
const monitor = await strategy.dynamicDelegation(
'TOwnerAddress...',
'TReceiverAddress...',
0.75 // Trigger at 75% usage
);
console.log('Dynamic delegation monitor started');
} catch (error) {
console.error('Delegation error:', error);
}
}
import requests
import json
import time
from typing import Dict, List, Optional, Tuple
from dataclasses import dataclass
@dataclass
class DelegationConfig:
receiver: str
amount_trx: float
resource: str
lock: bool = False
lock_period: Optional[int] = None
class TronDelegationManager:
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = f"https://api-tron-mainnet.n.dwellir.com/{api_key}"
def delegate_resources(
self,
owner_address: str,
receiver_address: str,
amount_trx: float,
resource: str,
lock: bool = False,
lock_period: Optional[int] = None
) -> Dict:
"""Create a resource delegation transaction"""
payload = {
"owner_address": owner_address,
"receiver_address": receiver_address,
"balance": int(amount_trx * 1_000_000), # Convert to SUN
"resource": resource,
"lock": lock,
"visible": True
}
if lock and lock_period:
payload["lock_period"] = lock_period
elif lock:
payload["lock_period"] = 3 * 24 * 3600 # Default 3 days
response = requests.post(
f"{self.base_url}/wallet/delegateresource",
json=payload
)
response.raise_for_status()
return response.json()
def get_delegation_index(self, address: str) -> Dict:
"""Get delegation index for an account"""
response = requests.post(
f"{self.base_url}/wallet/getdelegatedresourceaccountindex",
json={
"value": address,
"visible": True
}
)
response.raise_for_status()
return response.json()
def get_delegation_detail(
self,
from_address: str,
to_address: str
) -> Dict:
"""Get detailed delegation between two accounts"""
response = requests.post(
f"{self.base_url}/wallet/getdelegatedresource",
json={
"fromAddress": from_address,
"toAddress": to_address,
"visible": True
}
)
response.raise_for_status()
return response.json()
def analyze_delegation_needs(
self,
receiver_address: str,
days: int = 1
) -> Dict:
"""Analyze resource needs for optimal delegation"""
# Get account resource info
response = requests.post(
f"{self.base_url}/wallet/getaccountresource",
json={
"address": receiver_address,
"visible": True
}
)
response.raise_for_status()
resources = response.json()
# Calculate daily needs
energy_limit = resources.get('EnergyLimit', 0)
energy_used = resources.get('EnergyUsed', 0)
net_limit = resources.get('NetLimit', 0)
net_used = resources.get('NetUsed', 0)
# Estimate required delegation
energy_deficit = max(0, energy_used * days - energy_limit)
bandwidth_deficit = max(0, net_used * days - net_limit)
return {
'energy': {
'current_limit': energy_limit,
'daily_usage': energy_used,
'deficit': energy_deficit,
'recommended_delegation_trx': energy_deficit / 28.5 if energy_deficit > 0 else 0
},
'bandwidth': {
'current_limit': net_limit,
'daily_usage': net_used,
'deficit': bandwidth_deficit,
'recommended_delegation_trx': bandwidth_deficit if bandwidth_deficit > 0 else 0
}
}
def batch_delegate(
self,
owner_address: str,
delegations: List[DelegationConfig]
) -> List[Dict]:
"""Execute multiple delegations"""
results = []
for config in delegations:
try:
tx = self.delegate_resources(
owner_address,
config.receiver,
config.amount_trx,
config.resource,
config.lock,
config.lock_period
)
results.append({
'success': True,
'receiver': config.receiver,
'resource': config.resource,
'amount_trx': config.amount_trx,
'txID': tx['txID'],
'transaction': tx
})
except Exception as e:
results.append({
'success': False,
'receiver': config.receiver,
'resource': config.resource,
'error': str(e)
})
return results
class SmartDelegationStrategy:
"""Advanced delegation strategies for different use cases"""
def __init__(self, manager: TronDelegationManager):
self.manager = manager
def delegate_for_gaming(
self,
owner_address: str,
player_addresses: List[str]
) -> List[Dict]:
"""Optimized delegation for gaming DApps"""
delegations = []
for player in player_addresses:
# Gaming typically needs more energy for contracts
delegations.append(DelegationConfig(
receiver=player,
amount_trx=5000, # ~142,500 energy
resource='ENERGY',
lock=True # Lock for stable gameplay
))
# Moderate bandwidth for transactions
delegations.append(DelegationConfig(
receiver=player,
amount_trx=1000, # 1000 bandwidth
resource='BANDWIDTH',
lock=False
))
return self.manager.batch_delegate(owner_address, delegations)
def delegate_for_defi(
self,
owner_address: str,
trader_addresses: List[str]
) -> List[Dict]:
"""Optimized delegation for DeFi trading"""
delegations = []
for trader in trader_addresses:
# DeFi needs high energy for swaps/liquidity
delegations.append(DelegationConfig(
receiver=trader,
amount_trx=10000, # ~285,000 energy
resource='ENERGY',
lock=False # Flexible for trading
))
# High bandwidth for frequent transactions
delegations.append(DelegationConfig(
receiver=trader,
amount_trx=2000, # 2000 bandwidth
resource='BANDWIDTH',
lock=False
))
return self.manager.batch_delegate(owner_address, delegations)
def progressive_delegation(
self,
owner_address: str,
receiver_address: str,
initial_amount: float,
increment: float,
max_amount: float
) -> None:
"""Progressive delegation based on usage"""
current_delegation = initial_amount
while current_delegation <= max_amount:
# Check current usage
analysis = self.manager.analyze_delegation_needs(receiver_address)
# Delegate if needed
if analysis['energy']['deficit'] > 0:
tx = self.manager.delegate_resources(
owner_address,
receiver_address,
current_delegation,
'ENERGY',
lock=False
)
print(f"Delegated {current_delegation} TRX for energy: {tx['txID']}")
# Increase for next iteration
current_delegation += increment
# Wait before checking again
time.sleep(3600) # 1 hour
else:
print("No additional delegation needed")
time.sleep(3600)
# Example usage
def main():
manager = TronDelegationManager('YOUR_API_KEY')
strategy = SmartDelegationStrategy(manager)
# 1. Simple delegation
print("=== Simple Delegation ===")
simple_tx = manager.delegate_resources(
'TOwnerAddress...',
'TReceiverAddress...',
1000, # 1000 TRX
'ENERGY',
lock=True
)
print(f"Transaction ID: {simple_tx['txID']}")
# 2. Analyze delegation needs
print("\n=== Delegation Analysis ===")
analysis = manager.analyze_delegation_needs('TReceiverAddress...', days=7)
print(f"Energy needs: {analysis['energy']['recommended_delegation_trx']:.2f} TRX")
print(f"Bandwidth needs: {analysis['bandwidth']['recommended_delegation_trx']:.2f} TRX")
# 3. Batch delegation for gaming
print("\n=== Gaming Delegation ===")
gaming_results = strategy.delegate_for_gaming(
'TOwnerAddress...',
['TPlayer1...', 'TPlayer2...', 'TPlayer3...']
)
for result in gaming_results:
if result['success']:
print(f"✓ {result['receiver']}: {result['resource']} - TX: {result['txID'][:8]}...")
else:
print(f"✗ {result['receiver']}: {result['error']}")
# 4. Check existing delegations
print("\n=== Existing Delegations ===")
index = manager.get_delegation_index('TOwnerAddress...')
if index.get('toAccounts'):
for account in index['toAccounts']:
detail = manager.get_delegation_detail('TOwnerAddress...', account)
print(f"To {account}:")
for delegation in detail.get('delegatedResource', []):
print(f" - {delegation['frozen_balance_for_energy']/1_000_000:.2f} TRX for ENERGY")
print(f" - {delegation['frozen_balance_for_bandwidth']/1_000_000:.2f} TRX for BANDWIDTH")
if __name__ == "__main__":
main()
# Basic energy delegation
curl -X POST https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/delegateresource \
-H "Content-Type: application/json" \
-d '{
"owner_address": "TOwnerAddress...",
"receiver_address": "TReceiverAddress...",
"balance": 1000000000,
"resource": "ENERGY",
"visible": true
}'
# Delegate bandwidth with 3-day lock
curl -X POST https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/delegateresource \
-H "Content-Type: application/json" \
-d '{
"owner_address": "TOwnerAddress...",
"receiver_address": "TReceiverAddress...",
"balance": 500000000,
"resource": "BANDWIDTH",
"lock": true,
"lock_period": 259200,
"visible": true
}'
# Check delegation index
curl -X POST https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getdelegatedresourceaccountindex \
-H "Content-Type: application/json" \
-d '{
"value": "TOwnerAddress...",
"visible": true
}'
# Get delegation details between accounts
curl -X POST https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getdelegatedresource \
-H "Content-Type: application/json" \
-d '{
"fromAddress": "TOwnerAddress...",
"toAddress": "TReceiverAddress...",
"visible": true
}'
Example Response
{
"visible": true,
"txID": "d8f3c4b9e2a7d6c5e4f3b2a1d9c8e7f6b5a4d3c2e1f9a8b7c6d5e4f3a2b1c9e",
"raw_data": {
"contract": [
{
"parameter": {
"value": {
"owner_address": "TOwnerAddress...",
"receiver_address": "TReceiverAddress...",
"balance": 1000000000,
"resource": "ENERGY",
"lock": true,
"lock_period": 259200
},
"type_url": "type.googleapis.com/protocol.DelegateResourceContract"
},
"type": "DelegateResourceContract"
}
],
"ref_block_bytes": "6b5c",
"ref_block_hash": "4d3e5f9a8b7c6d5e",
"expiration": 1702456849000,
"timestamp": 1702456789000
}
}
Delegation Flow
graph LR
A[Owner Stakes TRX] --> B[Resources Available]
B --> C[Delegate to Receiver]
C --> D[Receiver Uses Resources]
D --> E[Resources Consumed]
E --> F[Owner Can Reclaim]
style A fill:#4CAF50
style C fill:#2196F3
style D fill:#FF9800
Best Practices
1. Calculate Before Delegating
// Always analyze needs first
const needs = await analyzeNeeds(receiverAddress);
const delegateAmount = Math.ceil(needs.energy.deficit / 28.5);
2. Use Locks Strategically
- Lock for stable, long-term delegations
- Keep unlocked for flexible, short-term needs
- Consider 3-day default lock period
3. Monitor Resource Usage
- Track receiver's consumption patterns
- Adjust delegations based on actual usage
- Implement alerts for high usage
4. Batch Operations
- Group multiple delegations together
- Reduces transaction overhead
- Easier management and tracking
Common Errors
Error | Description | Solution |
---|---|---|
Insufficient staked balance | Not enough staked resources | Stake more TRX first |
Invalid resource type | Must be BANDWIDTH or ENERGY | Use correct resource string |
Receiver address invalid | Malformed receiver address | Verify base58 format |
Already delegated | Resources already delegated to receiver | Check existing delegations |
Use Cases
- DApp Support: Provide resources for users to interact with your DApp
- Gaming: Enable free gameplay by covering resource costs
- DeFi Trading: Support traders with energy for smart contract calls
- Onboarding: Help new users get started without staking
- Resource Rental: Commercial resource delegation services
Related Methods
- wallet/undelegateresource - Reclaim delegated resources
- wallet/freezebalancev2 - Stake TRX for resources
- wallet/getaccountresource - View resource limits