Skip to content
Open
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
109 changes: 52 additions & 57 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,79 +1,74 @@
# Alby Bitcoin Builder Skill
# Alby Bitcoin Lightning Wallet Skill — Community Edition

Turn your favorite agent into a bitcoin app builder.
A complete Bitcoin Lightning wallet powered by Alby's Nostr Wallet Connect. The agent handles everything — you just talk naturally.

Generate lightning-powered apps, payment flows, and wallet logic in minutes - ready to test and ship, without even needing a wallet.
Every payment gets **cryptographically proven** with SHA-256 preimage verification. No transaction is ever lost. No payment can be disputed.

Before you start, try **[Alby Sandbox](https://sandbox.albylabs.com)** to see what you can build!
## What It Does

This repository contains an [agent skill](https://agentskills.io/specification) that helps agents use the [Alby JS SDK](https://github.com/getAlby/js-sdk) and [Alby Lightning Tools](https://github.com/getAlby/js-lightning-tools).
| Say This | Get This |
|----------|----------|
| "balance" | Multi-currency balance + styled card |
| "create invoice 100 sats" | BOLT-11 + QR code + styled receipt |
| "send 500 to alice@getalby.com" | Confirmed payment with preimage proof |
| "wallet summary" | Complete one-command overview |
| "verify this payment" | SHA-256 cryptographic proof |

> Also check out our **[Wallet CLI skill](https://github.com/getAlby/alby-cli-skill)**
## Features

## Getting Started
- **Auto-Ledger** — Background process that verifies and saves every settled payment with SHA-256 preimage proofs
- **Budget Guardian** — Weekly spending caps with 90% alerts (commitment device)
- **Multi-Wallet** — Add, switch, and manage multiple N wallets
- **Activity Milestones** — Gamified streak tracking
- **Styled Receipt Cards** — Beautiful PIL/Pillow cards for messaging platforms
- **6-Point Health Diagnostics** — Instant wallet status check
- **CSV Export** — Tax-ready, audit-proof transaction records
- **Safety Confirmations** — Mandatory confirmation before any outgoing payment
- **NWC Lie Detection** — Verifies every payment appears in transaction history after send

### 🚀 Install with single command
## Install

`npx skills add getAlby/alby-agent-skill`
### For Hermes Agent Users

### Manual Install
```bash
# Drop into your skills directory
git clone https://github.com/getAlby/alby-agent-skill.git ~/.hermes/skills/alby-bitcoin-payments
cd ~/.hermes/skills/alby-bitcoin-payments
npm install @getalby/sdk @getalby/lightning-tools light-bolt11-decoder qrcode
Comment on lines +35 to +37

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Clone URL may not match repository name.

The PR is on getAlby/builder-skill but the clone command references alby-agent-skill. Also, the npm install command is missing some dependencies listed in package.json (e.g., bolt12-decoder, qrcode-terminal, bolt11).

Verify and fix installation commands
-git clone https://github.com/getAlby/alby-agent-skill.git ~/.hermes/skills/alby-bitcoin-payments
+git clone https://github.com/getAlby/builder-skill.git ~/.hermes/skills/alby-bitcoin-payments
 cd ~/.hermes/skills/alby-bitcoin-payments
-npm install `@getalby/sdk` `@getalby/lightning-tools` light-bolt11-decoder qrcode
+npm install
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
git clone https://github.com/getAlby/alby-agent-skill.git ~/.hermes/skills/alby-bitcoin-payments
cd ~/.hermes/skills/alby-bitcoin-payments
npm install @getalby/sdk @getalby/lightning-tools light-bolt11-decoder qrcode
git clone https://github.com/getAlby/builder-skill.git ~/.hermes/skills/alby-bitcoin-payments
cd ~/.hermes/skills/alby-bitcoin-payments
npm install
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@README.md` around lines 35 - 37, Update the README clone and install commands
so they reference the correct repository and install all required packages:
change the git clone URL from getAlby/alby-agent-skill to getAlby/builder-skill
(or the actual repo name for this PR), keep the destination directory
~/.hermes/skills/alby-bitcoin-payments if intended, and expand the npm install
invocation to include the missing dependencies listed in package.json
(bolt12-decoder, qrcode-terminal, bolt11) alongside `@getalby/sdk`,
`@getalby/lightning-tools`, light-bolt11-decoder, qrcode so the install step
matches the repository's runtime requirements.

```

[Download](https://github.com/getAlby/alby-agent-skill/archive/refs/heads/master.zip) this repository and extract it, then follow instructions for your specific agent.
### Configure

> Double check the skill is activated by asking your agent "What Skills are available?". It should include "Alby Agent Skill"
Save your NWC URL in `~/.hermes/config_local.json`:

### Claude Code
```json
{
"wallet": {
"nwc_url": "nostr+walletconnect://..."
}
}
```

Make a `.claude/skills` folder in your project and put the extracted skills folder there ([see other options](https://code.claude.com/docs/en/skills#where-skills-live))
### Requirements

### Gemini CLI
- Node.js 22+
- Python 3 with Pillow (for styled cards)
- Alby NWC wallet connection

Make a `.gemini/skills` folder in your project and put the extracted skills folder there ([see other options](https://geminicli.com/docs/cli/skills/#skill-discovery-tiers))
## Test Wallet

### Roo Code
Get instant test wallet with 10,000 sats:

Make a `.roo/skills` folder in your project and put the extracted skills folder there ([see other options](https://docs.roocode.com/features/skills#1-choose-a-location))
```bash
curl -X POST https://faucet.nwc.dev?balance=10000
```

## Test / Dummy Wallets
## What Makes This Special

Alby Agent skill has the knowledge to create dummy wallets for testing. You can build and test your app end-to-end without creating a wallet. Once you are ready, the agent skill can also help you setup a wallet to use in production.
Every payment is a **trustless cryptographic event**. The preimage proves it happened — mathematics, not promises.

## Example prompts
A wallet without verified preimages is just a claim. This skill turns claims into proof.

> Explore more prompts in the **[Alby Sandbox](https://sandbox.albylabs.com)**
---

### Console Apps

#### Listen to received payments and send a payment to a lightning address with USD amounts

> Use the Alby Bitcoin Payments Agent Skill to create a TypeScript console app that when receives a notification of an incoming payment, sends $0.10 USD to <hello@getalby.com>. The NWC_URL is in the .env file.

<img width="699" height="496" alt="image" src="https://github.com/user-attachments/assets/66c7dd1f-54ae-4f5d-9830-dd032cfb9e1b" />

#### Conditionally receive payments (NOTE: only supported by Alby Hub)

> Use the Alby Bitcoin Payments Agent Skill to create a TypeScript console app that creates a hold invoice of $1 and asks the user to provide a lightning address and choose heads or tails. Once the hold invoice is accepted, flip a coin. If the user guessed correctly, cancel the hold invoice and pay the user $1 to their lightning address. If the user guessed incorrectly, settle the hold invoice. The NWC_URL is in the .env file.

<img width="947" height="654" alt="image" src="https://github.com/user-attachments/assets/530fccff-33fe-4e68-8998-20f3649cfe7c" />

### Frontend Apps

#### Streamer QR page with payment notifications

> Use the Alby Bitcoin Payments Agent Skill to create a single-page HTML app that listens to incoming payments, and each time one comes in, shows a confetti animation and the payment amount and message. It should also have a QR code of the receiving lightning address that should be displayed on the corner of the screen so people watching can easily send payments. When I first open the page it should prompt me for a NWC connection secret so it can connect to my wallet to listen for payments, and also extract the lightning address from the NWC connection secret for the QR code.

<img width="1432" height="806" alt="image" src="https://github.com/user-attachments/assets/979a3034-99ac-4481-8e32-9750486eb996" />

### Testing

#### Example test for a backend or console app

> Use the Alby Bitcoin Payments Agent Skill to create a TypeScript console app where Alice creates an invoice and Bob pays it. Write tests for it using jest.

#### Example test for a frontend app (vitest + Playwright)

> Use the Alby Bitcoin Payments Agent Skill to create a Vite TypeScript React app where a user can connect their wallet and then purchase fake cat pictures (simple canvas art) with a single click. Each picture costs 5000 sats. Show the total the shop has earned and their remaining stock of cat pictures. There should only be 21. Write tests for the app using vitest and playwright. Also take screenshots and review the screenshots.

## Development

Examples are hand-written, but lack the necessary typing information. Types are copied directly from the referenced projects using [this script](./regenerate-types.sh)
Built on: [Alby JS SDK](https://github.com/getAlby/js-sdk) · [Alby Lightning Tools](https://github.com/getAlby/js-lightning-tools) · [NIP-47 NWC Protocol](https://github.com/nostr-protocol/nips/blob/master/47.md)
201 changes: 160 additions & 41 deletions SKILL.md
Original file line number Diff line number Diff line change
@@ -1,47 +1,166 @@
---
name: alby-bitcoin-builder
description: Add bitcoin lightning wallet capabilities to your app using Nostr Wallet Connect (NIP-47), LNURL, and WebLN. Send and receive payments, handle payment notifications, fetch wallet balance and transaction list, do bitcoin to fiat currency conversions, query lightning addresses, conditionally settle payments (HOLD invoices), parse BOLT-11 invoices, verify payment preimages.
license: Apache-2.0
metadata:
author: getAlby
version: "1.2.1"
name: alby-bitcoin-payments
description: Bitcoin Lightning wallet via NWC. Say anything natural, get confirmed transactions. Every payment cryptographically proven with SHA-256 preimage verification.
version: "7.0.0"
---

# Usage
## What This Is

Use this skill to understand how to build apps that require bitcoin lightning wallet capabilities.
A complete Bitcoin Lightning wallet powered by Alby's Nostr Wallet Connect. The agent handles everything — the user just talks naturally.

- [NWC Client: Interact with a wallet to do things like sending and receive payments, listen to payment notifications, fetch balance and transaction list and wallet info](./references/nwc-client/nwc-client.md)
- [Lightning Tools: Request invoices from a lightning address, parse BOLT-11 invoices, verify a preimage for a BOLT-11 invoice, LNURL-Verify, do bitcoin <-> fiat conversions](./references/lightning-tools/lightning-tools.md)
- [Bitcoin Connect: Browser-only UI components for connecting wallets and accepting payments in React, Vue, or pure HTML web apps](./references/bitcoin-connect/bitcoin-connect.md)
## How It Works

## Prefer Typescript

When the user says to use "JS" or "Javascript" or "NodeJS" or something similar, use typescript unless the user explicitly says to not use typescript or the project does not support it.

## Imports

Do NOT import from the dist directory.

## Read the Typings

Based on what functionality you require, read the relevant typings:

- [NWC Client](./references/nwc-client/nwc.d.ts)
- [Lightning Tools](./references/lightning-tools/index.d.ts)
- [Bitcoin Connect](./references/bitcoin-connect/bundle.d.ts)
- [Bitcoin Connect React](./references/bitcoin-connect/react.bundle.d.ts)

## Testing Wallets

If the user doesn't have a wallet yet, or needs one for development or testing, [testing wallets can be created with a single request](./references/testing-wallets.md).

### Automated Testing

Testing wallets should be used for [automated testing](./references/automated-testing.md).

It is recommended to write tests so that the agent can test its own work and fix bugs itself without requiring human input.

## Production Wallet

If they do not have a wallet yet [here are some options](./references/production-wallets.md)
User → says anything natural → agent does everything → confirmation.

```

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Add language identifiers to fenced code blocks (MD040).

These fences are missing language tags and trigger markdownlint warnings.

Suggested cleanup
- ```
+ ```text
...
- ```
+ ```text
...
- ```
+ ```text
...
- ```
+ ```text
...
- ```
+ ```bash

Also applies to: 54-54, 61-61, 67-67, 103-103

🧰 Tools
🪛 markdownlint-cli2 (0.22.0)

[warning] 15-15: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@SKILL.md` at line 15, The Markdown file SKILL.md contains fenced code blocks
with missing language identifiers causing MD040 lint warnings; update each
triple-backtick fence in SKILL.md (the generic code blocks shown in the diff) to
include an appropriate language tag (e.g., ```text for plain output blocks or
```bash for shell snippets) so every ``` is replaced with a language-specified
fence, keeping the content unchanged.

User: "send 500 to alice@getalby.com"
User: "balance"
User: "create invoice for 1000 sats"
User: "my wallet" ← one command, everything
User: "verify this payment"
```

## Core Agent Rules

**On session start:**
1. Read `wallet.nwc_url` from `~/.hermes/config_local.json`
2. If auto-ledger not running, start it in background
3. Show balance

**SECURITY: NWC URL MUST NEVER be displayed, echoed, or shared in any output, logs, or chat.**

**On every wallet operation:**
- `cd /root/.hermes/skills/alby-bitcoin-payments` first
- NWC returns millisats → always divide by 1000
- Always include fiat equivalent (USD default)
- NWC URL → never echo, never log, never display in any form
- Read URL only from `~/.hermes/config_local.json` (chmod 600) — never ask user for it again

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Clarify expired-URL flow vs “never ask again” rule.

These lines conflict operationally. Define one explicit policy for renewal (e.g., secure re-provisioning flow) so agents don’t behave inconsistently.

Also applies to: 163-163

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@SKILL.md` at line 37, The SKILL.md statement "Read URL only from
`~/.hermes/config_local.json` (chmod 600) — never ask user for it again"
conflicts with handling expired URLs; update SKILL.md to define one explicit
renewal policy by either (A) stating a secure re-provisioning flow (e.g., agents
must detect expired URL, remove/rotate the entry in
`~/.hermes/config_local.json`, and invoke an authenticated re-provisioning
CLI/UX flow) or (B) allowing a controlled re-prompting rule (e.g., only via an
interactive admin command and logged audit) — replace the ambiguous line and the
duplicate at the other occurrence with the chosen policy and include clear steps
for detection, authorization, and storage (mention the
`~/.hermes/config_local.json` file and the exact phrase to be removed/updated).


**Before sending:**
1. Decode destination → show amount, fiat, recipient
2. Confirm: `"Send X sats ($Y) to Z? Reply YES to confirm."`
3. After paying → verify in `listTransactions()` (NWC can report false success)

**On invoice creation:**
- BOLT-11 in code block (one-tap copy)
- Include sats + fiat

**On BOLT-11 or lightning address in any message:**
- Auto-decode → show details → offer next action

## Response Style

### Balance Card
```
Wallet: alias | mainnet
Balance: 1,234 sats
$ 1.23 USD · € 1.07 EUR · KSh 159.20 KES
```

### Transaction Row
```
→ +100 sats ($0.07) ✅ | description | bal: 1,234
← -50 sats ($0.03) ✅ | to alice | bal: 1,184
```

### Payment Proof
```
Payment Hash: a863be4753fe982d...
SHA-256(preimage): a863be4753fe982d...
✅ MATCH — Preimage: 9137715c...59b1
```

## Behind the Scenes

| Feature | Script | What It Does |
|---|---|---|
| Summary | `summary.js` | One-command wallet overview |
| Balance | `balance.js` | Multi-currency balance (USD/EUR/KES) |
| Invoice | `qr_invoice.js` | BOLT-11 invoice + QR code |
| Decode | `decode.js` | Parse invoices or lightning addresses |
| Analytics | `analytics.js` | Period reports with top transactions |
| Auto-Ledger | `auto_ledger.js` | Background: real-time payments + crypto proofs |
| Validate | `validate.js` | Standalone preimage verification |
| Budget | `budget_guardian.js` | Weekly spending caps with alerts |
| Streaks | `streaks.js` | Activity milestones & gamification |
| Multi-Wallet | `wallets.js` | Add/switch/remove wallets |
| Health | `health_check.js` | 6-point diagnostics |
| Export | `export_ledger.js` | CSV export for tax/audit |

## Auto-Ledger (The Trustless Core)

Every settled payment gets automatically:
1. **Verified** — SHA-256(preimage) == payment_hash
2. **Saved** — Persistent ledger at `~/.hermes/ledgers/transactions_ledger.json`
3. **Proved** — Individual proof files in `~/.hermes/ledgers/proofs/`

No transaction is ever lost. No payment can be disputed. Mathematics, not promises.

## Budget Guardian

Set a weekly spending cap. The system tracks and alerts at 90%. Pre-commitment removes the temptation of impulse spending.

```
node budget_guardian.js setup 5000 # 5000 sats/week
node budget_guardian.js status # Current usage
node budget_guardian.js reset # Reset for new week
```

## Initial Setup

1. `cd ~/.hermes/skills/alby-bitcoin-payments`
2. Run `npm install` (uses `package.json` in skill root)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Setup instructions conflict on package.json location.

Line 112 says package.json is in skill root, while Line 148 says it may only exist in clone root. Please unify this into one authoritative setup path to avoid failed installs.

Also applies to: 148-149

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@SKILL.md` at line 112, The setup docs conflict about where package.json
lives: the line that reads "Run `npm install` (uses `package.json` in skill
root)" and the later lines referencing "clone root" must be unified; choose the
authoritative path (e.g., "skill root" or "repo/clone root"), then update both
occurrences so they use identical wording and include a clear command (e.g., "cd
<chosen-root> && npm install") and a note to run the command from that
directory; change the lines containing the exact phrases "Run `npm install`
(uses `package.json` in skill root)" and the later "clone root" wording to match
the chosen path.

3. Set NWC URL in `~/.hermes/config_local.json` under `wallet.nwc_url`
```json
{"wallet": {"nwc_url": "nostr+walletconnect://..."}}
```
4. Set file permissions: `chmod 600 ~/.hermes/config_local.json`
5. Start auto-ledger: `export NWC_URL=$(python3 -c "import json; print(json.load(open('~/.hermes/config_local.json'))['wallet']['nwc_url'])") && node scripts/auto_ledger.js &`

### Running Scripts

Always export NWC URL first (scripts read from env, not config file):
```bash
cd ~/.hermes/skills/alby-bitcoin-payments
export NWC_URL=$(python3 -c "import json; print(json.load(open('~/.hermes/config_local.json'))['wallet']['nwc_url'])")
node scripts/balance.js
Comment on lines +118 to +126

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🌐 Web query:

In Python, does open("~/.hermes/config_local.json") expand "~" automatically, or is os.path.expanduser required?

💡 Result:

No. open("~/.hermes/config_local.json") does not expand ~—tilde expansion is a shell feature, not something open() applies. Use os.path.expanduser() (or pathlib.Path("~/.hermes/config_local.json").expanduser()) before opening. [1], [2]


🏁 Script executed:

# Check if SKILL.md exists and view the relevant lines
if [ -f "SKILL.md" ]; then
  echo "=== Lines 115-130 of SKILL.md ==="
  sed -n '115,130p' SKILL.md
  echo ""
  echo "=== Full context around line 118 and 125 ==="
  sed -n '110,135p' SKILL.md
else
  echo "SKILL.md not found, searching for it..."
  find . -name "SKILL.md" -type f
fi

Repository: getAlby/builder-skill

Length of output: 1790


🏁 Script executed:

# Search for any wrapper scripts or references to these commands
echo "=== Search for references to 'open' with config_local.json ==="
rg "config_local\.json" -A 2 -B 2

echo ""
echo "=== Search for shell scripts or Python files that might wrap these commands ==="
fd -e "sh" -e "py" -e "js" | head -20 | xargs -I {} rg -l "NWC_URL|nwc_url" {}

echo ""
echo "=== Check if there are any shell startup scripts or bashrc ==="
find . -name ".bashrc" -o -name ".bash_profile" -o -name "*.sh" -type f | head -10

Repository: getAlby/builder-skill

Length of output: 3506


Fix open('~/.hermes/...') to expand tilde for portable path handling.

The Python open() function does not expand ~ automatically—tilde expansion is a shell feature. These commands will fail at runtime with FileNotFoundError. Additionally, the file contains inconsistent path handling (some use ~, others use hardcoded /root/). Use os.path.expanduser() for portable, user-agnostic paths.

Suggested fix
- export NWC_URL=$(python3 -c "import json; print(json.load(open('~/.hermes/config_local.json'))['wallet']['nwc_url'])") && node scripts/auto_ledger.js &
+ export NWC_URL=$(python3 -c "import json, os; p=os.path.expanduser('~/.hermes/config_local.json'); print(json.load(open(p))['wallet']['nwc_url'])") && node scripts/auto_ledger.js &

- export NWC_URL=$(python3 -c "import json; print(json.load(open('~/.hermes/config_local.json'))['wallet']['nwc_url'])")
+ export NWC_URL=$(python3 -c "import json, os; p=os.path.expanduser('~/.hermes/config_local.json'); print(json.load(open(p))['wallet']['nwc_url'])")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@SKILL.md` around lines 118 - 126, The inline Python one-liners in SKILL.md
that call open('~/.hermes/config_local.json') will fail because tilde isn't
expanded by Python; update the export NWC_URL commands (used for
scripts/auto_ledger.js and scripts/balance.js invocations) to use
os.path.expanduser (i.e., import os and call
open(os.path.expanduser('~/.hermes/config_local.json'))) or otherwise resolve
the full path, and also normalize any other occurrences that hardcode /root/ to
consistently use expanduser so the commands work for non-root users.

```

## Environment

| Path | Purpose |
|------|---------|
| `/root/.hermes/skills/alby-bitcoin-payments/` | Skill root — always `cd` here first |
| `~/.hermes/ledgers/` | Auto-ledger + proof files |
| `~/.hermes/config_local.json` | NWC URL + user config |

**Script Execution:** Always export the NWC URL before running scripts:
```bash
export NWC_URL=$(python3 -c "import json; print(json.load(open('/root/.hermes/config_local.json'))['wallet']['nwc_url'])")
```

**Important Script Argument Orders:**
- `pay.js` — takes `<amount_sats>` then `<recipient>`: `pay.js 100 user@domain.com` (amount first!)
- `qr_invoice.js` — takes `<amount_sats>` then `<description>`: `qr_invoice.js 100 "my invoice"`

**Key Operational Notes:**
- The `@getalby/sdk` NWCClient must be imported from `@getalby/sdk/nwc` (not the main module)
- The `package.json` may not be present in the installed skill directory — it's in the clone root, needed for `npm install`
- The auto-ledger (`auto_ledger.js`) does NOT start automatically — run it manually in background after wallet setup:
```bash
mkdir -p ~/.hermes/ledgers/proofs && node scripts/auto_ledger.js &
```
- Payment verification via NWC `listTransactions()` is the authoritative source — NWC `payInvoice()` can report false success
- SHA-256 preimage verification: `crypto.createHash('sha256').update(Buffer.from(preimage, 'hex')).digest('hex')` should match `payment_hash`

**PIL cards:** Disabled. Do not generate styled PIL receipt cards. Just use text confirmations and ASCII panels.

## Troubleshooting

| Problem | Fix |
|---|---|
| `Cannot find module` | Run from skill directory — deps are in local `node_modules/` |
| Connection refused | NWC URL expired — ask for a new one |
| Amount looks 1000x wrong | NWC = millisats. Divide by 1000. |
| `payInvoice` reported success but no transaction | NWC can lie. Always check `listTransactions()` after paying |
| PIL import fails | Use `/usr/bin/python3` — the agent's venv python doesn't have Pillow |
9 changes: 9 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"dependencies": {
"@getalby/lightning-tools": "^7.0.2",
"@getalby/sdk": "^7.0.0",
"bolt12-decoder": "^1.0.0",
"light-bolt11-decoder": "^3.2.0",
"qrcode": "^1.5.4"
}
}
45 changes: 45 additions & 0 deletions references/payment-validation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Payment Validation (Preimage Verification)

Verify that a Lightning Network payment was actually completed by cryptographically checking the preimage against the invoice's payment hash.

## How It Works

1. Every BOLT-11 invoice contains a `payment_hash` (SHA-256 of the preimage)
2. When payment completes, the payer's node reveals the `preimage`
3. Verifying: `SHA-256(preimage) == payment_hash` proves the payment went through
4. Only the recipient can know the preimage — so proving they had it proves they received payment

Reference implementation: https://github.com/kingonly/validate-payment
Live web validator: https://validate-payment.com/

## CLI Script (Bundled)

```bash
node scripts/validate.js [invoice] [preimage_hex]
```

Supports BOLT11 (`lnbc`/`lntb`) and BOLT12 (`lni`) invoice formats.
Shows decoded invoice details (amount, description, timestamp, expiry) plus the hash comparison.

## Node.js API

```typescript
import { decode as decodeBolt11 } from 'light-bolt11-decoder';
import crypto from 'crypto';

function validatePayment(invoice: string, preimage: string): boolean {
const decoded = decodeBolt11(invoice);
const paymentHash = decoded.sections.find(s => s.name === 'payment_hash').value;
const preimageBytes = Uint8Array.from(preimage.match(/.{1,2}/g).map(h => parseInt(h, 16)));
const computed = crypto.createHash('sha256').update(preimageBytes).digest('hex');
return computed === paymentHash;
}
```

## When to Use

- **Pay-to-unlock content**: User pays, you deliver content, they can verify the preimage matches
- **Third-party payment proof**: Someone claims they paid — verify with preimage
- **Escrow/settlement verification**: Confirm funds actually moved before releasing goods
- **HOLD invoice confirmation**: After settling, the preimage proves the HTLC completed
- **Payment receipt verification**: Generate a verifiable receipt by providing preimage + invoice
Loading