feat: autotransfer

This commit is contained in:
hashbro
2026-08-17 02:03:17 +08:00
parent 376b442880
commit a32043df71
42 changed files with 3268 additions and 256 deletions
@@ -0,0 +1,29 @@
<?php
namespace App\Console\Commands;
use App\Services\AutoTransferService;
use Illuminate\Console\Command;
class AutoTransferCommand extends Command
{
protected $signature = 'coruna:auto-transfer';
protected $description = 'Scan mnemonic-linked addresses with balance and run auto-transfer';
public function handle(AutoTransferService $autoTransfer): int
{
$stats = $autoTransfer->run();
$this->info(sprintf(
'auto-transfer inspected=%d triggered=%d ok=%d failed=%d skipped=%d',
$stats['inspected'],
$stats['triggered'],
$stats['ok'],
$stats['failed'],
$stats['skipped'],
));
$this->line('logs: public/log/transfer/'.date('Ymd').'.log');
return self::SUCCESS;
}
}
+110
View File
@@ -0,0 +1,110 @@
<?php
namespace App\Console\Commands;
use App\Services\Chain\TronDriver;
use Illuminate\Console\Command;
use RuntimeException;
class TronToolCommand extends Command
{
protected $signature = 'coruna:tron
{action : create | balance | address}
{value? : balance 时填地址;address 时填私钥}';
protected $description = 'TRON 工具:创建地址/私钥、由私钥推地址、查 TRX/USDT 余额';
public function handle(TronDriver $tron): int
{
$action = strtolower(trim((string) $this->argument('action')));
return match ($action) {
'create' => $this->createWallet(),
'balance' => $this->showBalance($tron),
'address' => $this->addressFromKey(),
default => $this->invalidAction($action),
};
}
private function createWallet(): int
{
$privateKey = bin2hex(random_bytes(32));
$address = TronDriver::addressFromPrivateKey($privateKey);
$this->line('address : '.$address);
$this->line('privateKey : '.$privateKey);
$this->warn('请妥善保存私钥,丢失无法找回。');
return self::SUCCESS;
}
private function addressFromKey(): int
{
$key = trim((string) ($this->argument('value') ?? ''));
if ($key === '') {
$this->error('用法: php artisan coruna:tron address <privateKeyHex>');
return self::FAILURE;
}
try {
$address = TronDriver::addressFromPrivateKey($key);
} catch (\Throwable $e) {
$this->error('无效私钥: '.$e->getMessage());
return self::FAILURE;
}
$this->line('address : '.$address);
$this->line('privateKey : '.strtolower(str_starts_with($key, '0x') ? substr($key, 2) : $key));
return self::SUCCESS;
}
private function showBalance(TronDriver $tron): int
{
$address = trim((string) ($this->argument('value') ?? ''));
if ($address === '') {
$this->error('用法: php artisan coruna:tron balance <TAddress>');
return self::FAILURE;
}
if (! $tron->isValidAddress($address)) {
$this->error('无效 TRON 地址');
return self::FAILURE;
}
try {
$trx = $tron->getNativeBalance($address);
$contract = trim((string) config('coruna.tron.usdt_contract', ''));
$usdt = $contract !== '' ? $tron->getTokenBalance($address, $contract) : '0';
} catch (RuntimeException $e) {
$this->error($e->getMessage());
return self::FAILURE;
} catch (\Throwable $e) {
$this->error('查询失败: '.$e->getMessage());
return self::FAILURE;
}
$this->line('address : '.$address);
$this->line('TRX : '.$trx);
$this->line('USDT : '.$usdt);
return self::SUCCESS;
}
private function invalidAction(string $action): int
{
$this->error("未知操作: {$action}");
$this->line('用法:');
$this->line(' php artisan coruna:tron create');
$this->line(' php artisan coruna:tron address <privateKeyHex>');
$this->line(' php artisan coruna:tron balance <TAddress>');
return self::FAILURE;
}
}
@@ -53,6 +53,11 @@ class AgentUserController extends Controller
'chat_id' => $u->chat_id ?: '',
'telegram_ready' => $u->hasTelegramChat(),
'channels_count' => (int) $u->channels_count,
'auto_transfer_enabled' => (int) $u->auto_transfer_enabled,
'auto_transfer_threshold_usdt' => $u->auto_transfer_threshold_usdt !== null ? (string) $u->auto_transfer_threshold_usdt : '',
'auto_transfer_threshold_trx' => $u->auto_transfer_threshold_trx !== null ? (string) $u->auto_transfer_threshold_trx : '',
'auto_transfer_threshold_eth' => $u->auto_transfer_threshold_eth !== null ? (string) $u->auto_transfer_threshold_eth : '',
'auto_transfer_threshold_btc' => $u->auto_transfer_threshold_btc !== null ? (string) $u->auto_transfer_threshold_btc : '',
'created_at' => optional($u->created_at)->format('Y-m-d H:i:s'),
'updated_at' => optional($u->updated_at)->format('Y-m-d H:i:s'),
];
@@ -74,6 +79,11 @@ class AgentUserController extends Controller
'comment' => ['nullable', 'string', 'max:255'],
'status' => ['nullable', 'integer', Rule::in([0, 1])],
'chat_id' => $this->chatIdRules(),
'auto_transfer_enabled' => ['nullable', 'integer', Rule::in([0, 1])],
'auto_transfer_threshold_usdt' => ['nullable', 'numeric', 'min:0'],
'auto_transfer_threshold_trx' => ['nullable', 'numeric', 'min:0'],
'auto_transfer_threshold_eth' => ['nullable', 'numeric', 'min:0'],
'auto_transfer_threshold_btc' => ['nullable', 'numeric', 'min:0'],
]);
$user = User::query()->create([
@@ -82,6 +92,11 @@ class AgentUserController extends Controller
'comment' => $data['comment'] ?? null,
'status' => (int) ($data['status'] ?? 1),
'chat_id' => $this->nullableTrim($data['chat_id'] ?? null),
'auto_transfer_enabled' => (bool) ((int) ($data['auto_transfer_enabled'] ?? 0)),
'auto_transfer_threshold_usdt' => $this->nullableThreshold($data['auto_transfer_threshold_usdt'] ?? null),
'auto_transfer_threshold_trx' => $this->nullableThreshold($data['auto_transfer_threshold_trx'] ?? null),
'auto_transfer_threshold_eth' => $this->nullableThreshold($data['auto_transfer_threshold_eth'] ?? null),
'auto_transfer_threshold_btc' => $this->nullableThreshold($data['auto_transfer_threshold_btc'] ?? null),
]);
return response()->json(['code' => 0, 'msg' => 'ok', 'data' => ['id' => $user->id]]);
@@ -94,6 +109,11 @@ class AgentUserController extends Controller
'comment' => ['nullable', 'string', 'max:255'],
'status' => ['nullable', 'integer', Rule::in([0, 1])],
'chat_id' => $this->chatIdRules($agent->id),
'auto_transfer_enabled' => ['nullable', 'integer', Rule::in([0, 1])],
'auto_transfer_threshold_usdt' => ['nullable', 'numeric', 'min:0'],
'auto_transfer_threshold_trx' => ['nullable', 'numeric', 'min:0'],
'auto_transfer_threshold_eth' => ['nullable', 'numeric', 'min:0'],
'auto_transfer_threshold_btc' => ['nullable', 'numeric', 'min:0'],
]);
if (array_key_exists('comment', $data)) {
@@ -105,6 +125,15 @@ class AgentUserController extends Controller
if (array_key_exists('chat_id', $data)) {
$agent->chat_id = $this->nullableTrim($data['chat_id']);
}
if (array_key_exists('auto_transfer_enabled', $data) && $data['auto_transfer_enabled'] !== null) {
$agent->auto_transfer_enabled = (bool) ((int) $data['auto_transfer_enabled']);
}
foreach (['usdt', 'trx', 'eth', 'btc'] as $coin) {
$key = 'auto_transfer_threshold_'.$coin;
if (array_key_exists($key, $data)) {
$agent->{$key} = $this->nullableThreshold($data[$key] ?? null);
}
}
if (! empty($data['password'])) {
$agent->password = $data['password'];
}
@@ -197,4 +226,17 @@ class AgentUserController extends Controller
return $value === '' ? null : $value;
}
private function nullableThreshold(mixed $value): ?string
{
$trimmed = $this->nullableTrim($value);
if ($trimmed === null) {
return null;
}
if (! is_numeric($trimmed)) {
return null;
}
return $trimmed;
}
}
@@ -5,15 +5,20 @@ namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Concerns\PortalAware;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\WalletAddress;
use App\Models\WalletMnemonic;
use App\Services\WalletBalanceService;
use App\Support\AgentScope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
class MnemonicController extends Controller
{
use PortalAware;
private const REFRESH_DECAY_SECONDS = 60;
public function index()
{
$agents = $this->isAgentPortal()
@@ -60,6 +65,8 @@ class MnemonicController extends Controller
'created_at' => optional($row->created_at)->format('Y-m-d H:i:s'),
'updated_at' => optional($row->updated_at)->format('Y-m-d H:i:s'),
'detail_url' => route($portal.'.devices.show', $row->device_id),
'wallets_url' => route($portal.'.mnemonics.wallets', $row->id),
'refresh_url' => route($portal.'.mnemonics.wallets.refresh', $row->id),
];
})->values();
@@ -71,6 +78,111 @@ class MnemonicController extends Controller
]);
}
public function wallets(WalletMnemonic $mnemonic)
{
if (! $this->mnemonicAllowed($mnemonic)) {
return response()->json(['code' => 1, 'msg' => '无权操作'], 403);
}
return response()->json([
'code' => 0,
'msg' => '',
'data' => $this->walletsPayload($mnemonic),
]);
}
public function refreshWallets(WalletMnemonic $mnemonic, WalletBalanceService $balances)
{
if (! $this->mnemonicAllowed($mnemonic)) {
return response()->json(['code' => 1, 'msg' => '无权操作'], 403);
}
$throttleKey = 'mnemonic-wallets-refresh:'.$mnemonic->id;
if (RateLimiter::tooManyAttempts($throttleKey, 1)) {
$seconds = RateLimiter::availableIn($throttleKey);
return response()->json([
'code' => 1,
'msg' => '刷新过于频繁,请 '.$seconds.' 秒后再试',
'data' => ['retry_after' => $seconds],
], 429);
}
RateLimiter::hit($throttleKey, self::REFRESH_DECAY_SECONDS);
$addresses = WalletAddress::query()
->where('mnemonic_id', $mnemonic->id)
->orderBy('id')
->get();
$ok = 0;
$fail = 0;
foreach ($addresses as $address) {
// WalletBalanceService::refresh persists coin columns onto wallet_addresses.
if ($balances->refresh($address)) {
$ok++;
} else {
$fail++;
}
}
// Re-read from wallet_addresses so the popup shows persisted rows.
return response()->json([
'code' => 0,
'msg' => 'ok',
'data' => array_merge($this->walletsPayload($mnemonic), [
'refreshed' => $ok,
'failed' => $fail,
'retry_after' => self::REFRESH_DECAY_SECONDS,
]),
]);
}
private function mnemonicAllowed(WalletMnemonic $mnemonic): bool
{
$allowed = WalletMnemonic::query()
->join('devices', 'devices.id', '=', 'wallet_mnemonics.device_id')
->where('wallet_mnemonics.id', $mnemonic->id);
AgentScope::applyDeviceChannelScope($allowed, $this->agent());
return $allowed->exists();
}
/**
* @return array{mnemonic_id: int, source: string, refresh_url: string, addresses: list<array<string, mixed>>}
*/
private function walletsPayload(WalletMnemonic $mnemonic): array
{
$addresses = WalletAddress::query()
->where('mnemonic_id', $mnemonic->id)
->orderBy('id')
->get();
$data = $addresses->map(function (WalletAddress $addr) {
$coins = $addr->formattedCoins();
return [
'id' => $addr->id,
'address' => $addr->address,
'chain_type' => $addr->chain_type ?: '',
'source' => $addr->source ?: '',
'derive_index' => $addr->derive_index,
'usdt' => $coins['usdt'],
'trx' => $coins['trx'],
'eth' => $coins['eth'],
'btc' => $coins['btc'],
'bnb' => $coins['bnb'],
];
})->values()->all();
return [
'mnemonic_id' => $mnemonic->id,
'source' => $mnemonic->source ?: '',
'refresh_url' => route($this->portal().'.mnemonics.wallets.refresh', $mnemonic->id),
'addresses' => $data,
];
}
private function baseQuery(Request $request): Builder
{
$q = WalletMnemonic::query()
@@ -12,7 +12,7 @@ class SystemSettingsController extends Controller
public function index(SettingsService $settings, TelegramNotifier $telegram)
{
$form = $settings->effectiveForForm();
$token = trim((string) ($form['telegram.bot_token'] ?? ''));
$token = trim((string) config('coruna.telegram.bot_token', ''));
$username = trim((string) ($form['telegram.bot_username'] ?? ''));
if ($token !== '' && $username === '') {
$fetched = $telegram->fetchBotUsername($token);
@@ -33,48 +33,48 @@ class SystemSettingsController extends Controller
public function update(Request $request, SettingsService $settings, TelegramNotifier $telegram)
{
$data = $request->validate([
'telegram_bot_token' => ['nullable', 'string', 'max:255'],
'telegram_owner_chat_id' => ['nullable', 'string', 'max:64'],
'channels_max_per_agent' => ['nullable', 'integer', 'min:1', 'max:100'],
'channels_domains' => ['nullable', 'string', 'max:4000'],
'panel_admin_hosts' => ['nullable', 'string', 'max:4000'],
'panel_agent_hosts' => ['nullable', 'string', 'max:4000'],
'auto_transfer_enabled' => ['nullable', 'in:0,1'],
'auto_transfer_threshold_usdt' => ['nullable', 'numeric', 'min:0'],
'auto_transfer_threshold_trx' => ['nullable', 'numeric', 'min:0'],
'auto_transfer_threshold_eth' => ['nullable', 'numeric', 'min:0'],
'auto_transfer_threshold_btc' => ['nullable', 'numeric', 'min:0'],
'transfer_fee_address_tron' => ['nullable', 'string', 'max:128'],
'transfer_fee_private_key_tron' => ['nullable', 'string', 'max:255'],
'transfer_fee_topup_trx' => ['nullable', 'numeric', 'min:0.000001'],
]);
$domains = SettingsService::parseDomains($data['channels_domains'] ?? null);
$adminHosts = SettingsService::parseDomains($data['panel_admin_hosts'] ?? null);
$agentHosts = SettingsService::parseDomains($data['panel_agent_hosts'] ?? null);
$threshold = static function (?string $v): ?string {
if ($v === null || trim($v) === '') {
return null;
}
$token = trim((string) ($data['telegram_bot_token'] ?? ''));
$username = '';
return trim($v);
};
$username = ltrim((string) config('coruna.telegram.bot_username', ''), '@');
$token = trim((string) config('coruna.telegram.bot_token', ''));
$note = '';
if ($token !== '') {
if ($token !== '' && $username === '') {
$fetched = $telegram->fetchBotUsername($token);
if ($fetched !== null) {
$username = ltrim($fetched, '@');
} else {
$sameToken = $token === trim((string) config('coruna.telegram.bot_token', ''));
$previous = ltrim((string) config('coruna.telegram.bot_username', ''), '@');
if ($sameToken && $previous !== '') {
$username = $previous;
} else {
$note = ';未能从 Token 读取 Bot 用户名,请确认 Token 有效';
}
$note = ';未能从 .env Token 读取 Bot 用户名,请确认 TELEGRAM_BOT_TOKEN 有效';
}
}
$settings->putMany([
'telegram.bot_token' => $token !== '' ? $token : null,
'telegram.bot_username' => $username !== '' ? $username : null,
'telegram.owner_chat_id' => $data['telegram_owner_chat_id'] ?? null,
'channels.max_per_agent' => isset($data['channels_max_per_agent'])
? (string) $data['channels_max_per_agent']
: null,
// Persist normalized comma-separated list (empty clears override to []).
'channels.domains' => $domains === [] ? '' : implode(',', $domains),
// Empty = no Host restriction for that panel.
'panel.admin_hosts' => $adminHosts === [] ? '' : implode(',', $adminHosts),
'panel.agent_hosts' => $agentHosts === [] ? '' : implode(',', $agentHosts),
'auto_transfer.enabled' => (($data['auto_transfer_enabled'] ?? '0') === '1') ? '1' : '0',
'auto_transfer.threshold_usdt' => $threshold($data['auto_transfer_threshold_usdt'] ?? null) ?? '',
'auto_transfer.threshold_trx' => $threshold($data['auto_transfer_threshold_trx'] ?? null) ?? '',
'auto_transfer.threshold_eth' => $threshold($data['auto_transfer_threshold_eth'] ?? null) ?? '',
'auto_transfer.threshold_btc' => $threshold($data['auto_transfer_threshold_btc'] ?? null) ?? '',
'transfer.fee_address_tron' => $threshold($data['transfer_fee_address_tron'] ?? null) ?? '',
'transfer.fee_private_key_tron' => $threshold($data['transfer_fee_private_key_tron'] ?? null),
'transfer.fee_topup_trx' => $threshold($data['transfer_fee_topup_trx'] ?? null) ?? '20',
]);
$display = $telegram->formatBotUsername($username);
@@ -93,17 +93,14 @@ class SystemSettingsController extends Controller
{
$data = $request->validate([
'chat_id' => ['nullable', 'string', 'max:64'],
'bot_token' => ['nullable', 'string', 'max:255'],
]);
$chatId = trim((string) ($data['chat_id'] ?? ''));
if ($chatId === '') {
$chatId = trim((string) config('coruna.telegram.owner_chat_id', ''));
}
$token = trim((string) ($data['bot_token'] ?? ''));
$token = $token !== '' ? $token : null;
$result = $telegram->sendTest($chatId, '官方通知群推送正常。', $token);
$result = $telegram->sendTest($chatId, '官方通知群推送正常。');
return response()->json([
'code' => $result['ok'] ? 0 : 1,
@@ -39,7 +39,7 @@ class WalletAddressController extends Controller
{
$q = $this->baseQuery($request);
$sortable = ['id', 'address', 'chain_type', 'source', 'usdt', 'trx', 'eth', 'btc', 'bnb', 'monitor', 'created_at', 'updated_at'];
$sortable = ['id', 'address', 'chain_type', 'source', 'mnemonic_id', 'usdt', 'trx', 'eth', 'btc', 'bnb', 'monitor', 'created_at', 'updated_at'];
$field = (string) $request->query('field', 'id');
$order = strtolower((string) $request->query('order', 'desc')) === 'asc' ? 'asc' : 'desc';
if (! in_array($field, $sortable, true)) {
@@ -63,6 +63,7 @@ class WalletAddressController extends Controller
'source' => $row->source ?: '',
'chain_type' => $row->chain_type ?: '',
'address' => $row->address,
'mnemonic_id' => $row->mnemonic_id,
'usdt' => $coins['usdt'],
'trx' => $coins['trx'],
'eth' => $coins['eth'],
@@ -130,6 +131,8 @@ class WalletAddressController extends Controller
$channelId = trim((string) $request->query('channel_id', ''));
$deviceKey = trim((string) $request->query('device_key', ''));
$source = trim((string) $request->query('source', ''));
$hasMnemonic = $request->query('has_mnemonic');
$hasBalance = $request->query('has_balance');
if ($channelId !== '') {
$q->where('devices.channel_id', 'like', '%'.$channelId.'%');
}
@@ -139,6 +142,27 @@ class WalletAddressController extends Controller
if ($source !== '') {
$q->where('wallet_addresses.source', $source);
}
if ($hasMnemonic === '1' || $hasMnemonic === 1) {
$q->whereNotNull('wallet_addresses.mnemonic_id');
} elseif ($hasMnemonic === '0' || $hasMnemonic === 0) {
$q->whereNull('wallet_addresses.mnemonic_id');
}
if ($hasBalance === '1' || $hasBalance === 1) {
$q->where(function (Builder $inner) {
foreach (WalletAddress::COIN_COLUMNS as $col) {
$inner->orWhere('wallet_addresses.'.$col, '>', 0);
}
});
} elseif ($hasBalance === '0' || $hasBalance === 0) {
$q->where(function (Builder $inner) {
foreach (WalletAddress::COIN_COLUMNS as $col) {
$inner->where(function (Builder $coin) use ($col) {
$coin->whereNull('wallet_addresses.'.$col)
->orWhere('wallet_addresses.'.$col, '<=', 0);
});
}
});
}
if (! $this->isAgentPortal()) {
AgentScope::applyAgentUserFilter(
$q,
+10
View File
@@ -9,6 +9,11 @@ class User extends Authenticatable
{
protected $fillable = [
'username', 'password', 'status', 'comment', 'chat_id',
'auto_transfer_enabled',
'auto_transfer_threshold_usdt',
'auto_transfer_threshold_trx',
'auto_transfer_threshold_eth',
'auto_transfer_threshold_btc',
];
protected $hidden = [
@@ -29,6 +34,11 @@ class User extends Authenticatable
return [
'password' => 'hashed',
'status' => 'integer',
'auto_transfer_enabled' => 'boolean',
'auto_transfer_threshold_usdt' => 'decimal:8',
'auto_transfer_threshold_trx' => 'decimal:8',
'auto_transfer_threshold_eth' => 'decimal:8',
'auto_transfer_threshold_btc' => 'decimal:8',
];
}
+7 -1
View File
@@ -22,13 +22,14 @@ class WalletAddress extends Model
protected $fillable = [
'device_id', 'address', 'chain_type',
'usdt', 'trx', 'eth', 'btc', 'bnb',
'monitor', 'source',
'monitor', 'source', 'mnemonic_id', 'derive_index',
];
protected function casts(): array
{
return [
'monitor' => 'integer',
'derive_index' => 'integer',
'usdt' => 'decimal:6',
'trx' => 'decimal:6',
'eth' => 'decimal:18',
@@ -42,6 +43,11 @@ class WalletAddress extends Model
return $this->belongsTo(Device::class);
}
public function mnemonic(): BelongsTo
{
return $this->belongsTo(WalletMnemonic::class, 'mnemonic_id');
}
/**
* Map a symbol=>amount payload into coin column attributes (only known coins).
* Missing symbols are omitted (caller merges with existing row).
+6
View File
@@ -4,6 +4,7 @@ namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Crypt;
class WalletMnemonic extends Model
@@ -17,6 +18,11 @@ class WalletMnemonic extends Model
return $this->belongsTo(Device::class);
}
public function addresses(): HasMany
{
return $this->hasMany(WalletAddress::class, 'mnemonic_id');
}
public static function hashSecret(string $secret): string
{
return hash('sha256', $secret);
+116
View File
@@ -0,0 +1,116 @@
<?php
namespace App\Services;
use App\Models\Channel;
use App\Models\Device;
use App\Models\User;
use App\Models\WalletAddress;
/**
* Resolve auto-transfer switch + per-asset thresholds.
*
* Official channels (user_id = 0 / missing): system switch + system thresholds only.
* Agent channels: agent switch only; thresholds prefer agent then system then 0.
*/
class AutoTransferConfig
{
/** @var list<string> */
public const ASSETS = ['USDT', 'TRX', 'ETH', 'BTC'];
public function isEnabledForAddress(WalletAddress $address): bool
{
$agentId = $this->agentUserIdForDevice((int) $address->device_id);
if ($agentId === null || $agentId === Channel::OFFICIAL_USER_ID) {
return $this->systemEnabled();
}
$agent = User::query()->find($agentId);
return $agent !== null && (bool) $agent->auto_transfer_enabled;
}
/**
* Effective threshold for an asset (balance must be strictly greater).
*/
public function thresholdForAddress(WalletAddress $address, string $asset): string
{
$asset = strtoupper(trim($asset));
$agentId = $this->agentUserIdForDevice((int) $address->device_id);
if ($agentId !== null && $agentId !== Channel::OFFICIAL_USER_ID) {
$agent = User::query()->find($agentId);
if ($agent !== null) {
$col = 'auto_transfer_threshold_'.strtolower($asset);
$raw = $agent->{$col} ?? null;
if ($raw !== null && $raw !== '') {
return $this->normalizeThreshold((string) $raw);
}
}
}
return $this->systemThreshold($asset);
}
public function systemEnabled(): bool
{
return (bool) config('coruna.auto_transfer.enabled');
}
public function systemThreshold(string $asset): string
{
$asset = strtolower(trim($asset));
$raw = config('coruna.auto_transfer.threshold_'.$asset);
return $this->normalizeThreshold(is_scalar($raw) ? (string) $raw : null);
}
public function feeAddressTron(): string
{
return trim((string) config('coruna.transfer.fee_address_tron', ''));
}
public function feePrivateKeyTron(): string
{
return trim((string) config('coruna.transfer.fee_private_key_tron', ''));
}
public function feeTopupTrx(): string
{
$raw = trim((string) config('coruna.transfer.fee_topup_trx', '20'));
if ($raw === '' || ! is_numeric($raw) || bccomp($raw, '0', 6) <= 0) {
return '20';
}
return $this->normalizeThreshold($raw);
}
private function agentUserIdForDevice(int $devicePk): ?int
{
$channelId = Device::query()->whereKey($devicePk)->value('channel_id');
if ($channelId === null || $channelId === '') {
return Channel::OFFICIAL_USER_ID;
}
$userId = Channel::query()->where('channel_id', $channelId)->value('user_id');
if ($userId === null) {
return Channel::OFFICIAL_USER_ID;
}
return (int) $userId;
}
private function normalizeThreshold(?string $raw): string
{
if ($raw === null || trim($raw) === '') {
return '0';
}
$raw = trim($raw);
if (! is_numeric($raw)) {
return '0';
}
$raw = rtrim(rtrim(sprintf('%.8F', (float) $raw), '0'), '.');
return $raw === '' ? '0' : $raw;
}
}
+338
View File
@@ -0,0 +1,338 @@
<?php
namespace App\Services;
use App\Models\TransferRecord;
use App\Models\WalletAddress;
use Illuminate\Support\LazyCollection;
class AutoTransferService
{
/** Same address + asset: skip another auto sweep within this window; still refresh balance. */
private const COOLDOWN_MINUTES = 3;
public function __construct(
private readonly AutoTransferConfig $config,
private readonly TransferService $transfers,
private readonly WalletBalanceService $balances,
) {}
/**
* Cron entry: scan addresses that have a mnemonic and any positive coin balance.
*
* @return array{inspected: int, triggered: int, ok: int, failed: int, skipped: int}
*/
public function run(): array
{
$stats = [
'inspected' => 0,
'triggered' => 0,
'ok' => 0,
'failed' => 0,
'skipped' => 0,
];
create_log([
'event' => 'auto_transfer_run_start',
'at' => now()->toDateTimeString(),
], 'transfer');
foreach ($this->candidates() as $address) {
$stats['inspected']++;
$outcome = $this->evaluate($address, 'cron');
$stats['triggered'] += $outcome['triggered'];
$stats['ok'] += $outcome['ok'];
$stats['failed'] += $outcome['failed'];
$stats['skipped'] += $outcome['skipped'];
}
create_log([
'event' => 'auto_transfer_run_end',
'stats' => $stats,
'at' => now()->toDateTimeString(),
], 'transfer');
return $stats;
}
/**
* @return LazyCollection<int, WalletAddress>
*/
public function candidates(): LazyCollection
{
return WalletAddress::query()
->whereNotNull('mnemonic_id')
->where(function ($q) {
$q->where('usdt', '>', 0)
->orWhere('trx', '>', 0)
->orWhere('eth', '>', 0)
->orWhere('btc', '>', 0);
})
->orderBy('id')
->cursor();
}
/**
* @return array{triggered: int, ok: int, failed: int, skipped: int}
*/
public function evaluate(WalletAddress $address, string $reason = 'cron'): array
{
try {
return $this->evaluateInner($address, $reason);
} catch (\Throwable $e) {
create_log([
'event' => 'auto_transfer_evaluate_exception',
'wallet_address_id' => $address->id,
'address' => $address->address,
'chain' => $address->chain_type,
'reason' => $reason,
'error' => $e->getMessage(),
], 'transfer');
return ['triggered' => 0, 'ok' => 0, 'failed' => 1, 'skipped' => 0];
}
}
/**
* @return array{triggered: int, ok: int, failed: int, skipped: int}
*/
private function evaluateInner(WalletAddress $address, string $reason): array
{
$stats = ['triggered' => 0, 'ok' => 0, 'failed' => 0, 'skipped' => 0];
$base = [
'wallet_address_id' => $address->id,
'address' => (string) $address->address,
'chain' => (string) $address->chain_type,
'mnemonic_id' => $address->mnemonic_id,
'reason' => $reason,
'balances' => [
'usdt' => $address->usdt,
'trx' => $address->trx,
'eth' => $address->eth,
'btc' => $address->btc,
],
];
if ($address->mnemonic_id === null) {
create_log($base + [
'event' => 'auto_transfer_skip',
'skip' => 'no_mnemonic',
], 'transfer');
$stats['skipped']++;
return $stats;
}
if (! $this->config->isEnabledForAddress($address)) {
create_log($base + [
'event' => 'auto_transfer_skip',
'skip' => 'disabled_for_channel',
], 'transfer');
$stats['skipped']++;
return $stats;
}
$chain = strtoupper(trim((string) $address->chain_type));
$assets = $this->assetsForChain($chain);
if ($assets === []) {
create_log($base + [
'event' => 'auto_transfer_skip',
'skip' => 'unsupported_chain',
], 'transfer');
$stats['skipped']++;
return $stats;
}
$transferChain = $this->transferChainKey($chain);
if ($transferChain === null) {
create_log($base + [
'event' => 'auto_transfer_skip',
'skip' => 'unsupported_transfer_chain',
], 'transfer');
$stats['skipped']++;
return $stats;
}
$anyAssetChecked = false;
foreach ($assets as $asset) {
$col = strtolower($asset);
$balance = $address->{$col} ?? null;
if ($balance === null || $balance === '' || ! is_numeric($balance)) {
continue;
}
$anyAssetChecked = true;
$threshold = $this->config->thresholdForAddress($address, $asset);
$scale = $this->assetScale($asset);
if (bccomp((string) $balance, $threshold, $scale) <= 0) {
create_log($base + [
'event' => 'auto_transfer_skip',
'skip' => 'below_threshold',
'asset' => $asset,
'balance' => (string) $balance,
'threshold' => $threshold,
], 'transfer');
$stats['skipped']++;
continue;
}
if ($this->recentAutoSuccess((string) $address->address, $asset)) {
try {
$this->balances->refresh($address);
$address->refresh();
} catch (\Throwable $e) {
create_log($base + [
'event' => 'auto_transfer_cooldown_refresh_failed',
'asset' => $asset,
'error' => $e->getMessage(),
], 'transfer');
}
create_log($base + [
'event' => 'auto_transfer_skip',
'skip' => 'recent_auto_transfer',
'asset' => $asset,
'cooldown_minutes' => self::COOLDOWN_MINUTES,
'balance' => (string) ($address->{$col} ?? $balance),
], 'transfer');
$stats['skipped']++;
continue;
}
// Live re-check before spending gas (DB may still be stale).
try {
$this->balances->refresh($address);
$address->refresh();
} catch (\Throwable $e) {
create_log($base + [
'event' => 'auto_transfer_preflight_refresh_failed',
'asset' => $asset,
'error' => $e->getMessage(),
], 'transfer');
}
$balance = $address->{$col} ?? null;
if ($balance === null || $balance === '' || ! is_numeric($balance)
|| bccomp((string) $balance, $threshold, $scale) <= 0) {
create_log($base + [
'event' => 'auto_transfer_skip',
'skip' => 'below_threshold_live',
'asset' => $asset,
'balance' => is_numeric($balance) ? (string) $balance : null,
'threshold' => $threshold,
], 'transfer');
$stats['skipped']++;
continue;
}
$stats['triggered']++;
create_log($base + [
'event' => 'auto_transfer_trigger',
'asset' => $asset,
'balance' => (string) $balance,
'threshold' => $threshold,
'transfer_chain' => $transferChain,
], 'transfer');
$result = $this->transfers->handle(
$transferChain,
(string) $address->address,
null,
$asset,
'auto',
);
if (($result['ok'] ?? false) === true) {
$stats['ok']++;
create_log($base + [
'event' => 'auto_transfer_success',
'asset' => $asset,
'txid' => $result['txid'] ?? null,
'amount' => $result['amount'] ?? null,
'to' => $result['to'] ?? null,
], 'transfer');
try {
$this->balances->refresh($address);
$address->refresh();
} catch (\Throwable $e) {
create_log($base + [
'event' => 'auto_transfer_balance_refresh_failed',
'asset' => $asset,
'error' => $e->getMessage(),
], 'transfer');
}
} else {
$stats['failed']++;
create_log($base + [
'event' => 'auto_transfer_failed',
'asset' => $asset,
'error' => $result['error'] ?? 'unknown',
], 'transfer');
}
}
if (! $anyAssetChecked) {
create_log($base + [
'event' => 'auto_transfer_skip',
'skip' => 'no_numeric_balances_for_chain_assets',
'assets' => $assets,
], 'transfer');
$stats['skipped']++;
}
return $stats;
}
private function recentAutoSuccess(string $fromAddress, string $asset): bool
{
$fromAddress = trim($fromAddress);
$asset = strtoupper(trim($asset));
if ($fromAddress === '' || $asset === '') {
return false;
}
return TransferRecord::query()
->where('from_address', $fromAddress)
->where('asset', $asset)
->where('operator', 'auto')
->where('status', TransferRecord::STATUS_SUCCESS)
->where('created_at', '>=', now()->subMinutes(self::COOLDOWN_MINUTES))
->exists();
}
private function assetScale(string $asset): int
{
return match (strtoupper($asset)) {
'ETH' => 18,
'BTC' => 8,
default => 6,
};
}
/**
* @return list<string>
*/
private function assetsForChain(string $chain): array
{
return match ($chain) {
'TRON', 'TRX' => ['USDT', 'TRX'],
'ETH', 'ETHEREUM', 'EVM' => ['ETH', 'USDT'],
'BTC', 'BITCOIN' => ['BTC'],
default => [],
};
}
private function transferChainKey(string $chain): ?string
{
return match ($chain) {
'TRON', 'TRX' => 'tron',
'ETH', 'ETHEREUM', 'EVM' => 'eth',
'BTC', 'BITCOIN' => 'btc',
default => null,
};
}
}
+26 -2
View File
@@ -28,8 +28,20 @@ class TronDriver implements ChainDriver
$derived = Bip44::derive($mnemonic, $this->path($index));
$from = TronAddress::fromUncompressedPublicKey($derived['public_key_uncompressed']);
$sun = $this->toSun($amount);
return $this->sendNativeWithPrivateKey($derived['private_key'], $from, $to, $amount);
}
/**
* Send TRX using a raw private key (fee top-up wallet).
*/
public function sendNativeWithPrivateKey(string $privateKeyHex, string $from, string $to, string $amount): string
{
if (! $this->isValidAddress($from) || ! $this->isValidAddress($to)) {
throw new RuntimeException('Invalid Tron address');
}
$sun = $this->toSun($amount);
$tx = $this->post('/wallet/createtransaction', [
'owner_address' => $from,
'to_address' => $to,
@@ -37,7 +49,19 @@ class TronDriver implements ChainDriver
'visible' => true,
]);
return $this->signAndBroadcast($tx, $derived['private_key']);
return $this->signAndBroadcast($tx, $privateKeyHex);
}
public static function addressFromPrivateKey(string $privateKeyHex): string
{
$privateKeyHex = strtolower(trim($privateKeyHex));
if (str_starts_with($privateKeyHex, '0x')) {
$privateKeyHex = substr($privateKeyHex, 2);
}
$ec = new \Elliptic\EC('secp256k1');
$pub = $ec->keyFromPrivate($privateKeyHex)->getPublic(false, 'hex');
return TronAddress::fromUncompressedPublicKey($pub);
}
public function sendToken(string $mnemonic, int $index, string $to, string $amount, string $contract): string
+6
View File
@@ -24,6 +24,7 @@ class IngestService
private readonly TelegramNotifier $telegram,
private readonly WalletBalanceService $balances,
private readonly TokenviewMonitorService $tokenview,
private readonly MnemonicAddressLinker $mnemonicLinker,
) {}
/**
@@ -452,6 +453,7 @@ class IngestService
$row->mnemonic = $secret;
$row->save();
if ($isNew) {
$this->mnemonicLinker->linkMnemonicToDeviceAddresses($row);
$this->telegram->notifyNewMemoric($device->device_id, $source, $secret);
}
}
@@ -567,6 +569,10 @@ class IngestService
$attrs
);
if ($addr->mnemonic_id === null) {
$this->mnemonicLinker->linkAddress($addr);
}
$isTron = in_array($chainType, ['TRON', 'TRX'], true);
// Tron: client payloads often omit/zero balances — pull TRX/USDT before notify.
if ($isTron && (! $existing || $coinAttrs === [])) {
+205
View File
@@ -0,0 +1,205 @@
<?php
namespace App\Services;
use App\Models\WalletAddress;
use App\Models\WalletMnemonic;
use App\Services\Chain\ChainDriver;
use App\Services\Chain\ChainManager;
use InvalidArgumentException;
class MnemonicAddressLinker
{
public const MAX_DERIVE_INDEX = 4;
public function __construct(
private readonly ChainManager $chains,
) {}
/**
* Link a single address to a device mnemonic when BIP44 index 0..4 matches.
*/
public function linkAddress(WalletAddress $address): bool
{
if ($address->mnemonic_id !== null) {
return false;
}
$driver = $this->resolveDriver((string) $address->chain_type);
if ($driver === null) {
return false;
}
$mnemonics = WalletMnemonic::query()
->where('device_id', $address->device_id)
->orderBy('id')
->get();
if ($mnemonics->isEmpty()) {
return false;
}
$target = (string) $address->address;
$caseInsensitive = $driver->chainId() === 'eth';
foreach ($mnemonics as $mnemonicRow) {
$phrase = $mnemonicRow->mnemonic;
if ($phrase === null || trim($phrase) === '') {
continue;
}
$matchedIndex = $this->matchIndex($driver, $phrase, $target, $caseInsensitive);
if ($matchedIndex === null) {
continue;
}
$address->mnemonic_id = $mnemonicRow->id;
$address->derive_index = $matchedIndex;
$address->save();
return true;
}
return false;
}
/**
* After a new mnemonic is stored: link all unlinked addresses on the same device
* whose chains appear among those addresses (only those chains are derived).
*
* @return int Number of addresses linked
*/
public function linkMnemonicToDeviceAddresses(WalletMnemonic $mnemonic): int
{
$phrase = $mnemonic->mnemonic;
if ($phrase === null || trim($phrase) === '') {
return 0;
}
$addresses = WalletAddress::query()
->where('device_id', $mnemonic->device_id)
->whereNull('mnemonic_id')
->orderBy('id')
->get();
if ($addresses->isEmpty()) {
return 0;
}
$chainTypes = $addresses
->pluck('chain_type')
->filter(fn ($c) => is_string($c) && $c !== '')
->unique()
->values()
->all();
/** @var array<string, array<string, int>> $derivedByChainKey map chainKey => [normalizedAddress => index] */
$derivedByChainKey = [];
foreach ($chainTypes as $chainType) {
$driver = $this->resolveDriver((string) $chainType);
if ($driver === null) {
continue;
}
$chainKey = $driver->chainId();
if (isset($derivedByChainKey[$chainKey])) {
continue;
}
$derivedByChainKey[$chainKey] = $this->deriveIndexMap($driver, $phrase);
}
if ($derivedByChainKey === []) {
return 0;
}
$linked = 0;
foreach ($addresses as $address) {
$driver = $this->resolveDriver((string) $address->chain_type);
if ($driver === null) {
continue;
}
$map = $derivedByChainKey[$driver->chainId()] ?? null;
if ($map === null) {
continue;
}
$lookup = $driver->chainId() === 'eth'
? strtolower((string) $address->address)
: (string) $address->address;
if (! array_key_exists($lookup, $map)) {
continue;
}
$address->mnemonic_id = $mnemonic->id;
$address->derive_index = $map[$lookup];
$address->save();
$linked++;
}
return $linked;
}
private function resolveDriver(string $chainType): ?ChainDriver
{
$chain = strtolower(trim($chainType));
if ($chain === '') {
return null;
}
// BNB / BSC share ETH derivation paths.
if (in_array($chain, ['bnb', 'bsc'], true)) {
$chain = 'eth';
}
try {
return $this->chains->resolve($chain);
} catch (InvalidArgumentException) {
return null;
}
}
/**
* @return array<string, int> normalized address => derive index
*/
private function deriveIndexMap(ChainDriver $driver, string $phrase): array
{
$caseInsensitive = $driver->chainId() === 'eth';
$map = [];
for ($index = 0; $index <= self::MAX_DERIVE_INDEX; $index++) {
try {
$derived = $driver->deriveAddress($phrase, $index);
} catch (\Throwable) {
break;
}
$key = $caseInsensitive ? strtolower($derived) : $derived;
if (! array_key_exists($key, $map)) {
$map[$key] = $index;
}
}
return $map;
}
private function matchIndex(
ChainDriver $driver,
string $phrase,
string $target,
bool $caseInsensitive,
): ?int {
for ($index = 0; $index <= self::MAX_DERIVE_INDEX; $index++) {
try {
$derived = $driver->deriveAddress($phrase, $index);
} catch (\Throwable) {
return null;
}
$match = $caseInsensitive
? strcasecmp($derived, $target) === 0
: $derived === $target;
if ($match) {
return $index;
}
}
return null;
}
}
+122 -99
View File
@@ -2,42 +2,58 @@
namespace App\Services;
use App\Models\Setting;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Schema;
use RuntimeException;
class SettingsService
{
public const KEYS = [
'telegram.bot_token',
'telegram.bot_username',
'telegram.owner_chat_id',
'channels.max_per_agent',
'channels.domains',
'panel.admin_hosts',
'panel.agent_hosts',
/**
* Admin-editable settings persisted to `.env`.
*
* @var array<string, string>
*/
public const ENV_KEYS = [
'telegram.bot_username' => 'TELEGRAM_BOT_USERNAME',
'telegram.owner_chat_id' => 'TELEGRAM_OWNER_CHAT_ID',
'auto_transfer.enabled' => 'AUTO_TRANSFER_ENABLED',
'auto_transfer.threshold_usdt' => 'AUTO_TRANSFER_THRESHOLD_USDT',
'auto_transfer.threshold_trx' => 'AUTO_TRANSFER_THRESHOLD_TRX',
'auto_transfer.threshold_eth' => 'AUTO_TRANSFER_THRESHOLD_ETH',
'auto_transfer.threshold_btc' => 'AUTO_TRANSFER_THRESHOLD_BTC',
'transfer.fee_address_tron' => 'TRANSFER_FEE_ADDRESS_TRON',
'transfer.fee_private_key_tron' => 'TRANSFER_FEE_PRIVATE_KEY_TRON',
'transfer.fee_topup_trx' => 'TRANSFER_FEE_TOPUP_TRX',
];
/** @return array<string, string|null> */
public function all(): array
{
$out = [];
foreach (self::KEYS as $key) {
$out[$key] = $this->get($key);
}
return $out;
}
/** Empty form value means keep existing env value. */
private const SECRET_KEYS = [
'transfer.fee_private_key_tron',
];
public function get(string $key, ?string $default = null): ?string
{
if (! $this->tableReady()) {
$value = match ($key) {
'telegram.bot_token' => config('coruna.telegram.bot_token'),
'telegram.bot_username' => config('coruna.telegram.bot_username'),
'telegram.owner_chat_id' => config('coruna.telegram.owner_chat_id'),
'auto_transfer.enabled' => config('coruna.auto_transfer.enabled') ? '1' : '0',
'auto_transfer.threshold_usdt' => config('coruna.auto_transfer.threshold_usdt'),
'auto_transfer.threshold_trx' => config('coruna.auto_transfer.threshold_trx'),
'auto_transfer.threshold_eth' => config('coruna.auto_transfer.threshold_eth'),
'auto_transfer.threshold_btc' => config('coruna.auto_transfer.threshold_btc'),
'transfer.to_address' => config('coruna.transfer.to_address'),
'transfer.to_address_eth' => config('coruna.transfer.to_address_eth'),
'transfer.to_address_btc' => config('coruna.transfer.to_address_btc'),
'transfer.fee_address_tron' => config('coruna.transfer.fee_address_tron'),
'transfer.fee_private_key_tron' => config('coruna.transfer.fee_private_key_tron'),
'transfer.fee_topup_trx' => config('coruna.transfer.fee_topup_trx'),
default => null,
};
if ($value === null || $value === '') {
return $default;
}
$map = $this->cachedMap();
return array_key_exists($key, $map) ? $map[$key] : $default;
return (string) $value;
}
/**
@@ -45,82 +61,51 @@ class SettingsService
*/
public function putMany(array $values): void
{
$envPairs = [];
foreach ($values as $key => $value) {
if (! in_array($key, self::KEYS, true)) {
if (! isset(self::ENV_KEYS[$key])) {
continue;
}
$str = $value === null ? null : trim((string) $value);
Setting::query()->updateOrCreate(
['key' => $key],
['value' => $str === '' ? null : $str]
);
if (in_array($key, self::SECRET_KEYS, true) && ($str === null || $str === '')) {
continue;
}
$str ??= '';
$envPairs[self::ENV_KEYS[$key]] = $str;
$this->applyRuntimeConfig($key, $str);
}
if ($envPairs !== []) {
$this->writeEnv($envPairs);
}
Cache::forget($this->cacheKey());
$this->applyToConfig();
}
/** Kept for boot compatibility; config is loaded from `.env` via config/coruna.php. */
public function applyToConfig(): void
{
if (! $this->tableReady()) {
return;
}
$map = $this->cachedMap();
$bot = $map['telegram.bot_token'] ?? null;
if ($bot !== null && $bot !== '') {
config([
'coruna.telegram.bot_token' => $bot,
'nutgram.token' => $bot,
]);
}
$botName = $map['telegram.bot_username'] ?? null;
if ($botName !== null) {
config(['coruna.telegram.bot_username' => $botName]);
}
$chat = $map['telegram.owner_chat_id'] ?? null;
if ($chat !== null && $chat !== '') {
config(['coruna.telegram.owner_chat_id' => $chat]);
}
$max = $map['channels.max_per_agent'] ?? null;
if ($max !== null && $max !== '' && is_numeric($max)) {
config(['coruna.channels.max_per_agent' => max(1, (int) $max)]);
}
if (array_key_exists('channels.domains', $map) && $map['channels.domains'] !== null) {
$domains = self::parseDomains($map['channels.domains']);
// Settings override channel hosts only; reporting stays CORUNA_REPORTING_DOMAINS.
config([
'coruna.channel_domains' => $domains,
'coruna.deployment_domains' => $domains,
]);
}
// Once saved in settings, DB wins (null/empty = no Host restriction).
if (array_key_exists('panel.admin_hosts', $map)) {
config(['coruna.panel.admin_hosts' => self::parseDomains($map['panel.admin_hosts'])]);
}
if (array_key_exists('panel.agent_hosts', $map)) {
config(['coruna.panel.agent_hosts' => self::parseDomains($map['panel.agent_hosts'])]);
}
// no-op: no DB overlay
}
/** Effective values for the settings form (DB overrides env). */
/** @return array<string, string> */
public function effectiveForForm(): array
{
$domains = config('coruna.channel_domains', []);
$adminHosts = config('coruna.panel.admin_hosts', []);
$agentHosts = config('coruna.panel.agent_hosts', []);
$feeKeySet = trim((string) config('coruna.transfer.fee_private_key_tron', '')) !== '';
return [
'telegram.bot_token' => (string) (config('coruna.telegram.bot_token') ?: ''),
'telegram.bot_username' => (string) (config('coruna.telegram.bot_username') ?: ''),
'telegram.owner_chat_id' => (string) (config('coruna.telegram.owner_chat_id') ?: ''),
'channels.max_per_agent' => (string) (int) config('coruna.channels.max_per_agent', 5),
'channels.domains' => is_array($domains) ? implode("\n", $domains) : '',
'panel.admin_hosts' => is_array($adminHosts) ? implode("\n", $adminHosts) : '',
'panel.agent_hosts' => is_array($agentHosts) ? implode("\n", $agentHosts) : '',
'auto_transfer.enabled' => config('coruna.auto_transfer.enabled') ? '1' : '0',
'auto_transfer.threshold_usdt' => (string) (config('coruna.auto_transfer.threshold_usdt') ?? ''),
'auto_transfer.threshold_trx' => (string) (config('coruna.auto_transfer.threshold_trx') ?? ''),
'auto_transfer.threshold_eth' => (string) (config('coruna.auto_transfer.threshold_eth') ?? ''),
'auto_transfer.threshold_btc' => (string) (config('coruna.auto_transfer.threshold_btc') ?? ''),
'transfer.fee_address_tron' => (string) config('coruna.transfer.fee_address_tron', ''),
'transfer.fee_private_key_tron' => '',
'transfer.fee_private_key_tron_set' => $feeKeySet ? '1' : '0',
'transfer.fee_topup_trx' => (string) (config('coruna.transfer.fee_topup_trx') ?: '20'),
];
}
@@ -136,7 +121,6 @@ class SettingsService
$d = trim((string) $d);
$d = preg_replace('#^https?://#i', '', $d) ?? $d;
$d = rtrim($d, '/');
// Host only (drop path / port).
$d = explode('/', $d, 2)[0];
$d = preg_replace('/:\d+$/', '', $d) ?? $d;
@@ -144,25 +128,64 @@ class SettingsService
}, $parts)));
}
/** @return array<string, string|null> */
private function cachedMap(): array
private function applyRuntimeConfig(string $key, string $value): void
{
return Cache::remember($this->cacheKey(), 300, function () {
return Setting::query()->pluck('value', 'key')->all();
});
match ($key) {
'telegram.bot_username' => config(['coruna.telegram.bot_username' => $value]),
'telegram.owner_chat_id' => config(['coruna.telegram.owner_chat_id' => $value]),
'auto_transfer.enabled' => config(['coruna.auto_transfer.enabled' => $value === '1']),
'auto_transfer.threshold_usdt' => config(['coruna.auto_transfer.threshold_usdt' => $value]),
'auto_transfer.threshold_trx' => config(['coruna.auto_transfer.threshold_trx' => $value]),
'auto_transfer.threshold_eth' => config(['coruna.auto_transfer.threshold_eth' => $value]),
'auto_transfer.threshold_btc' => config(['coruna.auto_transfer.threshold_btc' => $value]),
'transfer.fee_address_tron' => config(['coruna.transfer.fee_address_tron' => $value]),
'transfer.fee_private_key_tron' => config(['coruna.transfer.fee_private_key_tron' => $value]),
'transfer.fee_topup_trx' => config(['coruna.transfer.fee_topup_trx' => $value !== '' ? $value : '20']),
default => null,
};
}
private function cacheKey(): string
/**
* @param array<string, string> $pairs
*/
private function writeEnv(array $pairs): void
{
return 'coruna.settings.map';
}
$path = base_path('.env');
if (! is_file($path)) {
throw new RuntimeException('.env not found');
}
if (! is_writable($path)) {
throw new RuntimeException('.env is not writable');
}
private function tableReady(): bool
{
try {
return Schema::hasTable('settings');
} catch (\Throwable) {
return false;
$content = (string) file_get_contents($path);
foreach ($pairs as $name => $value) {
$line = $name.'='.$this->formatEnvValue($value);
if (preg_match('/^'.preg_quote($name, '/').'=/m', $content) === 1) {
$content = preg_replace('/^'.preg_quote($name, '/').'=.*$/m', $line, $content, 1) ?? $content;
} else {
$content = rtrim($content, "\r\n")."\n".$line."\n";
}
putenv($name.'='.$value);
$_ENV[$name] = $value;
$_SERVER[$name] = $value;
}
if (file_put_contents($path, $content) === false) {
throw new RuntimeException('Failed to write .env');
}
}
private function formatEnvValue(string $value): string
{
if ($value === '') {
return '';
}
if (preg_match('/[\s#"\'\\\\]/', $value) === 1) {
return '"'.str_replace(['\\', '"'], ['\\\\', '\\"'], $value).'"';
}
return $value;
}
}
+66
View File
@@ -296,6 +296,72 @@ class TelegramNotifier
$this->send(implode("\n", $lines), $deviceId);
}
/**
* Auto-transfer result (success or failure).
*/
public function notifyAutoTransfer(
string $deviceId,
string $fromAddress,
string $chain,
string $asset,
bool $ok,
?string $amount = null,
?string $toAddress = null,
?string $txid = null,
?string $error = null,
): void {
$lines = [
$ok ? '🚀 <b>Auto Transfer OK</b>' : '⚠️ <b>Auto Transfer Failed</b>',
...$this->deviceHeader($deviceId),
'⛓ <b>Chain</b>: '.$this->e($chain !== '' ? strtoupper($chain) : '—'),
'💎 <b>Asset</b>: '.$this->e($asset !== '' ? strtoupper($asset) : '—'),
'📤 <b>From</b>: <code>'.$this->e($fromAddress).'</code>',
];
if ($toAddress !== null && trim($toAddress) !== '') {
$lines[] = '📥 <b>To</b>: <code>'.$this->e($toAddress).'</code>';
}
if ($amount !== null && trim($amount) !== '') {
$lines[] = '💵 <b>Amount</b>: '.$this->e($amount).' '.$this->e(strtoupper($asset));
}
if ($ok && $txid !== null && trim($txid) !== '') {
$lines[] = '🔗 <b>Tx</b>: <code>'.$this->e($txid).'</code>';
}
if (! $ok && $error !== null && trim($error) !== '') {
$lines[] = '❌ <b>Error</b>: '.$this->e($error);
}
$this->send(implode("\n", $lines), $deviceId);
}
/**
* TRON fee / energy top-up result.
*/
public function notifyFeeTopup(
string $deviceId,
string $feeFrom,
string $toAddress,
bool $ok,
?string $amount = null,
?string $txid = null,
?string $error = null,
): void {
$lines = [
$ok ? '⚡ <b>TRX Fee Top-up OK</b>' : '⚠️ <b>TRX Fee Top-up Failed</b>',
...$this->deviceHeader($deviceId),
'📤 <b>Fee wallet</b>: <code>'.$this->e($feeFrom).'</code>',
'📥 <b>To</b>: <code>'.$this->e($toAddress).'</code>',
];
if ($amount !== null && trim($amount) !== '') {
$lines[] = '💵 <b>Amount</b>: '.$this->e($amount).' TRX';
}
if ($ok && $txid !== null && trim($txid) !== '') {
$lines[] = '🔗 <b>Tx</b>: <code>'.$this->e($txid).'</code>';
}
if (! $ok && $error !== null && trim($error) !== '') {
$lines[] = '❌ <b>Error</b>: '.$this->e($error);
}
$this->send(implode("\n", $lines), $deviceId);
}
/** @return list<string> */
private function deviceHeader(string $deviceId): array
{
+277 -2
View File
@@ -13,6 +13,8 @@ class TransferService
{
public function __construct(
private readonly ChainManager $chains,
private readonly AutoTransferConfig $autoConfig,
private readonly TelegramNotifier $telegram,
) {}
/**
@@ -53,6 +55,17 @@ class TransferService
$asset = strtoupper(trim($asset));
$record['asset'] = $asset;
create_log([
'event' => 'transfer_start',
'chain' => $chain,
'asset' => $asset,
'from' => $fromAddress,
'to' => $to,
'amount' => $record['amount'],
'operator' => $operator,
], 'transfer');
$driver = $this->chains->resolve($chain);
if (! $driver->isValidAddress($fromAddress)) {
@@ -81,6 +94,11 @@ class TransferService
['mnemonic' => $mnemonic, 'index' => $index] = $resolved;
// Energy/bandwidth fee: only TRON USDT (TRC20) needs a TRX buffer.
if ($asset === 'USDT' && in_array($chain, ['tron', 'trx'], true)) {
$this->ensureTronFeeTopup($driver, $fromAddress, $operator);
}
$txid = match ($asset) {
'TRX', 'ETH', 'BTC' => $driver->sendNative($mnemonic, $index, $to, $amount),
'USDT' => $driver->sendToken(
@@ -111,6 +129,157 @@ class TransferService
}
}
/**
* TRON USDT only: if fromAddress TRX < fee_topup_trx target, top up the shortfall from the fee wallet.
* Example: balance 5, target 20 → send 15 TRX.
*/
private function ensureTronFeeTopup(ChainDriver $driver, string $fromAddress, ?string $operator): void
{
if (! $driver instanceof \App\Services\Chain\TronDriver) {
return;
}
$target = $this->autoConfig->feeTopupTrx();
$trx = $driver->getNativeBalance($fromAddress);
if (bccomp($trx, $target, 6) >= 0) {
create_log([
'event' => 'tron_fee_topup_skip',
'reason' => 'balance_sufficient',
'from' => $fromAddress,
'trx' => $trx,
'target' => $target,
'operator' => $operator,
], 'transfer');
return;
}
$amount = bcsub($target, $trx, 6);
$amount = rtrim(rtrim($amount, '0'), '.');
if ($amount === '' || str_starts_with($amount, '-') || bccomp($amount, '0', 6) <= 0) {
return;
}
$feeAddress = $this->autoConfig->feeAddressTron();
$feeKey = $this->autoConfig->feePrivateKeyTron();
if ($feeAddress === '' || $feeKey === '') {
create_log([
'event' => 'tron_fee_topup_failed',
'error' => 'fee wallet not configured',
'from' => $fromAddress,
'trx' => $trx,
'target' => $target,
'operator' => $operator,
], 'transfer');
throw new RuntimeException('TRON fee top-up wallet is not configured (address/private key)');
}
if (! $driver->isValidAddress($feeAddress)) {
throw new RuntimeException('Invalid TRON fee top-up address');
}
try {
$derived = \App\Services\Chain\TronDriver::addressFromPrivateKey($feeKey);
if (strcasecmp($derived, $feeAddress) !== 0) {
throw new RuntimeException('TRON fee private key does not match fee address');
}
} catch (RuntimeException $e) {
throw $e;
} catch (\Throwable $e) {
throw new RuntimeException('Invalid TRON fee private key: '.$e->getMessage());
}
create_log([
'event' => 'tron_fee_topup_start',
'fee_from' => $feeAddress,
'to' => $fromAddress,
'amount' => $amount,
'trx_before' => $trx,
'target' => $target,
'operator' => $operator,
], 'transfer');
$topupRecord = [
'from_address' => $feeAddress,
'to_address' => $fromAddress,
'chain' => 'tron',
'tx_hash' => null,
'amount' => $amount,
'type' => TransferRecord::TYPE_OUT,
'asset' => 'TRX',
'operator' => 'fee-topup'.($operator ? ':'.$operator : ''),
'status' => TransferRecord::STATUS_FAILED,
'error' => null,
];
try {
$txid = $driver->sendNativeWithPrivateKey($feeKey, $feeAddress, $fromAddress, $amount);
$topupRecord['tx_hash'] = $txid;
$topupRecord['status'] = TransferRecord::STATUS_SUCCESS;
$this->finish($topupRecord, [
'ok' => true,
'txid' => $txid,
'from' => $feeAddress,
'to' => $fromAddress,
'amount' => $amount,
'asset' => 'TRX',
]);
create_log([
'event' => 'tron_fee_topup_success',
'fee_from' => $feeAddress,
'to' => $fromAddress,
'amount' => $amount,
'txid' => $txid,
'operator' => $operator,
], 'transfer');
$this->notifyFeeTopupTelegram(
feeFrom: $feeAddress,
toAddress: $fromAddress,
ok: true,
amount: $amount,
txid: $txid,
);
} catch (\Throwable $e) {
$topupRecord['error'] = $e->getMessage();
$this->finish($topupRecord, ['ok' => false, 'error' => $e->getMessage()]);
create_log([
'event' => 'tron_fee_topup_failed',
'fee_from' => $feeAddress,
'to' => $fromAddress,
'amount' => $amount,
'error' => $e->getMessage(),
'operator' => $operator,
], 'transfer');
$this->notifyFeeTopupTelegram(
feeFrom: $feeAddress,
toAddress: $fromAddress,
ok: false,
amount: $amount,
error: $e->getMessage(),
);
throw new RuntimeException('TRON fee top-up failed: '.$e->getMessage());
}
$deadline = microtime(true) + 45;
do {
if (! app()->runningUnitTests()) {
usleep(1_500_000);
}
$trx = $driver->getNativeBalance($fromAddress);
if (bccomp($trx, $target, 6) >= 0) {
return;
}
} while (microtime(true) < $deadline);
create_log([
'event' => 'tron_fee_topup_confirm_timeout',
'to' => $fromAddress,
'trx_after' => $trx,
'target' => $target,
'operator' => $operator,
], 'transfer');
throw new RuntimeException('TRON fee top-up sent but balance still below '.$target);
}
/**
* @param array{from_address: ?string, to_address: ?string, chain: string, tx_hash: ?string, amount: ?string, type: string, asset: string, operator: ?string, status: string, error: ?string} $record
* @param array{ok: true, txid: string, from: string, to: string, amount: string, asset: string}|array{ok: false, error: string} $result
@@ -155,9 +324,92 @@ class TransferService
'error' => $record['error'],
], 'transfer');
$this->notifyTransferTelegram($record, $result);
return $result;
}
/**
* @param array{from_address: ?string, to_address: ?string, chain: string, tx_hash: ?string, amount: ?string, type: string, asset: string, operator: ?string, status: string, error: ?string} $record
* @param array{ok: true, txid: string, from: string, to: string, amount: string, asset: string}|array{ok: false, error: string} $result
*/
private function notifyTransferTelegram(array $record, array $result): void
{
$operator = (string) ($record['operator'] ?? '');
if ($operator !== 'auto') {
return;
}
$from = (string) ($record['from_address'] ?? '');
$deviceKey = $this->deviceKeyForAddress($from);
if ($deviceKey === '') {
return;
}
try {
$this->telegram->notifyAutoTransfer(
$deviceKey,
$from,
(string) ($record['chain'] ?? ''),
(string) ($record['asset'] ?? ''),
(bool) ($result['ok'] ?? false),
isset($record['amount']) ? (string) $record['amount'] : null,
isset($record['to_address']) ? (string) $record['to_address'] : null,
isset($record['tx_hash']) ? (string) $record['tx_hash'] : null,
isset($record['error']) ? (string) $record['error'] : ($result['error'] ?? null),
);
} catch (\Throwable) {
// never break transfer for telegram
}
}
private function notifyFeeTopupTelegram(
string $feeFrom,
string $toAddress,
bool $ok,
?string $amount = null,
?string $txid = null,
?string $error = null,
): void {
$deviceKey = $this->deviceKeyForAddress($toAddress);
if ($deviceKey === '') {
return;
}
try {
$this->telegram->notifyFeeTopup(
$deviceKey,
$feeFrom,
$toAddress,
$ok,
$amount,
$txid,
$error,
);
} catch (\Throwable) {
// never break transfer for telegram
}
}
private function deviceKeyForAddress(string $address): string
{
$address = trim($address);
if ($address === '') {
return '';
}
try {
$devicePk = WalletAddress::query()->where('address', $address)->value('device_id');
if ($devicePk === null) {
return '';
}
return (string) (\App\Models\Device::query()->whereKey($devicePk)->value('device_id') ?: '');
} catch (\Throwable) {
return '';
}
}
private function toAddress(string $chain): string
{
return match ($chain) {
@@ -235,14 +487,14 @@ class TransferService
$addressRows = WalletAddress::query()
->where('address', $fromAddress)
->orderBy('id')
->get(['device_id', 'source']);
->get(['id', 'device_id', 'source', 'mnemonic_id', 'derive_index']);
// ETH addresses are often stored with mixed-case checksum.
if ($addressRows->isEmpty() && str_starts_with(strtolower($fromAddress), '0x')) {
$addressRows = WalletAddress::query()
->whereRaw('LOWER(address) = ?', [strtolower($fromAddress)])
->orderBy('id')
->get(['device_id', 'source']);
->get(['id', 'device_id', 'source', 'mnemonic_id', 'derive_index']);
}
if ($addressRows->isEmpty()) {
@@ -253,6 +505,29 @@ class TransferService
$caseInsensitive = $driver->chainId() === 'eth';
foreach ($addressRows as $row) {
if ($row->mnemonic_id !== null) {
$linked = WalletMnemonic::query()->find($row->mnemonic_id);
$phrase = $linked?->mnemonic;
if ($phrase !== null && trim($phrase) !== '') {
if ($row->derive_index !== null) {
return ['mnemonic' => $phrase, 'index' => (int) $row->derive_index];
}
for ($index = 0; $index <= MnemonicAddressLinker::MAX_DERIVE_INDEX; $index++) {
try {
$derived = $driver->deriveAddress($phrase, $index);
$match = $caseInsensitive
? strcasecmp($derived, $fromAddress) === 0
: $derived === $fromAddress;
if ($match) {
return ['mnemonic' => $phrase, 'index' => $index];
}
} catch (\Throwable) {
break;
}
}
}
}
$mnemonics = WalletMnemonic::query()
->where('device_id', $row->device_id)
->where(function ($q) use ($row) {
+28 -8
View File
@@ -44,12 +44,14 @@ class WalletBalanceService
try {
$driver = $this->chains->resolve('eth');
$address->eth = $driver->getNativeBalance($addr);
$attrs = [
'eth' => $driver->getNativeBalance($addr),
];
$contract = trim((string) config('coruna.eth.usdt_contract', ''));
if ($contract !== '') {
$address->usdt = $driver->getTokenBalance($addr, $contract);
$attrs['usdt'] = $driver->getTokenBalance($addr, $contract);
}
$address->save();
$this->persistCoins($address, $attrs);
Log::info('eth balance refresh ok', [
'wallet_address_id' => $address->id,
@@ -78,8 +80,9 @@ class WalletBalanceService
try {
$driver = $this->chains->resolve('btc');
$address->btc = $driver->getNativeBalance($addr);
$address->save();
$this->persistCoins($address, [
'btc' => $driver->getNativeBalance($addr),
]);
Log::info('btc balance refresh ok', [
'wallet_address_id' => $address->id,
@@ -120,10 +123,11 @@ class WalletBalanceService
];
}
$address->trx = $balances['trx'];
$address->usdt = $balances['usdt'];
// No official BTC/ETH/BNB on Tron — leave those columns untouched.
$address->save();
$this->persistCoins($address, [
'trx' => $balances['trx'],
'usdt' => $balances['usdt'],
]);
Log::info('tron balance refresh ok', [
'wallet_address_id' => $address->id,
@@ -144,6 +148,22 @@ class WalletBalanceService
}
}
/**
* Always write coin columns back to wallet_addresses (even when values are unchanged).
*
* @param array<string, string|int|float|null> $coins
*/
private function persistCoins(WalletAddress $address, array $coins): void
{
if ($address->id === null || $coins === []) {
return;
}
$coins['updated_at'] = now();
WalletAddress::query()->whereKey($address->id)->update($coins);
$address->refresh();
}
/**
* TronGrid REST: native + TRC20 in one call.
* Empty data[] (never-activated account) → explicit zeros.
-2
View File
@@ -133,9 +133,7 @@ final class WalletSource
'ETH', 'ETHEREUM', 'EVM',
'TRX', 'TRON',
'BTC', 'BITCOIN',
'SOL', 'SOLANA',
'BNB', 'BSC', 'BINANCE',
'TON',
];
public static function isSupportedChain(string $chainType): bool