npm package: @hlvuser/ability-lightning-payment
Description: A Vincent ability that pays Lightning Network invoices and captures preimages for HTLC verification
Latest version: 0.1.0

# @hlv/ability-lightning-payment

A Vincent ability that enables autonomous agents to pay Lightning Network invoices and capture payment preimages for HTLC (Hash Time-Locked Contract) verification.

## Overview

This ability is a core component of the HLV Protocol (Hash-Locked Value Protocol), enabling trustless atomic swaps between Bitcoin Lightning Network and Hedera blockchain.

### Key Features

- ⚡ **Pay Lightning Invoices**: Execute Lightning Network payments through agent wallets
- 🔐 **Capture Preimages**: Obtain cryptographic proof of payment (preimage) required for HTLC verification
- ✅ **Invoice Validation**: Decode and validate BOLT11 invoices before payment
- 🛡️ **Safety Checks**: Verify amounts, expiry, and liquidity before executing payments
- 🔄 **HTLC Integration**: Designed specifically for cross-chain atomic swap protocols

## How It Works

### The Flow

```
1. User locks wBTC in HTLC on Hedera with payment_hash
2. Vincent Agent uses this ability to pay Lightning invoice via NWC
3. NWC wallet pays the invoice and returns preimage
4. Agent submits preimage to HTLC contract on Hedera
5. HTLC verifies preimage and releases wBTC to agent
```

### NWC (Nostr Wallet Connect)

This ability uses **Nostr Wallet Connect** to execute Lightning payments:
- 🔐 Secure, encrypted communication via Nostr
- ✅ No direct Lightning node access required
- 🌐 Works with Alby, Mutiny, LNbits, Umbrel, and more
- 📱 Simple setup with connection string

### Precheck Phase (Local Validation)

Before committing to a payment, the ability:
- Decodes the BOLT11 invoice
- Extracts payment hash, amount, and expiry
- Validates invoice is not expired
- Checks amount matches expectations (if provided)
- Verifies agent has sufficient Lightning liquidity
- Estimates routing fees

### Execute Phase (Payment Execution)

In the Lit Action environment, the ability:
- Connects to Lightning node (LND, CLN, etc.)
- Executes the payment with specified parameters
- Waits for payment to settle
- **Captures the preimage from payment response**
- Returns preimage, payment hash, and payment details

## Usage

### Installation

```bash
pnpm add @hlv/ability-lightning-payment
```

### In a Vincent App

```typescript
import { bundledVincentAbility as lightningPaymentAbility } from '@hlv/ability-lightning-payment';

// Add to your Vincent App configuration
const abilities = [
  lightningPaymentAbility,
  // ... other abilities
];
```

### Setup NWC Connection

First, get your NWC connection string:

1. **Alby**: Extension → Settings → Advanced → Nostr Wallet Connect
2. **Mutiny**: Settings → Connections → Create NWC Connection
3. **LNbits**: Extensions → NWC → Create Connection

```bash
# .env
NWC_URI="nostr+walletconnect://YOUR_PUBKEY?relay=wss://relay.getalby.com/v1&secret=YOUR_SECRET"
```

### Calling the Ability

```typescript
const result = await lightningPaymentAbility.execute({
  abilityParams: {
    // BOLT11 Lightning invoice
    paymentRequest: 'lnbc1500n1...',
    
    // Optional: Maximum fee willing to pay (in sats)
    maxFeesat: 10,
    
    // Optional: Payment timeout in seconds
    timeoutSeconds: 60,
    
    // Optional: Expected amount for validation
    expectedAmountSat: 150,
    
    // Optional: NWC connection (defaults to NWC_URI env var)
    nwcUri: process.env.NWC_URI,
  }
});

if (result.status === 'success') {
  const { preimage, paymentHash, amountSat, feeSat } = result.data;
  
  // Use the preimage to claim HTLC funds on Hedera
  await hederaHTLC.claimFunds(preimage, signature);
}
```

## Ability Parameters

### Input Schema

```typescript
{
  paymentRequest: string;        // BOLT11 invoice (required)
  maxFeesat?: number;           // Max routing fee in satoshis
  timeoutSeconds?: number;      // Payment timeout (default: 60)
  lightningNodeUrl?: string;    // Lightning node RPC URL
  expectedAmountSat?: number;   // Expected amount for validation
}
```

### Success Response

```typescript
{
  preimage: string;              // 64-char hex string (CRITICAL for HTLC)
  paymentHash: string;           // 64-char hex string
  amountSat: number;             // Payment amount in satoshis
  feeSat: number;                // Actual fee paid in satoshis
  totalSat: number;              // Total cost (amount + fee)
  timestamp: number;             // Payment timestamp
  status: 'SUCCEEDED';           // Payment status
  route?: Array<{                // Optional: Route information
    pubkey: string;
    channel?: string;
    feeMsat?: number;
  }>;
}
```

### Error Response

```typescript
{
  reason?: 'PAYMENT_FAILED' | 'NO_ROUTE_FOUND' | 'INSUFFICIENT_LIQUIDITY';
  error: string;                 // Error message
  paymentHash?: string;          // Payment hash if available
  attemptedRoutes?: number;      // Number of routes attempted
}
```

## NWC Configuration

### Supported Wallets

This ability uses **Nostr Wallet Connect (NWC)** and works with:
- ⚡ **Alby** - Browser extension and web wallet
- ⚡ **Mutiny** - Self-custodial web wallet
- ⚡ **LNbits** - Self-hosted Lightning service
- ⚡ **Umbrel** - Self-hosted Lightning node
- ⚡ **Start9** - Self-hosted Lightning node

### Quick Setup

1. **Get NWC Connection String**:
   - Go to your wallet's settings
   - Find "Nostr Wallet Connect" or "App Connections"
   - Create new connection with permissions:
     - ✅ Pay invoices
     - ✅ Get balance
     - ✅ Get info

2. **Configure Environment**:
   ```bash
   # .env
   NWC_URI="nostr+walletconnect://YOUR_PUBKEY?relay=wss://relay.getalby.com/v1&secret=YOUR_SECRET"
   ```

3. **That's it!** The ability will automatically use NWC for payments.

**For detailed setup**: See [NWC_SETUP_GUIDE.md](./NWC_SETUP_GUIDE.md)

## Security Considerations

### Preimage Security

The preimage is the cryptographic proof that payment succeeded. It must be:
- Captured immediately after payment success
- Transmitted securely to the HTLC contract
- Never exposed publicly before HTLC claim

### Liquidity Management

Agents must:
- Maintain sufficient Lightning channel liquidity
- Monitor channel balances
- Coordinate with other agents for large payments
- Rebalance channels as needed

### Failure Handling

The ability handles failures gracefully:
- Retries failed payments (configurable)
- Returns funds if payment times out
- Provides detailed error information
- Never loses funds due to failed payments

## Integration with HLV Protocol

### In Vincent Agent Service

```typescript
import { vincentAbility as lightningAbility } from '@hlv/ability-lightning-payment';

// When HTLC lock is detected on Hedera
async function handleHTLCLock(lock: HTLCLock) {
  // Decode the Lightning invoice from HTLC lock
  const { paymentRequest } = lock;
  
  // Use Vincent ability to pay invoice
  const result = await lightningAbility.execute({
    abilityParams: {
      paymentRequest,
      maxFeesat: calculateMaxFee(lock.amount),
      expectedAmountSat: lock.amount,
    }
  });
  
  if (result.status === 'success') {
    // Submit preimage to Hedera HTLC to claim wBTC
    await submitToHedera({
      preimage: result.data.preimage,
      paymentHash: result.data.paymentHash,
      lockId: lock.id,
    });
  }
}
```

## Development

### Building

```bash
# Build the ability
pnpm nx build ability-lightning-payment

# Build and bundle for Lit Actions
pnpm nx action:build ability-lightning-payment
```

### Testing

```bash
# Run tests
pnpm nx test ability-lightning-payment

# Run e2e tests
pnpm test-e2e
```

### Deploying to IPFS

```bash
# Deploy to IPFS via Pinata
pnpm nx action:deploy ability-lightning-payment
```

## Roadmap

### Current Features (v0.1.0)
- [x] BOLT11 invoice decoding
- [x] Invoice validation and precheck
- [x] Payment execution framework
- [x] Preimage capture
- [x] Error handling

### Upcoming Features (v0.2.0)
- [ ] LND integration (gRPC)
- [ ] Core Lightning integration (REST)
- [ ] Multi-path payments (MPP)
- [ ] Automatic route optimization
- [ ] Channel liquidity monitoring
- [ ] Payment retry logic
- [ ] Fee optimization

### Future Features (v1.0.0)
- [ ] Multi-node support
- [ ] Lightning Address payments
- [ ] Submarine swaps
- [ ] AMP (Atomic Multi-Path) payments
- [ ] Spontaneous payments (keysend)
- [ ] LNURL support

## Related Packages

- `@hlv/agent` - Vincent agent implementation
- `@hlv/contracts` - Hedera HTLC smart contracts
- `@hlv/shared` - Shared types and utilities
- `@getalby/sdk` - NWC client library

## Documentation

- [NWC Setup Guide](./NWC_SETUP_GUIDE.md) - Complete NWC setup and usage
- [Integration Guide](./INTEGRATION_GUIDE.md) - Advanced integration options
- [Main README](../../README.md) - HLV Protocol overview

## Resources

- [Lightning Network Specification (BOLT)](https://github.com/lightning/bolts)
- [LND Documentation](https://docs.lightning.engineering/)
- [Core Lightning Documentation](https://docs.corelightning.org/)
- [HLV Protocol Documentation](../../README.md)
- [Vincent Protocol](https://docs.heyvincent.ai/)

## License

MIT License - see [LICENSE](../../LICENSE) for details

## Contributing

Contributions are welcome! See [CONTRIBUTING.md](../../CONTRIBUTING.md) for guidelines.

---

**Built for HLV Protocol** - Cross-chain Lightning ⚡ Hedera bridge