Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
188 changes: 188 additions & 0 deletions .github/workflows/typescript.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
on:
push:
paths:
- 'libs/gl-sdk-napi/package.json'
branches:
- main
pull_request: {}
release:
types: [created]
workflow_dispatch:

name: Typescript Library

jobs:
check-version:
runs-on: ubuntu-latest
outputs:
version-changed: ${{ steps.check.outputs.changed }}
defaults:
run:
working-directory: libs/gl-sdk-napi
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 2

- id: check
run: |
CURRENT_VERSION=$(cat package.json | jq -r '.version')
git checkout HEAD^
PREVIOUS_VERSION=$(cat package.json | jq -r '.version')
git checkout -
if [ "$CURRENT_VERSION" != "$PREVIOUS_VERSION" ]; then
echo "Version changed from $PREVIOUS_VERSION to $CURRENT_VERSION"
echo "changed=true" >> $GITHUB_OUTPUT
else
echo "Version unchanged"
echo "changed=false" >> $GITHUB_OUTPUT
fi

build:
needs: check-version
if: needs.check-version.outputs.version-changed == 'true'
strategy:
fail-fast: false
matrix:
settings:
- host: ubuntu-latest
target: x86_64-unknown-linux-gnu
build: |
npm run build --target x86_64-unknown-linux-gnu
strip -x *.node

- host: ubuntu-latest
target: aarch64-unknown-linux-gnu
build: |
npm run build --target aarch64-unknown-linux-gnu

- host: ubuntu-latest
target: x86_64-unknown-linux-musl
build: |
npm run build --target x86_64-unknown-linux-musl
strip -x *.node

- host: macos-13
target: x86_64-apple-darwin
build: |
npm run build --target x86_64-apple-darwin
strip -x *.node

- host: macos-14
target: aarch64-apple-darwin
build: |
npm run build --target aarch64-apple-darwin
strip -x *.node

- host: windows-latest
target: x86_64-pc-windows-msvc
build: npm run build --target x86_64-pc-windows-msvc

- host: windows-latest
target: aarch64-pc-windows-msvc
build: npm run build --target aarch64-pc-windows-msvc

name: Build - ${{ matrix.settings.target }}
runs-on: ${{ matrix.settings.host }}

defaults:
run:
working-directory: libs/gl-sdk-napi

steps:
- uses: actions/checkout@v4

- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
cache-dependency-path: libs/gl-sdk-napi/package-lock.json

- name: Install Rust
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.settings.target }}

- name: Setup cross-compilation (Linux ARM64)
if: matrix.settings.target == 'aarch64-unknown-linux-gnu'
run: |
sudo apt-get update
sudo apt-get install -y gcc-aarch64-linux-gnu g++-aarch64-linux-gnu
echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc" >> $GITHUB_ENV

- name: Setup musl tools (Linux musl)
if: matrix.settings.target == 'x86_64-unknown-linux-musl'
run: |
sudo apt-get update
sudo apt-get install -y musl-tools

- name: Cache cargo registry
uses: actions/cache@v4
with:
path: ~/.cargo/registry/cache
key: ${{ matrix.settings.target }}-cargo-registry

- name: Cache cargo index
uses: actions/cache@v4
with:
path: ~/.cargo/registry/index
key: ${{ matrix.settings.target }}-cargo-index

- name: Install dependencies
run: npm ci

- name: Build
run: ${{ matrix.settings.build }}
shell: bash

- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: bindings-${{ matrix.settings.target }}
path: libs/gl-sdk-napi/*.node
if-no-files-found: error

publish:
name: Publish to NPM
runs-on: ubuntu-latest
needs: build

defaults:
run:
working-directory: libs/gl-sdk-napi

steps:
- uses: actions/checkout@v4

- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
registry-url: 'https://registry.npmjs.org'

- name: Install dependencies
run: npm ci

- name: Download all artifacts
uses: actions/download-artifact@v4
with:
path: artifacts

- name: Move artifacts to package directory
run: |
for dir in ../../artifacts/bindings-*; do
if [ -d "$dir" ]; then
echo "Processing $dir"
cp "$dir"/*.node . 2>/dev/null || true
fi
done
ls -la *.node

- name: List package contents
run: npm pack --dry-run

- name: Publish to NPM
run: npm publish --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,6 @@ examples/javascript/package-lock.json

# IntelliJ
.idea/

# VSCode
.vscode/
133 changes: 91 additions & 42 deletions libs/gl-sdk-napi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,42 +59,83 @@ gl-sdk-napi/
## Usage Example

```typescript
import { Scheduler, Signer, Node, Credentials } from '@blockstream/gl-sdk';
import { randomBytes } from 'crypto';

async function quickStart() {
// 1. Register a new node
const scheduler = new Scheduler('regtest');
const seed = randomBytes(32);

const regResult = await scheduler.register(seed, 'INVITE_CODE');
const { device_cert, device_key } = JSON.parse(regResult);

// 2. Create credentials
const credentials = new Credentials(
Buffer.from(device_cert),
Buffer.from(device_key)
);

// 3. Start the signer
const signer = new Signer(seed, 'regtest', credentials);
await signer.start();

// 4. Connect to the node
const nodeId = await signer.nodeId();
const scheduleInfo = await scheduler.schedule(nodeId);
const { grpc_uri } = JSON.parse(scheduleInfo);

const node = await Node.connect(credentials, grpc_uri);

const address = await node.onchainReceive();
console.log('New address:', address.bech32);

// 6. Cleanup
await signer.stop();
import { Scheduler, Signer, Node, Credentials, OnchainReceiveResponse } from '@blockstream/gl-sdk';

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);
const nodeId = this.signer.nodeId();
console.log(`✓ Signer created. Node ID: ${nodeId.toString('hex')}`);
}

registerOrRecover(inviteCode?: string): void {
try {
console.log('Attempting to register node...');
this.credentials = 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 = 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;
}

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

cleanup(): void {
if (this.node) {
this.node.stop();
console.log('✓ Node stopped');
}
}
}

quickStart().catch(console.error);
function quickStart(): 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 {
app.registerOrRecover();
app.createNode();
const address = app.getOnchainAddress();
console.log(`✓ Bech32 Address: ${address.bech32}`);
console.log(`✓ P2TR Address: ${address.p2Tr}`);
} catch (e) {
console.error('✗ Error:', e);
} finally {
app.cleanup();
}
}

quickStart();
```

## Development
Expand All @@ -111,22 +152,30 @@ npm test
npm run build
```

### Cross-compilation

Build for multiple platforms:
### 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.

```bash
npm run build -- --target x86_64-unknown-linux-gnu
npm run build -- --target aarch64-apple-darwin
npm run build -- --target x86_64-pc-windows-msvc
# 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
```

## Important Notes

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

2. **Napi Macros**: We do not combine N-API (napi) macros with UniFFI macros in the same crate. They are incompatible, and mixing them within a single crate would cause conflicts and break the UniFFI-generated mobile bindings.

## Resources

- [Greenlight Documentation](https://blockstream.github.io/greenlight/)
Expand Down
Loading
Loading