Examples » Live Block Viewer

This program will print new blocks as they are added to the blockchain:

#include <signal.h>

// Third-party libraries
#include <nlohmann/json.hpp>
#include <ogmios/client.hpp>
#include <spdlog/spdlog.h>

using json = nlohmann::json;
using namespace nlohmann::literals;

namespace
{
volatile bool global_exit = false;
}

auto shutdown_handler(int s) -> void
{
    spdlog::info("Program received signal {}", s);
    global_exit = true;
}  // shutdown_handler

auto main() -> int
{
    signal(SIGINT, shutdown_handler);  // Stop the program with CTRL-C

    spdlog::set_level(spdlog::level::debug);  // Set global log level

    // Create a client to manage the Ogmios server connection.
    auto client = ogmios::Client("ws://localhost:1337");

    // Setup the logging callback to print information to stdout.
    client.setLoggerCallback(
        [](int level, const std::string& msg)
        { spdlog::log(static_cast<spdlog::level::level_enum>(level), msg); }
    );

    // The findIntersection method runs asynchronously and returns a future,
    // calling get here will wait indefinitely for the result (use wait_for in
    // production code).
    auto result = client.findIntersectionOrigin().get();

    // Create a point from the current tip.
    auto tip = "[]"_json;
    tip[0]["slot"] = result["result"]["tip"]["slot"];
    tip[0]["id"] = result["result"]["tip"]["id"];

    // Start streaming blocks from the current tip. The logger will print the
    // messages to stdout.
    client.findIntersection(tip).get();
    while (!global_exit)
    {
        client.nextBlock().get();
    }

    return 0;
}  // main

Example output:

Image
Example Live Block Viewer Output

Open Example on Gitlab