lthn.io/app/Mod/Chain/Services/WalletRpc.php
Claude 1f29000c11
feat(chain): circuit breaker with stale cache fallback
- DaemonRpc: try/catch with stale cache (1h TTL) when daemon is down
- WalletRpc: try/catch with clear error message
- Health endpoint: status=offline/degraded/critical/low_funds/healthy
- Reports wallet_online, daemon_online, stale flags
- Reduced daemon timeout from 10s to 5s, wallet from 30s to 15s

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 03:06:23 +01:00

102 lines
2.6 KiB
PHP

<?php
declare(strict_types=1);
namespace Mod\Chain\Services;
use Illuminate\Support\Facades\Http;
/**
* $wallet = app(WalletRpc::class);
* $wallet->registerAlias('myname', $address, 'v=lthn1;type=user');
*/
class WalletRpc
{
private string $endpoint;
public function __construct()
{
$this->endpoint = config('chain.wallet_rpc', 'http://127.0.0.1:46944/json_rpc');
}
/**
* $result = $wallet->getAddress();
* // 'iTHNHN11xMe...'
*/
public function getAddress(): string
{
$result = $this->call('getaddress');
return $result['address'] ?? '';
}
/**
* $balance = $wallet->getBalance();
* // ['balance' => 1000000000000, 'unlocked_balance' => 1000000000000]
*/
public function getBalance(): array
{
return $this->call('getbalance');
}
/**
* $result = $wallet->registerAlias('myname', $address, 'v=lthn1;type=user');
* // ['status' => 'OK', 'tx_id' => 'abc123...']
*/
public function registerAlias(string $alias, string $address, string $comment = ''): array
{
return $this->call('register_alias', [
'al' => [
'alias' => strtolower(trim($alias)),
'address' => $address,
'comment' => $comment,
],
]);
}
/**
* $result = $wallet->updateAlias('myname', $address, 'v=lthn1;type=gateway');
*/
public function updateAlias(string $alias, string $address, string $comment = ''): array
{
return $this->call('update_alias', [
'al' => [
'alias' => strtolower(trim($alias)),
'address' => $address,
'comment' => $comment,
],
]);
}
/**
* $result = $wallet->call('get_recent_txs_and_info', [...]);
*/
public function call(string $method, array $params = []): array
{
$payload = [
'jsonrpc' => '2.0',
'id' => '0',
'method' => $method,
];
if ($params) {
$payload['params'] = $params;
}
try {
$response = Http::timeout(15)
->accept('application/json')
->post($this->endpoint, $payload);
} catch (\Throwable $e) {
return ['error' => 'Wallet RPC unreachable — ' . $e->getMessage()];
}
if ($response->failed()) {
return ['error' => 'Wallet RPC unreachable'];
}
$data = $response->json();
return $data['result'] ?? $data['error'] ?? [];
}
}