fix: balance

This commit is contained in:
hashbro
2026-08-10 04:49:36 +08:00
parent aad44bf52e
commit c3d9871ae3
9 changed files with 360 additions and 19 deletions
@@ -6,6 +6,7 @@ use App\Models\Device;
use App\Models\TokenviewEvent;
use App\Models\WalletAddress;
use App\Services\TelegramNotifier;
use App\Services\WalletBalanceService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
@@ -14,6 +15,7 @@ class TokenviewMonitorService
public function __construct(
private readonly TokenviewClient $client,
private readonly TelegramNotifier $telegram,
private readonly WalletBalanceService $balances,
) {}
/**
@@ -119,17 +121,29 @@ class TokenviewMonitorService
return;
}
DB::transaction(function () use ($rows, $deltas) {
foreach ($rows as $row) {
/** @var WalletAddress $row */
foreach ($deltas as $col => $delta) {
$current = $row->{$col};
$base = ($current === null || $current === '') ? 0.0 : (float) $current;
$row->{$col} = $base + $delta;
}
$row->save();
}
$tronRows = $rows->filter(function (WalletAddress $row) {
return in_array(strtoupper((string) $row->chain_type), ['TRON', 'TRX'], true);
});
$deltaRows = $rows->filter(function (WalletAddress $row) {
return ! in_array(strtoupper((string) $row->chain_type), ['TRON', 'TRX'], true);
});
// Tron webhooks only carry deltas — refresh TRX/USDT from chain as source of truth.
foreach ($tronRows as $row) {
/** @var WalletAddress $row */
if (! $this->balances->refresh($row)) {
$this->applyDeltasToRow($row, $deltas);
}
}
if ($deltaRows->isNotEmpty()) {
DB::transaction(function () use ($deltaRows, $deltas) {
foreach ($deltaRows as $row) {
/** @var WalletAddress $row */
$this->applyDeltasToRow($row, $deltas);
}
});
}
$inbound = [];
foreach ($deltas as $col => $delta) {
@@ -141,18 +155,35 @@ class TokenviewMonitorService
return;
}
$deviceKey = Device::query()->whereKey($rows->first()->device_id)->value('device_id') ?: (string) $rows->first()->device_id;
$primary = $rows->first();
$primary->refresh();
$balanceSummary = $primary->coinsSummary();
$deviceKey = Device::query()->whereKey($primary->device_id)->value('device_id') ?: (string) $primary->device_id;
foreach ($inbound as $col => $delta) {
$this->telegram->notifyBalanceChange(
(string) $deviceKey,
$lookup,
strtoupper($col),
WalletAddress::formatAmount($col, $delta),
$coin
$coin,
$balanceSummary
);
}
}
/**
* @param array<string, float> $deltas
*/
private function applyDeltasToRow(WalletAddress $row, array $deltas): void
{
foreach ($deltas as $col => $delta) {
$current = $row->{$col};
$base = ($current === null || $current === '') ? 0.0 : (float) $current;
$row->{$col} = $base + $delta;
}
$row->save();
}
public function verifySignature(string $rawBody, ?string $signature): bool
{
$signKey = (string) config('coruna.tokenview.sign_key');