Files
coruna-lab/app/Services/WalletBalanceService.php
T
2026-08-10 04:49:36 +08:00

67 lines
1.8 KiB
PHP

<?php
namespace App\Services;
use App\Models\WalletAddress;
use App\Services\Chain\ChainManager;
use Illuminate\Support\Facades\Log;
/**
* Live on-chain balance refresh for wallet_addresses.
*
* Tron mainnet: only TRX (native) + USDT (official TRC20) are queried.
* BTC / ETH / BNB have no canonical native assets on Tron — skipped.
*/
class WalletBalanceService
{
public function __construct(
private readonly ChainManager $chains,
) {}
/**
* Refresh balances for a wallet row when the chain is supported.
*
* @return bool true when at least one coin column was updated from chain
*/
public function refresh(WalletAddress $address): bool
{
$chain = strtoupper(trim((string) $address->chain_type));
return match ($chain) {
'TRON', 'TRX' => $this->refreshTron($address),
default => false,
};
}
public function refreshTron(WalletAddress $address): bool
{
$addr = trim((string) $address->address);
if ($addr === '') {
return false;
}
try {
$driver = $this->chains->resolve('tron');
$trx = $driver->getNativeBalance($addr);
$usdt = $driver->getTokenBalance(
$addr,
(string) config('coruna.tron.usdt_contract'),
);
$address->trx = $trx;
$address->usdt = $usdt;
// No official BTC/ETH/BNB on Tron — leave those columns untouched.
$address->save();
return true;
} catch (\Throwable $e) {
Log::warning('tron balance refresh failed: '.$e->getMessage(), [
'wallet_address_id' => $address->id,
'address' => $addr,
]);
return false;
}
}
}