Files
Mikael BergandPaperclip b9f9aebd7b feat(watcher): BCH xpub transaction ingestion — watch address, capture on confirmation
- watcher.ts: derives BCH P2PKH CashAddr addresses from BIP44 account xpub
  (coin type 145, external chain m/0/i); polls Blockchair for confirmed txs;
  captures txid, amountBCH, blockHash, blockTimestamp, address
- demo.ts: end-to-end demo — generates test xpub from BIP44 seed, derives
  5 addresses, fetches and captures a real mainnet transaction (verified live)
- index.ts: CLI entry point for the live watcher
- Fix block_hash: Blockchair BCH omits block_hash inline; now fetched via
  /dashboards/block/{id} with in-process cache to avoid duplicate lookups
- Fix ESM imports: .ts extensions required for node --experimental-strip-types
- package.json: add npm run watch script
- README: add xpub watcher section with demo output and API reference

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-05-17 16:30:02 +00:00

162 lines
5.5 KiB
Markdown

# using-cash-spike
BCH engineering spike for using.cash — evaluates BCH node/API options, transaction ingestion, and price oracle.
## Spike Goals
1. **Repo + node/API evaluation** — PRO-61
2. **xpub transaction ingestion** — PRO-62
3. **Historical price oracle** — PRO-63
## xpub Transaction Watcher (`src/watcher.ts`)
BCH xpub watch-only transaction watcher. Derives receiving addresses from a BIP44 account-level xpub, polls Blockchair for confirmed transactions, and captures all required fields on confirmation.
### Address derivation
- **Standard**: BIP44 path `m/44'/145'/account'` (BCH coin type 145 per SLIP-0044)
- External (receiving) chain: `xpub/0/index` — the watcher monitors indices 0..N-1
- Address format: CashAddr P2PKH (`bitcoincash:q...`)
### Quick Start
```bash
# End-to-end demo (derives test xpub, captures a real mainnet tx)
npm run demo
# or:
node --experimental-strip-types src/demo.ts
# Live watcher — polls for new confirmed transactions every 30s
node --experimental-strip-types src/index.ts <your-xpub> [addressCount] [pollSeconds]
# Example:
node --experimental-strip-types src/index.ts xpub6ByHsPNSQXTWZ7... 20 30
```
### Demo Output (verified 2026-05-17)
```
=== BCH xpub Watcher — End-to-End Demo ===
BIP44 BCH account xpub (m/44'/145'/0'):
xpub6ByHsPNSQXTWZ7PLESMY2FufyYWtLXagSUpMQq7Un96SiThZH2iJB1X7pwviH1WtKVeDP6K8d6xxFzzoaFzF3s8BKCZx8oEDdDkNnp4owAZ
First 5 BCH receiving addresses (m/44'/145'/0'/0/0..4):
[0] bitcoincash:qqyx49mu0kkn9ftfj6hje6g2wfer34yfnq5tahq3q6
[1] bitcoincash:qp8sfdhgjlq68hlzka9lcsxtcnvuvnd0xqxugfzzc5
[2] bitcoincash:qqkuy34ntrye9a2h4xpdstcu4aq5wfrwscjtaphenr
[3] bitcoincash:qzcyvxr0e23d408u62ulf6cnspc0k4dyduy8kh77nc
[4] bitcoincash:qptzx8m39zjuuyvrf86s3kywuledfht2jcty8we6gv
--- Live Mainnet Capture Demo ---
Using block #951444
Selected txid: ee31309d9c19f184e8e1ff29b4da529f6c804c55fbc60c407e9042b1a17f254c
=== Captured Transaction ===
{
"txid": "ee31309d9c19f184e8e1ff29b4da529f6c804c55fbc60c407e9042b1a17f254c",
"amountBCH": 0.01552951,
"blockHash": "000000000000000000821d5b8673e87b415fb9d92262860b925ce458799d7895",
"blockTimestamp": "2026-05-17 16:17:18",
"address": "qpdaduzn8zujln5830zfasz4nkewslm3c5kw7g4g9r"
}
```
### API
```typescript
import { deriveAddresses, captureTransaction, watchXpub } from './src/watcher.ts';
// Derive receiving addresses from account-level xpub
const addresses = deriveAddresses(xpub, 20);
// Capture a confirmed transaction (all 4 required fields)
const capture = await captureTransaction(txid, address);
// { txid, amountBCH, blockHash, blockTimestamp, address }
// Start live watcher (polls indefinitely)
await watchXpub(xpub, 20, 30_000);
```
### API Source
Uses [Blockchair BCH REST API](https://blockchair.com/api/docs) — no API key required for basic usage. Rate limit: ~1,440 req/day on free tier.
---
## Price Oracle (`src/price-oracle.ts`)
BCH/USD historical price oracle. Accepts a block timestamp (Unix epoch or ISO date) and returns the BCH/USD spot price from multiple sources with variance comparison.
### Sources Evaluated
| Source | Status | Key Required | Coverage |
|--------|--------|-------------|----------|
| CoinGecko | Works (with key) | Yes — free Demo key | BCH from 2017-08 |
| CryptoCompare | Works (no key) | No | BCH from 2017 |
| Binance BCHUSDT | Works (no key) | No | BCH from 2018-03 |
| Messari | Deprecated | N/A | data.messari.io → 404 |
### Quick Start
```bash
# Single date lookup
node --experimental-strip-types src/price-oracle.ts 2023-01-15
# Multiple dates
node --experimental-strip-types src/price-oracle.ts 2021-05-10 2022-12-30 2024-03-15
# Full demo with variance table and recommendation
node --experimental-strip-types src/demo.ts
# With CoinGecko enabled (free Demo key from coingecko.com/en/api)
COINGECKO_API_KEY=your_key node --experimental-strip-types src/demo.ts
```
### Demo Output (verified 2026-05-17)
```
BCH/USD Historical Price Comparison
Date CoinGecko CC Binance MaxVar% Note
------------------------------------------------------------
2018-11-20 N/A $218.34 N/A N/A
2019-12-15 N/A $207.20 $206.88 0.155% ok
2021-05-10 N/A $1321.91 $1321.31 0.045% ok
2022-12-30 N/A $96.62 $96.80 0.186% ok
2024-03-15 N/A $416.65 $416.70 0.012% ok
Avg CryptoCompare vs Binance variance: 0.0995%
Max variance: 0.1861% — no dates exceeded the 1% threshold
```
### Production Recommendation
**Strategy: CoinGecko primary → CryptoCompare fallback → Binance fallback**
1. **CoinGecko** (primary): industry standard for FMV/accounting; requires free Demo API key (~30 req/min)
2. **CryptoCompare** (fallback A): verified free, no key needed, full coverage from 2017, <0.2% divergence from Binance
3. **Binance BCHUSDT** (fallback B): highest-volume exchange, free, no key, coverage from 2018-03
Cache by date (YYYY-MM-DD). Store prices as NUMERIC(20,8).
### API
```typescript
import { compareSourcesForTimestamps, printVarianceTable } from './src/price-oracle.ts';
const rows = await compareSourcesForTimestamps([
'2023-01-15',
1684368000, // Unix epoch seconds also accepted
]);
printVarianceTable(rows);
// rows[0].cryptocompare → BCH/USD close price for that date
// rows[0].flagged → true if any source pair differs >1%
```
### Environment Variables
| Variable | Purpose |
|----------|---------|
| `COINGECKO_API_KEY` | CoinGecko Demo or Pro API key (enables CoinGecko source) |
| `CRYPTOCOMPARE_API_KEY` | CryptoCompare API key (raises rate limit) |