PHP code example of dev404ai / drand-client-php

1. Go to this page and download the library: Download dev404ai/drand-client-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

dev404ai / drand-client-php example snippets




use Drand\Client\DrandClient;

// Create a client with default settings
$client = DrandClient::createDefault();

// Get the latest beacon (scheme is detected and verified automatically)
$beacon = $client->getLatestBeacon();
printf("Round %d: %s\n", $beacon->getRound(), $beacon->getRandomness());

// Get a specific round
$beacon = $client->getBeacon(12345);

// Get chain information
$chain = $client->getChain();
printf("Chain period: %d seconds\n", $chain->getPeriod());
printf("Signature scheme: %s\n", $chain->getSchemeID());

// Create a client with custom options
$client = DrandClient::createDefault(
    'https://api.drand.sh',  // Base URL
    [
        // Disable signature verification (not recommended for production)
        'disableBeaconVerification' => false,
        
        // Disable response caching
        'noCache' => false,
        
        // Verify chain hash and public key
        'chainVerificationParams' => [
            'chainHash' => '8990e7a9aaed2ffed73dbd7092123d6f289930540d7651336225dc172e51b2ce',
            'publicKey' => '868f005eb8e6e4ca0a47c8a77ceaa5309a47978a7c71bc5cce96366b5d7a569937c529eeda66c7293784a9402801af31'
        ],
        
        // HTTP request timeout in seconds
        'timeout' => 10
    ],
    true,           // Enable caching (default)
    300,            // Chain info cache TTL (5 minutes)
    30              // Beacon cache TTL (30 seconds)
);

// Get the round number for a specific time
$roundNumber = $client->roundAt(time() + 3600); // Round an hour from now

// Get the time when a round will be available
$roundTime = $client->roundTime(12345);
$whenAvailable = new DateTime("@$roundTime");

// Calculate current round
$currentRound = $client->roundAt();

try {
    $beacon = $client->getLatestBeacon();
} catch (\RuntimeException $e) {
    // Handle HTTP errors, verification failures, etc.
    error_log("Failed to get beacon: " . $e->getMessage());
} catch (\InvalidArgumentException $e) {
    // Handle invalid parameters
    error_log("Invalid parameters: " . $e->getMessage());
}

use Drand\Client\HttpClient;
use Drand\Client\CachingHttpClient;

// Create HTTP client with caching
$httpClient = new HttpClient('https://api.drand.sh');
$cachingClient = new CachingHttpClient(
    $httpClient,
    300,  // Chain info TTL (5 minutes)
    30    // Beacon TTL (30 seconds)
);

// Clear cache if needed
$cachingClient->clearCache();

use Drand\Client\HttpClient;
use Drand\Client\MultiChainClient;

// Create clients for different drand networks
$mainnet = new HttpClient('https://api.drand.sh');
$testnet = new HttpClient('https://pl-us.testnet.drand.sh');

// Combine them into a MultiChainClient
$multi = new MultiChainClient([$mainnet, $testnet]);

// Select by chain hash or beaconID
$mainnetClient = $multi->forChainHash('8990e7a9aaed2ffed73dbd7092123d6f289930540d7651336225dc172e51b2ce');
$testnetClient = $multi->forBeaconID('default');

// Use as a regular client (default is the first one)
$beacon = $multi->getLatestBeacon();

use Drand\Client\HttpClient;
use Drand\Client\FastestNodeClient;

// Create clients for several public endpoints
$clients = [
    new HttpClient('https://api.drand.sh'),
    new HttpClient('https://drand.cloudflare.com'),
    new HttpClient('https://drand.cloudflare.com/public')
];

// FastestNodeClient will always use the fastest node (auto-updated)
$fastest = new FastestNodeClient($clients);

$beacon = $fastest->getLatestBeacon();
printf("Fastest node randomness: %s\n", $beacon['randomness']);

use Drand\Client\DrandClient;
use Drand\Client\Networks;

// Mainnet
$client = DrandClient::createDefault(
    Networks::MAINNET['url'],
    [
        'chainVerificationParams' => Networks::MAINNET['chainVerificationParams']
    ]
);

// Testnet
$client = DrandClient::createDefault(
    Networks::TESTNET['url'],
    [
        'chainVerificationParams' => Networks::TESTNET['chainVerificationParams']
    ]
);

// Custom network
$client = DrandClient::createDefault(
    'https://your.custom.drand.node',
    [
        'chainVerificationParams' => [
            'chainHash' => 'your_chain_hash',
            'publicKey' => 'your_public_key'
        ]
    ]
);

$round = $client->roundAt(time());
$beacon = $client->getBeacon($round);
printf("Randomness for round %d: %s\n", $round, $beacon->getRandomness());

$round = 1000000;
$timestamp = $client->roundTime($round);
echo "Round $round will be available at: " . date('c', $timestamp) . "\n";

$chain = $client->getChain();
echo "Chain hash: " . $chain->getHash() . "\n";
echo "Signature scheme: " . $chain->getSchemeID() . "\n";

use Drand\Client\MultiChainClient;
use Drand\Client\HttpClient;
use Drand\Client\DrandClient;

$mainnet = new HttpClient(Drand\Client\Networks::MAINNET['url']);
$testnet = new HttpClient(Drand\Client\Networks::TESTNET['url']);
$multi = DrandClient::createMultiChain([$mainnet, $testnet]);

// Select mainnet by beaconID
$mainnetClient = $multi->getChain()->getHash() === Drand\Client\Networks::MAINNET['chainVerificationParams']['chainHash']
    ? $multi : null;
if ($mainnetClient) {
    $beacon = $mainnetClient->getBeacon(12345);
    echo "Mainnet randomness: " . $beacon->getRandomness() . "\n";
}

use Drand\Client\FastestNodeClient;

$clients = [
    new HttpClient('https://api.drand.sh'),
    new HttpClient('https://drand.cloudflare.com'),
];
$fastest = DrandClient::createFastestNode($clients);
$beacon = $fastest->getLatestBeacon();
echo "Fastest node randomness: " . $beacon->getRandomness() . "\n";

use Drand\Client\DrandClient;
use Drand\Client\Network;
use Drand\Client\VerificationMode;
use Drand\Client\CachePolicy;

$client = DrandClient::createDefault(
    Network::MAINNET->getDefaultUrl(),
    [
        'verificationMode' => VerificationMode::ENABLED,
        'cachePolicy' => CachePolicy::ENABLED,
        // 'chainVerificationParams' => ['chainHash' => '...', 'publicKey' => '...'],
    ]
);

$mainnet = new HttpClient(Network::MAINNET->getDefaultUrl());
$testnet = new HttpClient(Network::TESTNET->getDefaultUrl());
$multi = DrandClient::createMultiChain([
    $mainnet,
    $testnet,
], [
    'verificationMode' => VerificationMode::ENABLED
]);

$client = DrandClient::createFastestNode([
    new HttpClient(Network::MAINNET->getDefaultUrl()),
    new HttpClient(Network::TESTNET->getDefaultUrl()),
], [
    'verificationMode' => VerificationMode::ENABLED
]);
bash
# Permanent
echo "ffi.enable = true" | sudo tee /etc/php/conf.d/20-ffi.ini

# One‑off
php -dffi.enable=1 your_script.php
bash
composer 
bash
> php -m | grep ffi        # ffi
> php -r "new FFI(); echo 'FFI OK\n';"
>