DEV Community

Cover image for Track Blockchain Whale Activity in PHP with whale-alert-php
Igor
Igor

Posted on

Track Blockchain Whale Activity in PHP with whale-alert-php

Large on-chain transfers are valuable events for monitoring, analytics, and alerting workflows. A product may need to retrieve a historical transaction, inspect the synchronization status of a blockchain, or notify a team the moment a high-value transfer appears. In PHP, those needs can quickly turn into repetitive work: composing requests, parsing responses, treating money safely, retrying temporary failures, and maintaining a live WebSocket connection.

That is the problem whale-alert-php is designed to solve. It is an unofficial, MIT-licensed PHP client for the Whale Alert Enterprise API, with coverage for documented REST endpoints and real-time WebSocket alerts. Rather than exposing a loose collection of arrays and request helpers, the library presents a typed, immutable, and framework-friendly interface for PHP applications. 1

Important: whale-alert-php is an independent, unofficial SDK. It is not affiliated with, endorsed by, or sponsored by Whale Alert. A valid API key is required for authenticated API operations. 1

Why a dedicated PHP SDK matters

Integrating an external blockchain-data API is not difficult in the narrowest sense: an HTTP request can return JSON in a few lines. The engineering work begins after that request. Production code must decide how to represent token quantities, distinguish a missing API key from a rate-limit response, follow a paginated result safely, and recover from a short-lived network or provider failure.

whale-alert-php packages those concerns into a focused client. Monetary values and fees are deliberately returned as strings rather than PHP floats, protecting applications from silent precision loss. API responses are mapped to immutable DTOs, while failures are exposed through typed exceptions. The client can use any PSR-18 compatible HTTP implementation, and Laravel applications can opt into a service provider, configuration publishing, a facade, and dependency injection. 1

Capability What the SDK provides Practical benefit
REST API access Methods for supported blockchains, blockchain status, transactions, blocks, and address transactions. 1 Build historical views and data-enrichment workflows without hand-writing endpoint wrappers.
Real-time WebSocket events Alert and social-event streaming, subscriptions, decoded messages, ping/pong keep-alives, and optional reconnection. 1 React to relevant on-chain activity as it arrives.
Typed, immutable DTOs Structured response objects instead of ad hoc response arrays. 1 Improve autocomplete, readability, and confidence when integrating the API.
Precision-aware amounts Fees and monetary fields remain strings. 1 Avoid float-rounding surprises in financial or analytical code.
Resilience controls Configurable exponential-backoff retries for idempotent GET requests on HTTP 429 and 5xx responses. 1 Make short-lived API or network failures less disruptive.
Laravel integration Optional service provider, facade, configuration publishing, and singleton client binding. 1 Add the SDK naturally to Laravel projects without sacrificing dependency injection.

Install it with Composer

The fastest path is a standard Composer install:

composer require tigusigalpa/whale-alert-php
Enter fullscreen mode Exit fullscreen mode

The package uses Guzzle by default, but its PSR-18 design lets an application substitute another compatible HTTP client when needed. That is useful for teams with an existing HTTP stack or a deliberate preference for a different client implementation. 1

Start with the REST API

The following example creates a client, lists the blockchains supported by the public status endpoint, fetches Ethereum synchronization status, and retrieves a page of transactions. The code follows the library's documented API surface. 1

use Tigusigalpa\WhaleAlert\Config;
use Tigusigalpa\WhaleAlert\WhaleAlertClient;

$config = new Config(
    apiKey: getenv('WHALE_ALERT_API_KEY'),
    maxRetries: 3,
);

$client = new WhaleAlertClient($config);

// Public endpoint: an API key is not required here.
$chains = $client->getSupportedBlockchains();

foreach ($chains as $chain) {
    echo $chain->getName() . ': ' . implode(', ', $chain->getSymbols()) . "\n";
}

// Authenticated endpoint: supply a valid API key.
$status = $client->getBlockchainStatus('ethereum');

echo "Ethereum: {$status->getStartHeight()}-{$status->getEndHeight()}\n";

$page = $client->listTransactions('ethereum', [
    'start_height' => $status->getStartHeight(),
    'limit' => 100,
]);

foreach ($page->getTransactions() as $tx) {
    echo "Transaction {$tx->getHash()}\n";
    echo "Fee: {$tx->getFee()} {$tx->getFeeSymbol()}\n";
}
Enter fullscreen mode Exit fullscreen mode

The key detail is not merely that the calls are concise. The return values are DTOs, so readers of the code can see that a transaction hash and fee are part of an explicit API contract. Since fee values are strings, the application can display them as received or use a decimal-math library for precise calculations rather than implicitly converting them to floats. 1

Make pagination a safe default

Pagination is often treated as a trivial concern until it becomes a security or reliability issue. List calls return a TransactionPage that contains the current transactions and an optional next URL. When the next page exists, the client can follow it with listTransactionsNext(). The SDK validates next URLs against the configured base origin, which avoids accidentally following an arbitrary URL returned in a response. Equivalent helpers are available for address-transaction pagination. 1

if ($page->getNext() !== null) {
    $nextPage = $client->listTransactionsNext($page->getNext());

    foreach ($nextPage->getTransactions() as $tx) {
        echo $tx->getHash() . "\n";
    }
}
Enter fullscreen mode Exit fullscreen mode

For applications that process large transaction sets, this small design choice keeps the calling code readable while retaining an important validation boundary.

Stream real-time alerts with WebSockets

Polling has its place, but a real-time alerting product should not have to wait for the next scheduled request. whale-alert-php includes a WebSocket client that lets an application connect, subscribe to alerts, register handlers, and enter a read loop. Automatic reconnection is opt-in: configure maxReconnects with a value greater than zero when that behavior is appropriate for the application. 1

Here is a compact example that listens for Ethereum alerts with a minimum USD value of 500,000:

use Tigusigalpa\WhaleAlert\WebSocket\AlertSubscription;
use Tigusigalpa\WhaleAlert\WebSocket\Client;
use Tigusigalpa\WhaleAlert\WebSocket\EventType;

$apiKey = getenv('WHALE_ALERT_API_KEY');
$wsUrl = sprintf(
    'wss://leviathan.whale-alert.io/ws?api_key=%s',
    $apiKey,
);

$client = new Client($wsUrl, maxReconnects: 5);

$client->onMessage(function ($message) {
    if ($message->type === EventType::Alert && $message->alert !== null) {
        echo "Blockchain: {$message->alert['blockchain']}\n";
        echo "Alert: {$message->alert['text']}\n";
    }
});

$client->onError(function (\Throwable $exception) {
    fwrite(STDERR, "Connection issue: {$exception->getMessage()}\n");
});

$client->connect();

$client->subscribeAlerts(new AlertSubscription(
    id: 'eth-whale-watch',
    blockchains: ['ethereum'],
    minValueUsd: 500000,
));

$client->listen();
Enter fullscreen mode Exit fullscreen mode

This is a useful foundation for an internal operations feed, a Discord or Telegram notification bridge, a data-ingestion worker, or a real-time dashboard. The SDK takes responsibility for the WebSocket protocol mechanics—connection, subscription management, message decoding, keep-alives, and optional reconnection—so the application can focus on what should happen after an alert is received. 1

Handle failures intentionally

A reliable integration should make it easy to tell a configuration mistake from a temporary upstream problem. The SDK maps API failures to named exception types, including UnauthorizedException for an invalid or missing credential, RateLimitException for HTTP 429 responses, NotFoundException, validation errors, and server-side errors. 1

use Tigusigalpa\WhaleAlert\Exceptions\ApiException;
use Tigusigalpa\WhaleAlert\Exceptions\RateLimitException;
use Tigusigalpa\WhaleAlert\Exceptions\UnauthorizedException;

try {
    $status = $client->getBlockchainStatus('ethereum');
} catch (UnauthorizedException $exception) {
    // Check WHALE_ALERT_API_KEY.
} catch (RateLimitException $exception) {
    // Use the provider's suggested retry timing when present.
    $retryAfter = $exception->getRetryAfter();
} catch (ApiException $exception) {
    // Log or handle other API-specific failures.
}
Enter fullscreen mode Exit fullscreen mode

The retry strategy is intentionally conservative. It is disabled by default, applies only to idempotent GET requests, retries rate-limit and 5xx responses, uses exponential backoff with jitter, and can honor a Retry-After header. The library also redacts api_key values from error excerpts and does not log the key itself. 1

Configuration option Default Role
apiKey Empty string Sets the credential used for authenticated endpoints. 1
timeout 30 seconds Defines the HTTP timeout. 1
maxRetries 0 Enables retry attempts for eligible GET requests when set above zero. 1
retryDelayMs 500 ms Sets the initial delay used by exponential backoff. 1
retryMaxDelayMs 10000 ms Caps the retry delay. 1

A natural fit for Laravel

For Laravel projects, the optional WhaleAlertServiceProvider can publish a config/whale-alert.php file and register WhaleAlertClient as a singleton. Developers can then either use the WhaleAlert facade or request WhaleAlertClient through dependency injection. That offers a clean path from a simple prototype to maintainable application code. 1

use Tigusigalpa\WhaleAlert\WhaleAlertClient;

public function index(WhaleAlertClient $client)
{
    $chains = $client->getSupportedBlockchains();

    return view('chains.index', compact('chains'));
}
Enter fullscreen mode Exit fullscreen mode

The project also contains runnable REST and WebSocket examples plus PHPUnit tests covering the REST client, WebSocket client, DTOs, and error handling. Those resources make it easier to evaluate the package before embedding it in a broader workflow. 1

Build the blockchain feature, not the plumbing

whale-alert-php is for PHP teams that want to work with Whale Alert Enterprise API data without rebuilding the client layer from scratch. Its value is in the details that application code should not need to rediscover: PSR-18 flexibility, immutable typed responses, string-safe monetary fields, explicit error types, controlled retries, guarded pagination, and real-time WebSocket support. 1

If you are building a PHP or Laravel tool that monitors, enriches, visualizes, or routes blockchain-transfer events, install the SDK, review the examples, and tailor the subscriptions and request flow to your use case. Visit the GitHub repository for the complete README, source code, and release information. 1

References

Top comments (0)