it-healer/laravel-tron 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

it-healer/laravel-tron

Composer 安装命令:

composer require it-healer/laravel-tron

包简介

A library for Laravel that allows you to create and manage the Tron cryptocurrency.

README 文档

README

Logo

Laravel Tron Package

Latest Version Total Downloads License Tests

Laravel Tron is a comprehensive Laravel package for working with the Tron blockchain and TRC-20 tokens. It allows you to generate HD wallets using mnemonic phrases (BIP39/BIP44), validate addresses, check balances and resources, preview and send TRX/TRC-20 tokens. Automate cryptocurrency receiving and withdrawals in your Laravel application with ease.

Table of Contents

Features

Key Features:

  • 🔐 Built-in BIP39/BIP44 Support - No external dependencies for mnemonic generation
  • 💼 HD Wallet Generation - Create hierarchical deterministic wallets
  • 🎯 Multiple Address Support - Generate unlimited addresses from a single seed
  • 💰 TRX & TRC-20 Support - Full support for native TRX and TRC-20 tokens
  • 🔄 Automatic Synchronization - Background sync of transactions and balances
  • 📊 Resource Management - Track bandwidth and energy usage
  • 🎨 Customizable Models - Extend default models to fit your needs
  • 🔔 Webhook Handler - Custom event handling for deposits
  • 🧪 Fully Tested - Comprehensive test suite with 17 tests
  • 🛡️ Secure - Encrypted storage for sensitive data

Requirements

  • PHP: 8.1 or newer
  • Laravel: 10.0 or newer (tested with Laravel 10, 11, and 12)
  • PHP Extensions:
    • ext-gmp - GNU Multiple Precision arithmetic
    • ext-ctype - Character type checking
  • External Services:

Installation

Install the package via Composer:

composer require it-healer/laravel-tron

Run the installer command:

php artisan tron:install

This will publish the configuration file and migrations.

Run the migrations:

php artisan migrate

Laravel 11+ (Automatic Discovery)

The package will be automatically discovered. No additional steps needed!

Laravel 10 (Manual Registration)

For Laravel 10, register the Service Provider and Facade in config/app.php:

'providers' => ServiceProvider::defaultProviders()->merge([
    // ...
    \ItHealer\LaravelTron\TronServiceProvider::class,
])->toArray(),

'aliases' => Facade::defaultAliases()->merge([
    // ...
    'Tron' => \ItHealer\LaravelTron\Facades\Tron::class,
])->toArray(),

Scheduler Setup

For Laravel 10:

Edit app/Console/Kernel.php and add to the schedule() method:

protected function schedule(Schedule $schedule): void
{
    $schedule->command('tron:sync')
        ->everyMinute()
        ->runInBackground();
}

For Laravel 11+:

Add to routes/console.php:

use Illuminate\Support\Facades\Schedule;

Schedule::command('tron:sync')
    ->everyMinute()
    ->runInBackground();

Configuration

After installation, you'll find the configuration file at config/tron.php:

return [
    /*
     * Touch Synchronization System (TSS)
     * Optimize sync by only updating recently touched addresses
     */
    'touch' => [
        'enabled' => false,
        'waiting_seconds' => 3600, // 1 hour
    ],

    /*
     * Webhook handler for deposit events
     */
    'webhook_handler' => \ItHealer\LaravelTron\Handlers\EmptyWebhookHandler::class,

    /*
     * Custom model classes
     */
    'models' => [
        'api' => \ItHealer\LaravelTron\Api\Api::class,
        'node' => \ItHealer\LaravelTron\Models\TronNode::class,
        'wallet' => \ItHealer\LaravelTron\Models\TronWallet::class,
        'address' => \ItHealer\LaravelTron\Models\TronAddress::class,
        'trc20' => \ItHealer\LaravelTron\Models\TronTRC20::class,
        'transaction' => \ItHealer\LaravelTron\Models\TronTransaction::class,
        'deposit' => \ItHealer\LaravelTron\Models\TronDeposit::class,
    ]
];

Custom Webhook Handler

Create a custom webhook handler to process deposit events:

namespace App\Handlers;

use ItHealer\LaravelTron\Handlers\WebhookHandler;
use ItHealer\LaravelTron\Models\TronDeposit;

class CustomWebhookHandler extends WebhookHandler
{
    public function handle(TronDeposit $deposit): void
    {
        // Your custom logic here
        // Send notification, update user balance, etc.
    }
}

Then update config/tron.php:

'webhook_handler' => \App\Handlers\CustomWebhookHandler::class,

Quick Start

1. Register with TronGrid

First, create an account on TronGrid and generate an API key.

2. Create a Tron Node

use ItHealer\LaravelTron\Facades\Tron;

$apiKey = "your-trongrid-api-key";
$node = Tron::createTronGridNode($apiKey, 'MainNet Node');

3. Generate a Wallet

// Generate a new mnemonic phrase (15 words by default)
$mnemonic = Tron::mnemonicGenerate(15);
echo 'Mnemonic: ' . implode(' ', $mnemonic);

// Create wallet from mnemonic
$wallet = Tron::createWallet('My Wallet', $mnemonic);

4. Create an Address

// Primary address is created automatically when wallet is created
// Get the primary address
$address = $wallet->addresses()->first();

// Or create additional addresses
$secondaryAddress = Tron::createAddress($wallet, 'Secondary Address');

echo 'Address: ' . $address->address;

5. Send TRX

$recipientAddress = 'TJCnKsPa7y5okkXvQAidZBzqx3QyQ6sxMW';
$amount = 10; // 10 TRX

$transfer = Tron::transfer($address, $recipientAddress, $amount);

echo 'Transaction ID: ' . $transfer->txid;

Usage

Working with Nodes

Create a Node

use ItHealer\LaravelTron\Facades\Tron;

// Using TronGrid
$node = Tron::createTronGridNode($apiKey, 'Node Name');

// Custom node
$node = Tron::createNode('Node Name', 'https://api.trongrid.io');

Alchemy as RPC node

Alchemy can serve Tron RPC (balances, account resources, triggerconstantcontract, broadcast), but not the TronGrid address-history endpoints (v1/accounts/.../transactions). createAlchemyNode() points RPC at Alchemy and keeps history (and therefore deposit detection) on TronGrid via a separate indexer provider — pass your TronGrid API key for that:

$node = Tron::createAlchemyNode(
    apiKey: 'YOUR_ALCHEMY_KEY',
    name: 'alchemy',
    tronGridApiKey: 'YOUR_TRONGRID_KEY', // used only for v1 history; omit to fall back to Alchemy
);

Under the hood the node stores an optional index_node ({url, headers}); ApiManager routes v1/* requests to it when set, everything else to the RPC node.

Get Node Information

$node = Tron::getNode(); // Get default node
$apiUrl = $node->api_url;
$requestsCount = $node->requests;

Working with Wallets

Generate Wallet

// Generate with default 15 words
$mnemonic = Tron::mnemonicGenerate();

// Generate with custom word count (12, 15, 18, 21, or 24)
$mnemonic = Tron::mnemonicGenerate(24);

// Create wallet
$wallet = Tron::createWallet('Wallet Name', $mnemonic);

Import Existing Wallet

$mnemonic = "your existing twenty four word mnemonic phrase here...";
$wallet = Tron::importWallet('Imported Wallet', $mnemonic);

Wallet with Passphrase

$mnemonic = Tron::mnemonicGenerate();
$passphrase = "super-secret-passphrase";
$wallet = Tron::createWallet('Wallet Name', $mnemonic, $passphrase);

Validate Mnemonic

$isValid = Tron::mnemonicValidate($mnemonic);
if ($isValid) {
    echo "Mnemonic is valid!";
}

Working with Addresses

Create Address

// Create with auto-incremented index
$address = Tron::createAddress($wallet, 'Address Label');

// Create with specific index
$address = Tron::newAddress($wallet, 'Custom Address', $index = 5);

Import Watch-Only Address

$address = Tron::importAddress($wallet, 'TJCnKsPa7y5okkXvQAidZBzqx3QyQ6sxMW');

Validate Address

$isValid = Tron::validateAddress('TJCnKsPa7y5okkXvQAidZBzqx3QyQ6sxMW');

Get Address Balance

$balance = $address->balance; // Balance in TRX
$balanceSun = $address->balance_sun; // Balance in SUN (1 TRX = 1,000,000 SUN)

Get Address Resources

$resources = $address->getResources();
echo "Bandwidth: " . $resources->bandwidth;
echo "Energy: " . $resources->energy;

Working with TRX

Preview Transfer

$preview = Tron::transferPreview($address, $recipientAddress, $amount);

echo "Fee: " . $preview->fee . " TRX";
echo "Total: " . $preview->total . " TRX";

Send TRX

$transfer = Tron::transfer($address, $recipientAddress, $amount);

if ($transfer->success) {
    echo "Transaction sent! TXID: " . $transfer->txid;
} else {
    echo "Transfer failed: " . $transfer->error;
}

Working with TRC-20 Tokens

Register TRC-20 Token

use ItHealer\LaravelTron\Models\TronTRC20;

// USDT TRC-20 contract address
$contractAddress = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t';

$token = TronTRC20::create([
    'contract_address' => $contractAddress,
    'name' => 'Tether USD',
    'symbol' => 'USDT',
    'decimals' => 6,
]);

Get TRC-20 Balance

$balance = $address->getTRC20Balance($token);
echo "USDT Balance: " . $balance;

Preview TRC-20 Transfer

$preview = Tron::transferTRC20Preview($address, $recipientAddress, $amount, $token);

echo "Fee: " . $preview->fee . " TRX";
echo "Energy Required: " . $preview->energy_required;

Send TRC-20 Tokens

$transfer = Tron::transferTRC20($address, $recipientAddress, $amount, $token);

if ($transfer->success) {
    echo "Transaction sent! TXID: " . $transfer->txid;
}

Advanced Usage

Custom Models

Extend the default models to add custom functionality:

namespace App\Models;

use ItHealer\LaravelTron\Models\TronWallet as BaseTronWallet;

class TronWallet extends BaseTronWallet
{
    // Add custom methods or properties
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Update config/tron.php:

'models' => [
    'wallet' => \App\Models\TronWallet::class,
    // ...
],

Touch Synchronization System (TSS) — adaptive sync

For applications with many addresses, enable TSS so addresses are polled often while in use and rarely while idle, instead of every run. An address is "active" for waiting_seconds after its last touch_at; while active it syncs no more often than fast_interval, while idle no more often than slow_interval.

// In config/tron.php
'touch' => [
    'enabled' => true,
    'waiting_seconds' => 1800, // stay "active" 30 min after last touch
    'fast_interval' => 60,     // while active: at most once per 60s
    'slow_interval' => 3600,   // while idle: at most once per hour (null = skip idle entirely)
],

Mark activity by updating touch_at when the wallet is used (GUI view, API call, unlock):

$address->update(['touch_at' => now()]);
// or in bulk for a wallet:
$wallet->addresses()->update(['touch_at' => now()]);

Defaults (fast_interval 0, slow_interval null) preserve the legacy behavior: active addresses sync every run, idle ones are skipped. tron:address-sync --force bypasses the schedule.

Multiple Derivation Paths

The package uses BIP44 standard with the path m/44'/195'/0'/0 for Tron:

// Create addresses with different indexes from the same wallet
$address0 = Tron::createAddress($wallet, 'Address 0', 0);
$address1 = Tron::createAddress($wallet, 'Address 1', 1);
$address2 = Tron::createAddress($wallet, 'Address 2', 2);

Testing

The package includes a comprehensive test suite:

# Run all tests
composer test

# Run with detailed output
vendor/bin/phpunit --testdox

# Run specific test
vendor/bin/phpunit --filter MnemonicTest

Test Coverage:

  • ✅ BIP39 mnemonic generation (12, 15, 24 words)
  • ✅ BIP39 mnemonic validation
  • ✅ Seed generation with/without passphrase
  • ✅ BIP44 address derivation
  • ✅ Private/public key generation
  • ✅ Address generation from private keys
  • ✅ Multiple address generation

See tests/README.md for more details.

Artisan Commands

Synchronization Commands

# Sync everything (all nodes, wallets, addresses)
php artisan tron:sync

# Sync specific node
php artisan tron:sync-node {nodeId}

# Sync specific wallet
php artisan tron:sync-wallet {walletId}

# Sync specific address
php artisan tron:sync-address {addressId}

Creation Commands

# Create a new Tron node
php artisan tron:new-node

# Create a new wallet
php artisan tron:new-wallet

# Generate a new address
php artisan tron:new-address

# Import watch-only address
php artisan tron:import-address

# Register TRC-20 token
php artisan tron:new-trc20

Security

Best Practices

  • 🔐 Never store mnemonics in plain text - Always encrypt sensitive data
  • 🔑 Use strong passphrases - Add an additional layer of security to wallets
  • 🌐 Use HTTPS - Always communicate with Tron nodes over HTTPS
  • 🔒 Secure your database - Encrypt database backups and use strong credentials
  • 👥 Limit access - Restrict who can access wallet operations
  • 📝 Log transactions - Keep audit logs of all cryptocurrency operations
  • 🧪 Test on testnet first - Always test on Shasta testnet before mainnet

Encrypted Storage

The package automatically encrypts sensitive data:

  • Private keys are encrypted using Laravel's encryption
  • Mnemonics are encrypted before storage
  • Passwords are hashed using bcrypt

Reporting Vulnerabilities

If you discover a security vulnerability, please email info@it-healer.com. All security vulnerabilities will be promptly addressed.

Troubleshooting

Common Issues

Issue: "Class 'GMP' not found"

# Install GMP extension
# Ubuntu/Debian
sudo apt-get install php-gmp

# macOS (Homebrew)
brew install gmp

Issue: "Invalid mnemonic phrase"

  • Ensure the mnemonic has the correct number of words (12, 15, 18, 21, or 24)
  • Check for typos in the mnemonic words
  • Verify words are from the BIP39 wordlist

Issue: "Insufficient energy"

  • Freeze TRX to get energy
  • Or use TRX to pay for energy (higher cost)
  • Consider using transferPreview() to estimate costs

Issue: "Node API limit exceeded"

  • TronGrid free tier has rate limits
  • Upgrade to a paid plan on TronGrid
  • Or use your own Tron node

Debug Mode

Enable debug logging in .env:

LOG_LEVEL=debug

Check logs in storage/logs/laravel.log for detailed information.

Changelog

Please see CHANGELOG for more information on what has changed recently.

Custom development & contacts / Заказная разработка и контакты

EN — Need a new project built from scratch, or these modules integrated into your existing application? Contact the developer directly — custom development, module integration and ongoing support are available.

RU — Нужен новый проект «под ключ» или интеграция этих модулей в существующее приложение? Свяжитесь с разработчиком напрямую — доступны заказная разработка, интеграция модулей и поддержка.

Credits

License

The MIT License (MIT). Please see License File for more information.

Made with ❤️ by IT-HEALER

it-healer/laravel-tron 适用场景与选型建议

it-healer/laravel-tron 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 172 次下载、GitHub Stars 达 2, 最近一次更新时间为 2025 年 07 月 23 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「php」 「laravel」 「tron」 「it-healer」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 it-healer/laravel-tron 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 it-healer/laravel-tron 我们能提供哪些服务?
定制开发 / 二次开发

基于 it-healer/laravel-tron 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 172
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 2
  • 点击次数: 24
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 2
  • Watchers: 0
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-07-23