npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@greenlightcln/glsdk

v0.1.1

Published

Node.js bindings for Blockstream Greenlight SDK

Readme

Greenlight SDK - Node.js Bindings

Node.js bindings for Blockstream's Greenlight SDK using napi-rs.

Prerequisites

  • Node.js >= 16
  • Protocol Buffers compiler (protoc)

Installation

From npm

npm install @greenlightcln/glsdk

Building from source

  1. Clone the Greenlight repository:
git clone https://github.com/Blockstream/greenlight.git
cd greenlight
  1. Navigate to the napi bindings directory:
cd libs/gl-sdk-napi
  1. Install dependencies:
npm install
  1. Build the package:
npm run build

This will compile the Rust code and generate the Node.js native module.

Supported Platforms

Prebuilt binaries are available for the following platforms:

| OS | Architecture | Target | |---------|--------------|-----------------------------| | Linux | x64 | x86_64-unknown-linux-gnu | | Linux | arm64 | aarch64-unknown-linux-gnu | | macOS | x64 | x86_64-apple-darwin | | macOS | arm64 (M1/M2)| aarch64-apple-darwin | | Windows | x64 | x86_64-pc-windows-msvc |

For Unsupported Platforms:

  1. Follow the instructions in the Building from source section above.

  2. Then install the package from your local directory:

cd /path/to/your/project
npm install /path/to/greenlight/libs/gl-sdk-napi

Project Structure

gl-sdk-napi/
├── Cargo.toml          # Rust dependencies and configuration
├── package.json        # Node.js package configuration
├── src/
│   └── lib.rs          # Rust implementation of Node.js bindings
├── example.ts          # TypeScript usage examples
└── tests/              # Test file/s

Usage Example

Async/Await: All network operations are asynchronous. Always use await or handle returned promises properly to avoid unhandled rejections or unexpected behavior.

Streaming: streamNodeEvents() runs as a background task — call startEventStream(node) without await so it listens for events concurrently while your app continues calling other node methods. When you call node.stop(), next() returns null and the loop exits cleanly.

import { Scheduler, Signer, Node, Credentials, OnchainReceiveResponse, NodeEvent, NodeEventStream } from '@greenlightcln/glsdk';

type Network = 'bitcoin' | 'regtest';

class GreenlightApp {
  private credentials: Credentials | null = null;
  private scheduler: Scheduler;
  private signer: Signer;
  private node: Node | null = null;

  constructor(phrase: string, network: Network) {
    this.scheduler = new Scheduler(network);
    this.signer = new Signer(phrase);
    console.log(`✓ Signer created. Node ID: ${this.signer.nodeId().toString('hex')}`);
  }

  async registerOrRecover(inviteCode?: string): Promise<void> {
    try {
      console.log('Attempting to register node...');
      this.credentials = await this.scheduler.register(this.signer, inviteCode || '');
      console.log('✓ Node registered successfully');
    } catch (e: any) {
      const match = e.message.match(/message: "([^"]+)"/);
      console.error(`✗ Registration failed: ${match ? match[1] : e.message}`);
      console.log('Attempting recovery...');
      try {
        this.credentials = await this.scheduler.recover(this.signer);
        console.log('✓ Node recovered successfully');
      } catch (recoverError) {
        console.error('✗ Recovery failed:', recoverError);
        throw recoverError;
      }
    }
  }

  createNode(): Node {
    if (!this.credentials) { throw new Error('Must register/recover before creating node'); }
    console.log('Creating node instance...');
    this.node = new Node(this.credentials);
    console.log('✓ Node created');
    return this.node;
  }

  // Starts the event stream as a background task — returns immediately.
  // The loop runs concurrently while other node methods are called.
  startEventStream(): void {
    if (!this.node) { throw new Error('Must create node before starting event stream'); }
    const node = this.node;

    (async () => {
      let stream: NodeEventStream;
      try {
        stream = await node.streamNodeEvents();
        console.log('✓ Event stream started');
      } catch (e: any) {
        if (e?.message?.includes('Unimplemented')) {
          console.warn('StreamNodeEvents not supported by this node build — skipping');
          return;
        }
        throw e;
      }

      while (true) {
        const event: NodeEvent | null = await stream.next();

        // null means the stream closed (node stopped or connection lost)
        if (event === null) {
          console.log('Event stream closed');
          break;
        }

        switch (event.eventType) {
          case 'invoice_paid': {
            const p = event.invoicePaid!;
            console.log('✓ invoice_paid:');
            console.log(`  payment_hash: ${p.paymentHash.toString('hex')}`);
            console.log(`  preimage: ${p.preimage.toString('hex')}`);
            console.log(`  bolt11: ${p.bolt11}`);
            console.log(`  label: ${p.label}`);
            console.log(`  amount_msat: ${p.amountMsat}`);
            break;
          }
          default:
            console.log(`Received unrecognised event type: "${event.eventType}" — skipping`);
            break;
        }
      }
    })().catch(e => console.error('Event stream error:', e));
  }

  async getOnchainAddress(): Promise<OnchainReceiveResponse> {
    if (!this.node) { this.createNode(); }
    console.log('Generating on-chain address...');
    return await this.node!.onchainReceive();
  }

  async cleanup(): Promise<void> {
    if (this.node) {
      // Stopping the node causes stream.next() to return null,
      // which exits the startEventStream() loop cleanly.
      await this.node.stop();
      console.log('✓ Node stopped');
    }
  }
}

async function quickStart(): Promise<void> {
  const phrase = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about';
  const network: Network = 'regtest';

  console.log('=== Greenlight SDK Demo ===');
  const app = new GreenlightApp(phrase, network);

  try {
    await app.registerOrRecover();
    app.createNode();

    // Start listening for events in the background — does not block.
    app.startEventStream();

    // Continue using the node normally while the stream listens concurrently.
    const address = await app.getOnchainAddress();
    console.log(`✓ Bech32 Address: ${address.bech32}`);
    console.log(`✓ P2TR Address: ${address.p2Tr}`);
  } catch (e) {
    console.error('✗ Error:', e);
  } finally {
    // Stops the node and closes the event stream.
    await app.cleanup();
  }
}

quickStart();

Event Types

| eventType | Payload field | Description | |-----------------|----------------|------------------------------------| | invoice_paid | invoicePaid | An invoice was paid to this node | | unknown | — | An unrecognised server-side event |

InvoicePaidEvent fields

| Field | Type | Description | |---------------|----------|----------------------------------------| | paymentHash | Buffer | Payment hash of the settled invoice | | preimage | Buffer | Preimage that proves payment | | bolt11 | string | The BOLT11 invoice string | | label | string | Label assigned to the invoice | | amountMsat | number | Amount received in millisatoshis |

Testing

The test setup starts and stops all required infrastructure automatically.

Running the Tests

# Run all tests
npm test

# Run with verbose infrastructure logs
VERBOSE=1 npm test

# Run a specific test file
npm test -- --verbose tests/node.spec.ts

How It Works

The global setup script ./tests/jest.globalSetup.ts automatically:

  • Starts test_setup.py, spinning up bitcoind, the Greenlight scheduler, and an LSPS2-compatible LSP node
  • Waits for all services to be ready
  • Injects the required environment variables (GL_SCHEDULER_GRPC_URI, GL_CA_CRT, GL_NOBODY_CRT, GL_NOBODY_KEY, LSP_RPC_SOCKET, LSP_NODE_ID, TEST_SETUP_SERVER_URL)
  • Shuts everything down after all tests complete

Test Helpers

test.helper.ts provides utilities for interacting with the running infrastructure:

| Function | Description | |----------|-------------| | fundNode(node, amountSats?) | Funds a test node with on-chain Bitcoin, waiting until the node detects the confirmed UTXO | | lspInfo() | Returns the LSP node's RPC socket, node ID, and promise secret |

Local npm Publishing

This workflow only builds for local platform. For multi-platform builds, use the GitHub Actions workflow which cross-compiles for all supported targets.

# Clean previous builds
npm run clean

# Build the native binary for your platform
npm run build

# Preview what will be included in the package (Tarball Contents)
npm pack --dry-run

# Bump version (patch: 0.1.4 → 0.1.5, minor: 0.1.4 → 0.2.0, major: 0.1.4 → 1.0.0)
npm version patch/minor/major

# Publish to npm registry (requires authentication)
npm publish --access public

Resources