### Install and Run Examples Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/INDEX.md Instructions for setting up the project, configuring environment variables, building the project, and running various examples. ```bash # Setup npm install export OGMIOS_HOST=localhost OGMIOS_PORT=1337 # Build npm run build # Run examples npm run local-state-query # Query blockchain state npm run local-chain-sync # Stream blocks npm run local-mempool-monitor # Monitor mempool (infinite loop) ``` -------------------------------- ### Build and Run Ogmios Examples Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/README.md Commands to install dependencies, build the TypeScript project, and run specific examples for Ogmios protocols. ```bash npm install npm run build # Compile TypeScript npm run local-state-query # Run examples npm run local-chain-sync npm run local-mempool-monitor ``` -------------------------------- ### Run Local Chain Sync Example Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/overview.md Builds the project and then executes the local chain sync example script. ```bash npm run build && node dist/local-chain-sync.js ``` -------------------------------- ### Run Local Mempool Monitor Example Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/overview.md Builds the project and then executes the local mempool monitoring example script. ```bash npm run build && node dist/local-mempool-monitor.js ``` -------------------------------- ### Run Local State Query Example Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/overview.md Builds the project and then executes the local state query example script. ```bash npm run build && node dist/local-state-query.js ``` -------------------------------- ### Run Local Chain Sync Example Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/README.md Execute the local chain sync example script. This script connects to Ogmios using the Local-Chain-Sync mini-protocol to synchronize chain state by pulling block data. Note: This example does not terminate automatically. ```sh yarn local-chain-sync ``` -------------------------------- ### Install and Build Ogmios Client Starter Kit Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/quick-reference.md Clone the repository, install dependencies, set environment variables for Ogmios host and port, and compile the TypeScript code. ```bash git clone https://github.com/CardanoSolutions/ogmios-client-starter-kit.git cd ogmios-client-starter-kit npm install export OGMIOS_HOST=localhost export OGMIOS_PORT=1337 npm run build ``` -------------------------------- ### Run Chain Synchronization Example Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/chain-synchronization.md Executes a complete chain synchronization example. Connects to Ogmios and streams blocks from the network. This example does not terminate automatically and requires manual stopping. ```typescript export async function runExample() ``` ```typescript import { runExample } from './local-chain-sync'; // Start synchronizing blocks await runExample(); // Logs roll-forward and roll-backward events as they arrive ``` -------------------------------- ### Context Setup Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/quick-reference.md Establishes a connection context to Ogmios using environment variables for host and port. ```APIDOC ## Context Setup ### Description Establishes a connection context to Ogmios using environment variables for host and port. ### Code ```typescript import { createContext } from './src/context'; const context = await createContext(); // Connects to Ogmios at OGMIOS_HOST:OGMIOS_PORT ``` ``` -------------------------------- ### Run Local Mempool Monitor Example Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/README.md Execute the local mempool monitor example script. This script fetches transactions from the node's mempool and continuously monitors for changes. It will not exit on its own. ```sh yarn local-mempool-monitor ``` -------------------------------- ### Complete State Query Example Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/quick-reference.md This example demonstrates how to connect to Ogmios, create a ledger state query client, and retrieve network block height and tip. Ensure you have the necessary context and client creation functions imported. ```typescript import { createContext } from './src/context'; import { createLedgerStateQueryClient } from '@cardano-ogmios/client'; async function main() { try { // 1. Connect const context = await createContext(); // 2. Create client const client = await createLedgerStateQueryClient(context); // 3. Query const height = await client.networkBlockHeight(); const tip = await client.networkTip(); // 4. Display console.log(`Height: ${height}`); console.log(`Tip: ${JSON.stringify(tip)}`); // 5. Cleanup client.shutdown(); } catch (error) { console.error('Error:', error.message); process.exit(1); } } main(); ``` -------------------------------- ### Run Ledger State Query Example Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/ledger-state-query.md Executes a complete example of state query operations. Connects to Ogmios, queries network state, and logs results. Ensure OGMIOS_HOST and OGMIOS_PORT environment variables are set. ```typescript import { runExample } from './local-state-query'; // Execute the example await runExample(); // Output: // === Network height // 12345 // // === Network tip // { // "id": "abc123...", // "slot": 99999 // } // // === Protocol parameters // { // "minFeeCoefficient": 44, // "minFeeConstant": 155381, // "maxTxSize": 16384, // ... // } ``` -------------------------------- ### Run Local State Query Example Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/README.md Execute the local state query example script. This script connects to Ogmios using the Local-State-Query mini-protocol for request/response semantics. ```sh yarn local-state-query ``` -------------------------------- ### Install Dependencies with Yarn Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/README.md Install project dependencies using yarn. This command is typically run after cloning the repository and setting up the development environment. ```sh yarn ``` -------------------------------- ### Run Mempool Monitoring Example Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/mempool-monitoring.md Executes a continuous mempool monitoring loop. Connects to Ogmios and periodically fetches and logs mempool state. This example never exits and must be stopped manually. ```typescript export async function runExample() ``` ```typescript import { runExample } from './local-mempool-monitor'; // Start monitoring the mempool (runs until interrupted) await runExample(); // Output: // Local mempool: { "bytes": ..., "transactions": ..., "capacity": ... } // Awaiting for changes in the mempool... // (repeats as transactions arrive/leave) ``` -------------------------------- ### Usage with Mempool Monitoring Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/context-setup.md Illustrates setting up a context and creating a mempool monitoring client. This example continuously acquires the mempool and logs the ID of each new transaction encountered. ```typescript import { createContext } from './context'; import { createMempoolMonitoringClient } from '@cardano-ogmios/client'; async function example() { const context = await createContext(); const client = await createMempoolMonitoringClient(context); while (true) { await client.acquireMempool(); const txId = await client.nextTransaction(); if (txId !== null) { console.log(`New transaction: ${txId}`); } } } ``` -------------------------------- ### Initialize Database Instance Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/chain-synchronization.md Instantiates the `Database` class to begin managing block data. This is the initial setup for the chain synchronization process. ```typescript const db = new Database(); ``` -------------------------------- ### Usage with Chain Synchronization Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/context-setup.md Shows how to set up a context and initialize a chain synchronization client. This example includes handlers for block roll-forward and rollback events, and resumes the synchronization process. ```typescript import { createContext } from './context'; import { createChainSynchronizationClient } from '@cardano-ogmios/client'; async function example() { const context = await createContext(); const client = await createChainSynchronizationClient(context, { rollForward: async (msg, next) => { console.log(`New block: ${msg.block.id}`); next(); }, rollBackward: async (msg, next) => { console.log(`Rollback to: ${msg.point}`); next(); }, }); await client.resume(); } ``` -------------------------------- ### Run Docker Compose Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/quick-reference.md This command starts the services defined in the docker-compose.yml file. ```bash docker-compose up ``` -------------------------------- ### Set Environment Variables for Local Chain Sync Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/configuration.md Sets OGMIOS_HOST and OGMIOS_PORT environment variables for the local-chain-sync example. Note that this example synchronizes from the network tip and does not resume from checkpoints. ```bash export OGMIOS_HOST=localhost export OGMIOS_PORT=1337 npm run local-chain-sync ``` -------------------------------- ### Slot Example Value Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/types.md Illustrates example values for a slot number on the Cardano timeline. The type can be a number or a bigint, depending on the context. ```plaintext 12345 12345n ``` -------------------------------- ### Demeter.run Environment Variables Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/configuration.md When running in a Demeter.run environment, Ogmios host and port are automatically configured via environment variables. No manual setup is required. ```bash OGMIOS_HOST= OGMIOS_PORT= ``` -------------------------------- ### Run Local Chain Synchronization Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/chain-synchronization.md Execute the local chain synchronization example using npm scripts. Ensure environment variables for Ogmios host and port are set, and an Ogmios instance is running and reachable with a fully synced Cardano Node. ```bash npm run local-chain-sync ``` ```bash npm run build node dist/local-chain-sync.js ``` -------------------------------- ### Dockerfile for Local Development Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/quick-reference.md This Dockerfile sets up the Node.js environment, copies project files, installs dependencies, builds the project, and configures environment variables for Ogmios connection. It specifies the command to run the local state query script. ```dockerfile FROM node:18 WORKDIR /app COPY . . RUN npm install && npm run build ENV OGMIOS_HOST=ogmios ENV OGMIOS_PORT=1337 CMD ["node", "dist/local-state-query.js"] ``` -------------------------------- ### Handle Connection Errors Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/INDEX.md Example of how to catch and log connection errors when establishing a context with the Ogmios client. ```typescript // Connection errors try { const context = await createContext(); } catch (error) { console.error('Connection failed:', error.message); } ``` -------------------------------- ### TransactionId Example Value Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/types.md An example of a transaction ID, represented as a blake2b-256 hash in hexadecimal format. This unique identifier is used for mempool monitoring. ```plaintext "abc123def456ghi789jkl012mno345pqr678stu901vwx234yz" ``` -------------------------------- ### Example Chain Synchronization Output Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/chain-synchronization.md Illustrates the expected output messages during chain synchronization, including 'Roll backward' for establishing a synchronization point or handling reorgs, and 'Roll forward' for new blocks. ```text Roll backward: {"id":"abc123...","slot":99999} Roll forward: {"id":"def456...","slot":100000,...} Roll forward: {"id":"ghi789...","slot":100001,...} Roll backward: {"id":"jkl012...","slot":99998} Roll forward: {"id":"mno345...","slot":99999,...} ``` -------------------------------- ### TypeScript Configuration for Ogmios Client Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/quick-reference.md Example tsconfig.json settings for building the Ogmios client. Ensure the module is set to CommonJS and the target is ES2017 for compatibility. ```json { "compilerOptions": { "module": "commonjs", "target": "es2017", "sourceDir": "src/", "outDir": "dist/" } } ``` -------------------------------- ### Set Environment Variables for Local State Query Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/configuration.md Sets OGMIOS_HOST and OGMIOS_PORT environment variables for the local-state-query example. Ensure these variables are exported before running the npm script. ```bash export OGMIOS_HOST=localhost export OGMIOS_PORT=1337 npm run local-state-query ``` -------------------------------- ### Monitor Cardano Mempool Transactions Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/quick-reference.md Initializes a mempool monitoring client to stream pending transactions. This example continuously acquires mempool data, logs each transaction, and reports the mempool size. ```typescript import { createMempoolMonitoringClient } from '@cardano-ogmios/client'; const client = await createMempoolMonitoringClient(context); while (true) { await client.acquireMempool(); let tx; while ((tx = await client.nextTransaction()) !== null) { console.log(`Transaction: ${tx}`); } const size = await client.sizeOfMempool(); console.log(`Mempool: ${size.transactions} tx, ${size.bytes} bytes`); } ``` -------------------------------- ### Set Environment Variables for Local Mempool Monitor Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/configuration.md Sets OGMIOS_HOST and OGMIOS_PORT environment variables for the local-mempool-monitor example. Ensure these variables are exported before running the npm script. ```bash export OGMIOS_HOST=localhost export OGMIOS_PORT=1337 npm run local-mempool-monitor ``` -------------------------------- ### Handle Protocol Errors Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/INDEX.md Example of how to catch and log errors that occur during network queries, such as fetching the block height. ```typescript // Protocol errors try { const height = await client.networkBlockHeight(); } catch (error) { console.error('Query failed:', error.message); } ``` -------------------------------- ### Database Pattern for Chain Synchronization Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/quick-reference.md This example shows a database pattern for handling chain synchronization events, including rolling forward with new blocks and rolling backward to a specific point. It requires a context and a chain synchronization client. ```typescript class Database { blocks = []; rollForward(block) { this.blocks.push(block); console.log(`Stored block ${block.id}, total: ${this.blocks.length}`); } rollBackward(point) { this.blocks = this.blocks.filter(b => b.slot <= point.slot); console.log(`Rolled back to slot ${point.slot}`); } } const db = new Database(); const client = await createChainSynchronizationClient(context, { rollForward: async ({ block }, next) => { db.rollForward(block); next(); }, rollBackward: async ({ point }, next) => { db.rollBackward(point); next(); } }); await client.resume(); ``` -------------------------------- ### Set Ogmios Host and Port Environment Variables Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/configuration.md Set these environment variables to configure the connection to your Ogmios instance. This is used for both Docker Compose and manual installations. ```bash export OGMIOS_HOST=localhost export OGMIOS_PORT=1337 ``` ```bash export OGMIOS_HOST= export OGMIOS_PORT= ``` -------------------------------- ### DigestBlake2B256 Example Value Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/types.md An example of a blake2b-256 hash digest, commonly used for block hashes and transaction IDs. This type is represented as a hexadecimal string. ```plaintext "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789" ``` -------------------------------- ### Set Up Ogmios Client Context Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/quick-reference.md Establishes a connection context to the Ogmios instance using environment variables for host and port. ```typescript import { createContext } from './src/context'; const context = await createContext(); // Connects to Ogmios at OGMIOS_HOST:OGMIOS_PORT ``` -------------------------------- ### Docker Configuration Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/configuration.md Set up a Dockerfile to build an image with the Ogmios client and configure environment variables for the Ogmios host and port. The CMD instruction specifies the entry point for the container. ```dockerfile FROM node:18 WORKDIR /app COPY . . RUN npm install && npm run build ENV OGMIOS_HOST=ogmios ENV OGMIOS_PORT=1337 CMD ["node", "dist/local-state-query.js"] ``` -------------------------------- ### Docker Build and Run Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/configuration.md Build a Docker image for the Cardano sync application and then run the container, specifying the Ogmios host via an environment variable. The `--network host` flag is used for direct network access. ```bash docker build -t cardano-sync . docker run --network host -e OGMIOS_HOST=localhost cardano-sync ``` -------------------------------- ### Basic Usage: Create Context and Query State Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/context-setup.md Demonstrates basic usage by creating a context, initializing a ledger state query client, and fetching the network block height. Ensure the context is properly created before client initialization. ```typescript import { createContext } from './context'; import { createLedgerStateQueryClient } from '@cardano-ogmios/client'; async function example() { const context = await createContext(); const client = await createLedgerStateQueryClient(context); const height = await client.networkBlockHeight(); console.log(`Block height: ${height}`); client.shutdown(); } ``` -------------------------------- ### Create Mempool Monitoring Client Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/configuration.md Initialize the Mempool Monitoring Client. Similar to the Ledger State Query Client, no specific configuration object is typically passed. ```typescript const client = await createMempoolMonitoringClient(context); // No configuration object is typically passed ``` -------------------------------- ### Create Ledger State Query Client Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/configuration.md Initialize the Ledger State Query Client. No specific configuration object is typically passed during creation. ```typescript const client = await createLedgerStateQueryClient(context); // No configuration object is typically passed ``` -------------------------------- ### Testnet Configuration Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/configuration.md Configure the Ogmios client to connect to a testnet instance using specific host and port settings. Then, run a local chain sync. ```bash export OGMIOS_HOST=testnet-ogmios.example.com export OGMIOS_PORT=6001 npm run local-chain-sync ``` -------------------------------- ### Local Development Configuration Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/configuration.md Configure Ogmios connection details for local development using environment variables. Then, build and run a local state query. ```bash export OGMIOS_HOST=127.0.0.1 export OGMIOS_PORT=1337 npm run build npm run local-state-query ``` -------------------------------- ### Ogmios Host and Port Configuration Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/quick-reference.md Set these environment variables to specify the Ogmios instance to connect to. OGMIOS_HOST is required for the hostname or IP address, and OGMIOS_PORT is required for the port number. ```bash OGMIOS_HOST= # Required: Ogmios hostname/IP OGMIOS_PORT= # Required: Ogmios port (integer) ``` -------------------------------- ### Set OGMIOS_HOST and OGMIOS_PORT Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/configuration.md Ensure that both OGMIOS_HOST and OGMIOS_PORT environment variables are set correctly to establish a connection. Verify they are set using `env | grep OGMIOS`. ```bash export OGMIOS_HOST=localhost export OGMIOS_PORT=1337 # Verify they are set env | grep OGMIOS ``` -------------------------------- ### Type Casting Block to BlockPraos Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/types.md Illustrates type casting a generic Block to a BlockPraos variant, as might be used in chain synchronization examples. This allows access to era-specific properties like slot. ```typescript const block: Block = ...; const praosBlock = block as BlockPraos; console.log(praosBlock.slot); ``` -------------------------------- ### Ogmios Configuration Reference Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/INDEX.md Details on required and optional environment variables for configuring the Ogmios client connection. ```bash # Required environment variables export OGMIOS_HOST=localhost # Ogmios hostname export OGMIOS_PORT=1337 # Ogmios port # Optional: For custom Ogmios instance export OGMIOS_HOST=example.com export OGMIOS_PORT=6001 ``` -------------------------------- ### createContext() Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/context-setup.md Creates and returns an Ogmios interaction context with error handling and connection lifecycle management. It configures the connection using environment variables `OGMIOS_HOST` and `OGMIOS_PORT` and sets up callbacks for connection errors and closure. ```APIDOC ## createContext() ### Description Creates and returns an Ogmios interaction context with error handling and connection lifecycle management. It configures the connection using environment variables `OGMIOS_HOST` and `OGMIOS_PORT` and sets up callbacks for connection errors and closure. ### Method `async` ### Signature `createContext(): Promise` ### Parameters None ### Return Type `Promise` Returns a promise that resolves to an interaction context object from `@cardano-ogmios/client`. This context encapsulates the WebSocket connection to the Ogmios instance and must be passed to client factory functions. ### Configuration Uses environment variables: - `OGMIOS_HOST` — hostname of the Ogmios instance - `OGMIOS_PORT` — port number of the Ogmios instance (parsed as base-10 integer) ### Error Handling - Connection errors are logged to `console.error()` - When the connection closes, a message is logged to `console.log()` ### Throws/Rejects - Rejects if the Ogmios instance is unreachable or the connection fails - Rejects if environment variables are not set or invalid - Rejects if port cannot be parsed as an integer ``` -------------------------------- ### Connect to Ogmios Instance Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/README.md Sets up an interaction context to establish a connection between the client and the Ogmios instance. It handles connection errors and closure events. Assumes OGMIOS_HOST and OGMIOS_PORT are set as environment variables. ```typescript import { createInteractionContext } from '@cardano-ogmios/client' const context = createInteractionContext( err => console.error(err), () => console.log("Connection closed."), { connection: { host: process.env.OGMIOS_HOST, port: parseInt(process.env.OGMIOS_PORT!) } } ); ``` -------------------------------- ### Create Mempool Monitoring Client Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/types.md Instantiate a client for monitoring transactions in the mempool. This client requires an existing InteractionContext. ```typescript import { createMempoolMonitoringClient } from '@cardano-ogmios/client'; const client = await createMempoolMonitoringClient(context); ``` -------------------------------- ### Run Local Mempool Monitor Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/mempool-monitoring.md Execute the local mempool monitor script. Ensure environment variables OGMIOS_HOST and OGMIOS_PORT are set, and an Ogmios instance is running and reachable. ```bash npm run local-mempool-monitor ``` ```bash npm run build node dist/local-mempool-monitor.js ``` -------------------------------- ### Create Context and Query Ledger State Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/ledger-state-query.md This snippet demonstrates the complete flow for querying ledger state. It includes creating a context, initializing a state query client, executing queries for block height, network tip, and protocol parameters, logging the results, and cleaning up resources. ```typescript import { createContext, createLedgerStateQueryClient } from "@cardano-ogmios/client"; import { handleBigInt } from "@cardano-ogmios/client/dist/utils"; const main = async () => { const context = await createContext({ // OGMIOS_HOST and OGMIOS_PORT are expected to be set as environment variables host: process.env.OGMIOS_HOST, port: parseInt(process.env.OGMIOS_PORT || "1337"), }); const client = createLedgerStateQueryClient(context); try { const networkBlockHeight = await client.networkBlockHeight(); console.log("Network Block Height:", networkBlockHeight); const networkTip = await client.networkTip(); console.log("Network Tip:", networkTip); const protocolParameters = await client.protocolParameters(); console.log("Protocol Parameters:", JSON.stringify(protocolParameters, handleBigInt, 2)); } catch (error) { console.error("Error querying ledger state:", error); } finally { await client.shutdown(); } }; main(); ``` -------------------------------- ### Configure CI/CD Environment Variables Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/configuration.md Sets OGMIOS_HOST and OGMIOS_PORT for deployment in CI/CD environments like GitHub Actions or GitLab CI. These variables are typically set directly in the CI/CD system's settings. ```bash # In GitHub Actions, GitLab CI, etc. OGMIOS_HOST=production-ogmios.example.com OGMIOS_PORT=6001 ``` -------------------------------- ### Verify Ogmios Host and Port Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/configuration.md Use these commands to check if Ogmios is running and accessible on the specified host and port. This helps diagnose 'Connection refused' errors. ```bash # Verify host and port nc -zv localhost 1337 # On Linux/Mac # or telnet localhost 1337 # Alternative ``` ```bash # Verify environment variables echo $OGMIOS_HOST echo $OGMIOS_PORT ``` -------------------------------- ### Create Chain Synchronization Client with Handlers Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/configuration.md Initialize the Chain Synchronization Client, passing a configuration object that includes handlers for rollForward and rollBackward events. The configuration is provided as the handlers object itself. ```typescript const client = await createChainSynchronizationClient(context, { rollForward: async ({ block }, requestNextBlock) => { /* ... */ }, rollBackward: async ({ point }, requestNextBlock) => { /* ... */ } }); // Configuration is the handlers object, not a separate options parameter ``` -------------------------------- ### Create Ledger State Query Client Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/types.md Instantiate a client for executing read-only queries about the blockchain state. This client requires an existing InteractionContext. ```typescript import { createLedgerStateQueryClient } from '@cardano-ogmios/client'; const client = await createLedgerStateQueryClient(context); ``` -------------------------------- ### Ogmios Connection Options Configuration Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/configuration.md Configure the connection options for the Ogmios client using environment variables. The host is a string, and the port is parsed as an integer. ```typescript const options = { connection: { host: process.env.OGMIOS_HOST, port: parseInt(process.env.OGMIOS_PORT, 10) } }; ``` -------------------------------- ### Load Environment Variables from .env File Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/configuration.md Loads OGMIOS_HOST and OGMIOS_PORT from a local .env file for development. This file should not be tracked by git. Source the file before running npm scripts. ```bash # .env (not tracked by git) OGMIOS_HOST=localhost OGMIOS_PORT=1337 ``` ```bash source .env npm run local-state-query ``` -------------------------------- ### Production Cluster Configuration Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/configuration.md Set environment variables for connecting to a production Ogmios instance, typically via a load balancer. Note that connection pooling is not included. ```bash export OGMIOS_HOST=ogmios-lb.prod.example.com export OGMIOS_PORT=443 # HTTPS WebSocket npm run local-state-query ``` -------------------------------- ### Create Chain Synchronization Client Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/types.md Create a client for streaming blocks from the blockchain. This client requires an InteractionContext and handler functions for block events. ```typescript import { createChainSynchronizationClient } from '@cardano-ogmios/client'; const client = await createChainSynchronizationClient(context, { rollForward: async (message, requestNext) => { ... }, rollBackward: async (message, requestNext) => { ... } }); ``` -------------------------------- ### Build Command using npm Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/configuration.md Run this command to compile TypeScript source files to JavaScript. It uses the 'tsc' command configured in tsconfig.json. ```bash npm run build # Runs: tsc # Compiles src/**/*.ts to dist/**/*.js ``` -------------------------------- ### Set Ogmios Host and Port Environment Variables Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/configuration.md Set the OGMIOS_HOST and OGMIOS_PORT environment variables to configure the connection to your Ogmios instance. The port is parsed as a base-10 integer. ```bash export OGMIOS_HOST=localhost export OGMIOS_PORT=1337 ``` ```bash export OGMIOS_HOST=ogmios.example.com export OGMIOS_PORT=6001 ``` -------------------------------- ### Docker Compose for Local Development Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/quick-reference.md This docker-compose.yml file defines services for Cardano Node, Ogmios, and the application. It configures volumes, ports, dependencies, and environment variables, including the socket path for the Cardano Node. ```yaml version: '3' services: cardano-node: image: ghcr.io/cardanosolutions/cardano-node:latest volumes: - node-data:/data ogmios: image: ghcr.io/cardanosolutions/ogmios:latest ports: - "1337:1337" depends_on: - cardano-node environment: CARDANO_NODE_SOCKET_PATH: /ipc/cardano-node.socket app: build: . depends_on: - ogmios ``` -------------------------------- ### Build TypeScript Project Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/overview.md Compiles TypeScript source files to JavaScript using the TypeScript compiler. ```bash npm run build ``` -------------------------------- ### Create a Point Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/types.md Demonstrates the construction of a Point object, which is used for rollback references. It requires an ID and a slot number. ```typescript const point: Point = { id: "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789", slot: 12345 }; ``` -------------------------------- ### Database Class Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/chain-synchronization.md A demonstration data store for managing blocks as they arrive via chain synchronization. It includes methods to add blocks, handle reorgs, and retrieve blocks. ```APIDOC ## Class: Database ### Description A demonstration data store for managing blocks as they arrive via chain synchronization. ### Constructor #### `constructor()` **Parameters:** None **Initializes:** `blocks` to an empty array. **Usage:** ```typescript const db = new Database(); ``` ### Methods #### `rollForward(block: Block): void` **Description:** Records a new block when the chain extends. **Parameters:** - `block` (Block) - Required - Block object from the blockchain **Return Type:** `void` **Behavior:** Appends the block to the `blocks` array. **Usage:** ```typescript const block = { id: "abc...", slot: 12345, ... }; db.rollForward(block); ``` #### `rollBackward(point: Point): void` **Description:** Handles chain reorg by removing blocks after a given point. **Parameters:** - `point` (Point) - Required - Reference point (contains `slot` and `id` fields) **Return Type:** `void` **Behavior:** Filters the blocks array to retain only blocks with `slot <= point.slot`. (Note: The current implementation has a bug — it uses `filter()` instead of reassigning, so it doesn't actually update the stored blocks.) **Usage:** ```typescript const point = { id: "abc...", slot: 9999 }; db.rollBackward(point); ``` #### `getBlock(point: Point): Block[]` **Description:** Retrieves blocks matching a point reference. **Parameters:** - `point` (Point) - Required - Reference point with `id` field **Return Type:** `Block[]` **Behavior:** Returns an array of blocks whose `id` matches the point's `id`. **Usage:** ```typescript const point = { id: "abc...", slot: 12345 }; const blocks = db.getBlock(point); ``` ``` -------------------------------- ### Create Ogmios Interaction Context Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/context-setup.md Creates and returns an Ogmios interaction context with error handling and connection lifecycle management. Configured using environment variables for host and port. Connection errors are logged to console.error and connection closures to console.log. ```typescript export const createContext = () => createInteractionContext( err => console.error(err), () => console.log("Connection closed."), { connection: { host: process.env.OGMIOS_HOST, port: parseInt(process.env.OGMIOS_PORT, 10) } } ); ``` -------------------------------- ### Docker Compose for Ogmios and Cardano Node Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/configuration.md Use this Docker Compose configuration to set up Ogmios and Cardano Node locally. Ensure the CARDANO_NODE_SOCKET_PATH environment variable is correctly set within the Ogmios service. ```yaml version: '3' services: cardano-node: image: ghcr.io/cardanosolutions/cardano-node:latest # ... node configuration ogmios: image: ghcr.io/cardanosolutions/ogmios:latest ports: - "1337:1337" depends_on: - cardano-node environment: CARDANO_NODE_SOCKET_PATH: /ipc/cardano-node.socket ``` -------------------------------- ### Stream Cardano Blocks and Handle Reorgs Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/quick-reference.md Sets up a chain synchronization client to stream blocks and handle rollbacks. Implement `rollForward` for new blocks and `rollBackward` for reorgs. Call `requestNext()` to continue streaming. ```typescript import { createChainSynchronizationClient } from '@cardano-ogmios/client'; const client = await createChainSynchronizationClient(context, { rollForward: async ({ block }, requestNext) => { console.log(`Block: ${block.id}`); requestNext(); }, rollBackward: async ({ point }, requestNext) => { console.log(`Reorg to: ${point.id}`); requestNext(); } }); await client.resume(); ``` -------------------------------- ### Basic Try-Catch for Queries Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/errors.md Use a try-catch block to handle potential errors during asynchronous operations like querying network block height. Ensure resources like clients are properly shut down. ```typescript async function safeQuery() { try { const context = await createContext(); const client = await createLedgerStateQueryClient(context); const height = await client.networkBlockHeight(); console.log(`Height: ${height}`); client.shutdown(); } catch (error) { console.error('Query failed:', error.message); process.exit(1); } } ``` -------------------------------- ### Create Interaction Context Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/types.md Obtain the main connection context for Ogmios. This context maintains the WebSocket connection and is passed to all client factory functions. ```typescript import { createInteractionContext } from '@cardano-ogmios/client'; const context = await createInteractionContext( errorCallback, closeCallback, options ); ``` -------------------------------- ### Query Cardano Network State Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/quick-reference.md Initializes a ledger state query client to retrieve network block height, tip, and protocol parameters. Remember to shut down the client when done. ```typescript import { createLedgerStateQueryClient } from '@cardano-ogmios/client'; const client = await createLedgerStateQueryClient(context); const height = await client.networkBlockHeight(); const tip = await client.networkTip(); const params = await client.protocolParameters(); client.shutdown(); ``` -------------------------------- ### Integrating Winston Logger with Ogmios Context Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/errors.md Replace default console logging with a structured logger like Winston. This snippet shows how to pass a logger instance to the `createInteractionContext` function for better error reporting and application monitoring. ```typescript import { Logger } from 'winston'; // or pino, bunyan, etc. const logger = new Logger(); createInteractionContext( err => logger.error('Ogmios error:', err), () => logger.info('Connection closed'), { /* ... */ } ); ``` -------------------------------- ### Create Roll Forward Handler Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/chain-synchronization.md Factory function to create a handler for block arrival events. It logs the block, stores it in the database, and requests the next block. ```typescript const rollForward = (db: Database) => async ({ block }: { block: Block }, requestNextBlock: () => void) => { console.log(`Roll forward: ${JSON.stringify(block, replacer)}`); db.rollForward(block); requestNextBlock(); } ``` -------------------------------- ### External Client APIs Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/INDEX.md Client APIs provided by '@cardano-ogmios/client' for specific Ogmios functionalities. ```APIDOC ## LedgerStateQueryClient ### Description Client for querying the current ledger state, including network tip and protocol parameters. ### Creation `createLedgerStateQueryClient(context: InteractionContext)` ### Key Methods - `networkBlockHeight()`: Gets the current block height of the network. - `networkTip()`: Gets the current tip of the network. - `protocolParameters()`: Retrieves the current protocol parameters. - `shutdown()`: Closes the connection for this client. ``` ```APIDOC ## ChainSynchronizationClient ### Description Client for synchronizing with the blockchain by streaming blocks. ### Creation `createChainSynchronizationClient(context: InteractionContext, handlers: any)` ### Key Methods - `resume()`: Resumes the block streaming. - `shutdown()`: Closes the connection for this client. ``` ```APIDOC ## MempoolMonitoringClient ### Description Client for monitoring the transaction mempool. ### Creation `createMempoolMonitoringClient(context: InteractionContext)` ### Key Methods - `acquireMempool()`: Acquires the current mempool contents. - `nextTransaction()`: Retrieves the next transaction from the mempool. - `sizeOfMempool()`: Gets the current size of the mempool. - `shutdown()`: Closes the connection for this client. ``` -------------------------------- ### Validate Environment Variables Before Execution Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/configuration.md A bash script to validate that OGMIOS_HOST and OGMIOS_PORT are set before building and running the application. Exits with an error if variables are not set. ```bash #!/bin/bash [ -z "$OGMIOS_HOST" ] && echo "Error: OGMIOS_HOST not set" && exit 1 [ -z "$OGMIOS_PORT" ] && echo "Error: OGMIOS_PORT not set" && exit 1 npm run build && node dist/local-state-query.js ``` -------------------------------- ### Retrieve Blocks by Point Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/chain-synchronization.md Fetches blocks from the database that match a given reference point. This is useful for querying specific blocks or chain segments. ```typescript const point = { id: "abc...", slot: 12345 }; const blocks = db.getBlock(point); ``` -------------------------------- ### Chain Synchronization Handler Signatures Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/types.md Illustrates the expected signatures for the `rollForward` and `rollBackward` handler functions used when creating a ChainSynchronizationClient. ```typescript rollForward: (message: {block: Block}, requestNextBlock: () => void) => Promise rollBackward: (message: {point: Point}, requestNextBlock: () => void) => Promise ``` -------------------------------- ### TypeScript Compiler Options (tsconfig.json) Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/configuration.md Configure the TypeScript compiler options for the project. This file specifies module format, target ECMAScript version, module interop, and source/output directories. ```json { "compilerOptions": { "module": "commonjs", "target": "es2017", "esModuleInterop": true, "rootDir": "./src", "outDir": "./dist" } } ``` -------------------------------- ### Graceful Shutdown with SIGINT Handler Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/errors.md Handle the SIGINT signal (Ctrl+C) to gracefully shut down the Ogmios client and exit the process. This pattern ensures resources are released properly during termination. ```typescript let client; process.on('SIGINT', async () => { console.log('Shutting down...'); if (client) { client.shutdown(); } process.exit(0); }); async function main() { const context = await createContext(); client = await createMempoolMonitoringClient(context); while (true) { try { await client.acquireMempool(); const size = await client.sizeOfMempool(); console.log(`Mempool: ${size.transactions} tx`); } catch (error) { console.error('Mempool error:', error); } } } main().catch(err => { console.error('Fatal error:', err); process.exit(1); }); ``` -------------------------------- ### MempoolMonitoringClient Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/types.md A client for monitoring transactions in the mempool. It allows acquiring exclusive access, fetching the next transaction, and querying mempool metrics. ```APIDOC ## MempoolMonitoring.MempoolMonitoringClient ### Description A client for monitoring transactions in the mempool. It allows acquiring exclusive access, fetching the next transaction, and querying mempool metrics. ### Key Methods - `acquireMempool(): Promise` — Acquire exclusive mempool access - `nextTransaction(): Promise` — Get next pending transaction - `sizeOfMempool(): Promise` — Query mempool metrics - `shutdown(): void` — Close the client ### Creation ```typescript import { createMempoolMonitoringClient } from '@cardano-ogmios/client'; const client = await createMempoolMonitoringClient(context); ``` ``` -------------------------------- ### Track New Transactions Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/mempool-monitoring.md Continuously monitor the mempool for new transactions. This snippet connects to Ogmios, acquires the mempool state, and logs the ID of each new transaction encountered. ```typescript const client = await createMempoolMonitoringClient(context); while (true) { await client.acquireMempool(); const txId = await client.nextTransaction(); if (txId) { console.log(`New transaction: ${txId}`); } } ``` -------------------------------- ### State Queries Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/quick-reference.md Provides methods to query read-only blockchain state such as network block height, tip, and protocol parameters. ```APIDOC ## State Queries (Read-Only) ### Description Provides methods to query read-only blockchain state such as network block height, tip, and protocol parameters. ### Code ```typescript import { createLedgerStateQueryClient } from '@cardano-ogmios/client'; const client = await createLedgerStateQueryClient(context); const height = await client.networkBlockHeight(); const tip = await client.networkTip(); const params = await client.protocolParameters(); client.shutdown(); ``` ``` -------------------------------- ### Check for Missing OGMIOS_HOST Environment Variable Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/errors.md Validate that the OGMIOS_HOST environment variable is set before attempting to establish a connection. This prevents errors related to an undefined hostname. ```typescript if (!process.env.OGMIOS_HOST) { throw new Error('OGMIOS_HOST environment variable is not set'); } ``` -------------------------------- ### Main Mempool Monitoring Loop Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/mempool-monitoring.md This TypeScript code continuously monitors the local mempool. It acquires access, flushes pending transactions, retrieves mempool size, logs the combined data, and then waits for the next mempool change before repeating. ```typescript while (true) { await client.acquireMempool(); const transactions = await flushMempool(client); const capacity = await client.sizeOfMempool(); console.log(`Local mempool: ${JSON.stringify({ ...capacity, transactions }, null, 2)}`); console.log(`Awaiting for changes in the mempool...`); } ``` -------------------------------- ### Query Network Tip Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/ledger-state-query.md Retrieve the current tip of the blockchain, which includes the hash and slot of the most recently confirmed block. ```typescript client.networkTip() ``` -------------------------------- ### Exported Classes Source: https://github.com/cardanosolutions/ogmios-ts-client-starter-kit/blob/main/_autodocs/INDEX.md Classes available for interacting with chain data. ```APIDOC ## Database Class ### Description Provides methods for interacting with chain data, including rolling forward, backward, and retrieving specific blocks. ### Module `local-chain-sync` ### Methods - `rollForward()`: Advances the chain synchronization. - `rollBackward()`: Reverts the chain synchronization. - `getBlock(point: Point)`: Retrieves a specific block by its reference. ```