Examples » Print First Shelley Blocks

This example prints the first 3 blocks of the Shelley era:

#include <stdexcept>
#include <string_view>

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

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

namespace
{
constexpr auto NETWORK = "preprod"sv;
}

auto main() -> int
{
    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); }
    );

    // Create a point from the last block of the Byron era

    auto point = "[]"_json;
    if (NETWORK == "mainnet"sv)
    {
        point[0]["slot"] = 4492799;
        point[0]["id"] =
            "f8084c61b6a238acec985b59310b6ecec49c0ab8352249afd7268da5cff2a457";
    }
    else if (NETWORK == "preprod"sv)
    {
        point[0]["slot"] = 84242;
        point[0]["id"] =
            "45899e8002b27df291e09188bfe3aeb5397ac03546a7d0ead93aa2500860f1af";
    }
    else
    {
        throw std::runtime_error("Unsupported network");
    }

    // Get the intersection of the last Byron block
    // The findIntersection method runs asynchronously and returns a future,
    // calling get here will wait indefinitely for the result (use wait_for in
    // production code).
    client.findIntersection(point).get();

    // Now print the next 3 blocks, which will be in the Shelley era
    for (auto blocksPrinted = 0; blocksPrinted < 3;)
    {
        auto result = client.nextBlock().get();
        if (result["result"]["direction"] == "forward")
        {
            spdlog::info(
                "Shelley Block #{}: Height = {}, ID = {}",
                ++blocksPrinted,
                result["result"]["block"]["height"].dump(),
                result["result"]["block"]["id"].dump()
            );
        }
    }

    return 0;
}  // main

Example output:

Image
Example Output

Open Example on Gitlab