npm package: @hlvuser/ability-lightning-invoice
Description: Vincent ability to create Lightning Network invoices via NWC for HLV Protocol
Latest version: 1.0.0

# Lightning Invoice Creation Ability

Vincent ability to create Lightning Network invoices via NWC (Nostr Wallet Connect) for HLV Protocol.

## Purpose

This ability is used in the HLV Protocol rebalancing flow:

1. **User clicks "Rebalance"** with X% of their wBTC balance
2. **This ability creates a Lightning invoice** for the equivalent amount in sats
3. **Returns payment hash** which is used to create HTLC on Hedera
4. **Agent monitors** for payment and captures preimage
5. **Preimage used** to claim wBTC from HTLC

## Flow

```
User Request → Create LN Invoice → Get Payment Hash → Create HTLC → Monitor Payment
```

## Ability Parameters

```typescript
{
  amountSat: number;       // Amount in satoshis
  description?: string;     // Optional description
  expirySec?: number;      // Expiry in seconds (default 24h)
  nwcUri: string;          // Nostr Wallet Connect URI
}
```

## Response

```typescript
{
  paymentRequest: string;   // BOLT11 invoice
  paymentHash: string;      // Payment hash (for HTLC)
  amountSat: number;        // Invoice amount
  description?: string;     // Invoice description
  expiresAt: number;        // Unix timestamp
}
```

## Usage Example

```typescript
import { getVincentAbilityClient } from '@lit-protocol/vincent-app-sdk/abilityClient';
import { bundledVincentAbility } from '@hlv/ability-lightning-invoice';

const abilityClient = getVincentAbilityClient({
  bundledVincentAbility,
  ethersSigner: yourEthersSigner,
});

// Precheck
const precheckResult = await abilityClient.precheck(
  {
    amountSat: 100000, // 100k sats
    description: 'HLV Protocol rebalance',
    expirySec: 86400, // 24 hours
    nwcUri: 'nostr+walletconnect://...',
  },
  {
    delegatorPkpEthAddress: userVincentWalletAddress,
  },
);

// Execute
if (precheckResult.success) {
  const result = await abilityClient.execute(
    {
      amountSat: 100000,
      description: 'HLV Protocol rebalance',
      nwcUri: 'nostr+walletconnect://...',
    },
    {
      delegatorPkpEthAddress: userVincentWalletAddress,
    },
  );

  if (result.success) {
    const { paymentHash, paymentRequest } = result.result;
    // Use paymentHash to create HTLC
    // paymentRequest is the invoice to present to user/agent
  }
}
```

## Integration with HLV Protocol

### 1. Rebalance Button Click

```typescript
// In hlv-frontend
const handleRebalance = async () => {
  // Get user's wBTC balance
  const wbtcBalance = await getWBTCBalance(userAddress);

  // Calculate 20% for rebalancing
  const rebalanceAmount = wbtcBalance * 0.2;

  // Convert to satoshis (assuming 1 wBTC = 100,000,000 sats)
  const amountSat = convertWBTCToSats(rebalanceAmount);

  // Create invoice via Vincent ability
  const invoiceResult = await createLightningInvoice({
    amountSat,
    description: `HLV Rebalance: ${rebalanceAmount} wBTC`,
    nwcUri: userNWCUri,
  });

  if (invoiceResult.success) {
    // Now create HTLC with the payment hash
    await createHTLC({
      paymentHash: invoiceResult.result.paymentHash,
      amount: rebalanceAmount,
      timelock: Date.now() + 86400000, // 24 hours
    });
  }
};
```

### 2. Backend Job Flow

```typescript
// In hlv-backend job
async function executeRebalance(rebalanceRequest) {
  // Step 1: Create Lightning invoice
  const invoice = await lightningInvoiceAbility.execute({
    amountSat: rebalanceRequest.amountSat,
    nwcUri: rebalanceRequest.nwcUri,
  });

  // Step 2: Create HTLC on Hedera
  const htlc = await hederaHTLCAbility.execute({
    paymentHash: invoice.paymentHash,
    tokenAmount: rebalanceRequest.wbtcAmount,
    timelock: invoice.expiresAt,
  });

  // Step 3: Monitor for payment
  // (handled by separate monitoring job)

  return {
    invoiceRequest: invoice.paymentRequest,
    htlcContractId: htlc.contractId,
  };
}
```

## NWC Integration

This ability uses Nostr Wallet Connect (NWC) to interact with Lightning wallets:

- **Alby**: Most common NWC provider
- **LND with NWC bridge**: For self-hosted nodes
- **Mutiny**: Mobile wallet with NWC support

### Getting NWC URI

1. Open your NWC-compatible wallet (e.g., Alby)
2. Go to Settings → Nostr Wallet Connect
3. Create new connection with `make_invoice` permission
4. Copy the `nostr+walletconnect://...` URI

## Development

```bash
# Install dependencies
pnpm install

# Build
pnpm build

# Test
pnpm test

# Deploy to IPFS (requires PINATA_JWT)
pnpm deploy
```

## Environment Variables

```bash
# For testing
TEST_NWC_URI=nostr+walletconnect://...
TEST_AMOUNT_SAT=1000

# For deployment
PINATA_JWT=your_pinata_jwt
```

## TODO

- [ ] Implement actual NWC connection
- [ ] Add Nostr relay communication
- [ ] Parse and validate BOLT11 invoices
- [ ] Add retry logic for NWC commands
- [ ] Implement proper error handling
- [ ] Add invoice expiry monitoring
- [ ] Support multiple NWC providers

## Related

- **ability-hedera-htlc**: Creates HTLCs on Hedera using the payment hash
- **ability-lightning-payment**: Pays Lightning invoices (complementary)
- **hlv-starter-app**: Frontend and backend that uses these abilities

## License

MIT