Commit Graph
103 Commits
Author SHA1 Message Date
redshift 19ae28c382 fix(wallet): block coco-core while legacy cocod is running
Check the legacy cocod PID file and Unix socket before opening coco.db. Refuse startup when cocod is active or its state cannot be verified, while permitting confirmed stale socket files. Add focused coverage for PID, live socket, stale socket, and fail-closed behavior.
2026-07-13 17:16:15 +08:00
Om Santoshwarandredshift 4afc50500d fix(wallet): add cancel on send/melt failure, use trusted mints for listMints, improve receiveBolt11 type safety 2026-07-13 17:02:22 +08:00
Om Santoshwarandredshift a2219e43a9 fix: revert cosmetic formatting and document coco-core wallet status 2026-07-13 17:02:22 +08:00
Om Santoshwarandredshift 11d9a2b1f7 feat(wallet): replace cocod IPC with coco-core library 2026-07-13 17:02:22 +08:00
redshift 60bc8b4cb2 fix: capture daemon crash logs and prevent silent crashes
- Redirect detached daemon stdout/stderr to ~/.routstrd/debug.log
  instead of ignoring them, so uncaught exception stack traces are
  no longer lost
- Add process-level uncaughtException/unhandledRejection handlers
  that log to the file logger before the process dies
- Wrap setInterval async callbacks (model refresh + refund jobs) in
  IIFE catch chains so rejected promises can't escape and kill the
  process silently
2026-07-09 00:07:13 +08:00
redshift 1ff3b9a4e1 Fix renderToday definite-assignment and usage-summary stale fixtures
renderToday declared todayStats/recentDays/hourlyMap with let but only
assigned inside if (stats.summary); TypeScript flagged them as used
before assignment (TS2454). Initialize with sensible defaults so the
function degrades gracefully when summary is missing.

The usage-summary tz-bucketing test used hardcoded May 2026 timestamps
with a comment dated 2026-06-02. Those entries aged out of
getUsageSummary's 30-day rolling window, so days came back empty.
Recompute timestamps relative to now and assert on dynamically-derived
local-day date strings.
2026-07-05 21:27:20 +05:30
redshift b2738109e3 Sync daemon with SDK discovery adapter API 2026-07-04 21:11:56 +05:30
redshift 3c6161d9bf fix: add periodic Nostr event refresh to daemon
Calls refreshNostrEvents() after initial bootstrap and in the 21-minute
recurring job, covering provider discovery (38421) and lgtm reviews
(38425) which were previously only refreshed on manual trigger.
2026-06-28 10:33:52 +08:00
redshift f15e18cf05 Adapt request response logging to SDK sink 2026-06-20 17:00:52 +08:00
redshift 1735d97a9e feat: configure raw request response logging 2026-06-20 10:10:21 +08:00
redshift 8c52c90f94 addeed npub filtering for /usage as well 2026-06-11 09:31:32 +08:00
redshift 61acc0b5fb added npub based filter! 2026-06-11 09:17:13 +08:00
redshift ae91c46f01 fix(usage-summary): compute size buckets in JS after SDK removed token-range filters
The SDK dropped minTotalTokens/maxTotalTokens from AggregateUsageOptions
(routstr-sdk c98de6b), so replace the five aggregate() calls with a single
list() and bucket entries in-process.
2026-06-10 17:29:19 +08:00
redshift 6536333224 Merge remote-tracking branch 'origin/main' into pr-43
# Conflicts:
#	package.json
#	src/daemon/index.ts
2026-06-10 17:14:24 +08:00
redshift 0ab608bf88 fixed provider disabling not working while running 2026-06-08 09:43:15 +08:00
redshift d87a911241 viisble lgos 2026-06-07 11:25:02 +08:00
redshift 4a66af87da feat(providers): add --refresh flag to providers list
routstrd providers list --refresh now:
- Re-fetches Nostr kind 38421 provider discovery events
- Re-fetches Nostr kind 38423 routstr21 model list
- Re-fetches Nostr kind 38425 review events (applies LGTM-based disable)
- Fetches models from all discovered providers
- Syncs fresh provider list and disabled status into the store

Usage: routstrd providers list --refresh
2026-06-07 11:13:39 +08:00
redshift 27b13c30b0 made relays configurable 2026-06-07 10:56:06 +08:00
redshift 70230d9030 cached otkens now appear on the TUI 2026-06-07 09:06:53 +08:00
redshift d86a231ed3 fix: use Bun-safe SDK entrypoints for ModelManager and storage
- Import ModelManager from @routstr/sdk/bun instead of @routstr/sdk
- Import storage helpers from @routstr/sdk/storage/bun instead of @routstr/sdk/storage
- Fix createBunSqliteUsageTrackingDriver call: async and no longer needs
  manual bun:sqlite import (now handled internally by the sdk entrypoint)
- Verified sharded discovery adapter setup matches SDK pattern in
  scripts/routstr-daemon.ts at 6077aa7
2026-06-06 18:13:06 +08:00
Bilthon bc7ac9ff01 fix(daemon): import bun ModelManager for event persistence 2026-06-03 11:39:16 -05:00
Bilthon c47145137d fix(test): export reset hook and call it in beforeEach for cache isolation 2026-06-02 15:27:19 -05:00
Bilthon bc8611ba7f fix(daemon): include client identity in usage-summary cache key 2026-06-02 15:26:55 -05:00
Bilthon f0978f22c1 test: cover /usage/summary builder 2026-06-02 14:53:38 -05:00
Bilthon 8f77da3911 feat(daemon): add /usage/summary aggregated endpoint 2026-06-02 14:45:06 -05:00
Bilthon 0c382209af refactor: import bun sqlite drivers from @routstr/sdk/storage/bun 2026-06-02 14:43:35 -05:00
redshift f9412af8b3 version bump and using the new adapters and a local eventsDb. 2026-05-30 18:25:18 +08:00
redshift e9775c10d4 Display cooldown in minutes instead of milliseconds
- Add cooldownMinutes field to /nwc/status and /nwc/auto-refill responses
- Change auto-refill log from ms to minutes display
- Keep cooldownMs internally for calculations
2026-05-24 10:23:29 +08:00
redshift 789fd9db2b fix(auto-refill): broken backoff and preimage crash causing payment spam
Two bugs caused the auto-refill loop to retry every 5s regardless of outcome:

1) Backoff used lastRefillAt which was only set on success. On failure
   it stayed at 0, so now - 0 < backoffInterval never blocked once the
   daemon had been running > 30s. Switched to a separate lastAttemptAt
   that is updated on every attempt (success or failure).

2) preimage.slice() crashed when NWC returned a payment result without
   a preimage field. This turned successful payments into exceptions,
   triggering retries and causing the wallet to be charged repeatedly.
   Guard preimage with an if-check before calling .slice().
2026-05-24 10:16:16 +08:00
redshift 99244a8bdb feat: hot-reload NWC connection (remove restart requirement)
- Add reconnect() method to wallet adapter that tears down old
  WalletConnect/RelayPool and creates a new one on the fly
- Auto-refill loop now uses a getWallet() getter so it always
  references the latest wallet instance after reconnect
- POST /nwc/connect and /nwc/disconnect handlers call reconnect()
  after saving config, no restart needed
- Remove 'Run routstrd restart' messages from CLI connect/disconnect
2026-05-24 09:22:45 +08:00
redshift 5799c5c5b0 auto-refill: update wallet auto-refill logic 2026-05-24 09:11:13 +08:00
redshift e5f5c0995d auto-refill: add error categorization, exponential backoff, and fatal error handling 2026-05-23 23:13:52 +08:00
redshift 92ca9a7cb0 chore: remove legacy NWC client, fix auto-refill getter 2026-05-23 23:03:48 +08:00
redshift c98709e383 feat: auto-refill no longer requires daemon restart
Changed startAutoRefillLoop to accept a config getter instead of a static
config object. The getter reads config from disk on every check cycle, so
CLI changes (nwc auto-refill on/off) take effect immediately.

- auto-refill.ts: config parameter replaced with getConfig() callback
- wallet/index.ts: always start loop when wallet exists, use getter
- daemon/index.ts: pass getAutoRefillConfig reading from disk sync
- config-store.ts: added loadDaemonConfigSync() for sync disk reads
- http/index.ts + cli.ts: removed 'Restart daemon to apply' messages
2026-05-23 22:37:43 +08:00
redshift b9d30b12a9 nwc: add progress logs to fundFromNWC, trim response to amount+balance
- Add step-by-step logging to fundFromNWC (initial/final balance, invoice,
  payment status, fees) matching pay_invoice.mts pattern
- Remove invoice and preimage from POST /nwc/fund response
- Add final wallet balance to the response after funding completes
2026-05-23 22:26:10 +08:00
redshift 5ee6a39567 refactor: replace custom NwcClient with applesauce-wallet-connect
- auto-refill.ts: use WalletConnect instance directly instead of
  NwcClient + RelayPool; check wallet.service for connection state
- wallet/index.ts: create single shared WalletConnect for auto-refill,
  fundFromNWC, and getNwcStatus; remove NwcClient entirely
- daemon/index.ts: strip all NwcClient creation/connect/logging/cleanup;
  auto-refill now gates on connectionString alone
- add applesauce-wallet-connect dependency
2026-05-23 22:14:15 +08:00
redshift fd07a688fa simplify NWC client: NIP-04 only, remove encryption negotiation, trim test 2026-05-23 14:42:28 +08:00
redshift 62bd014836 feat: rewrite NWC client with encryption auto-negotiation, EOSE waiting, add test script
- Encryption auto-detection: reads wallet info event (kind 13194) on connect
  to choose NIP-04 vs NIP-44 per NIP-47 spec
- Subscription readiness: wait for EOSE before resolving connect()
- Dual NIP-04 / NIP-44 encrypt/decrypt support
- Proper encryption tags on NIP-44 requests
- test_nwc.ts: standalone NWC test script for make_invoice + pay_invoice
2026-05-23 14:26:45 +08:00
redshift cd9b724ca6 fix(nwc): double hex-encoding of client pubkey and unused connection secret
Two bugs caused NWC responses to never arrive:

1. getPublicKey() in nostr-tools v2 already returns a hex string, but
   the code wrapped it with Buffer.from().toString('hex'), producing a
   double-encoded 128-char string. The relay rejected the REQ filter
   with 'filter item too large' because the #p tag value was invalid.

2. The 'secret' from the NWC connection string (the pre-shared client
   private key per NIP-47) was parsed but never used. Instead a new
   random keypair was generated on every restart, so the wallet service
   would see requests from an unexpected pubkey.

Also removed 'since' from the subscription filter (simpler, some relays
choke on it) and added debug logging for the REQ filter.
2026-05-19 02:00:18 +08:00
redshift 44e6dd884f Merge branch 'main' of github.com-red:Routstr/routstrd into feat/nwc-integration 2026-05-19 01:26:04 +08:00
redshift cee4666f6e nwc integration 2026-05-19 01:25:27 +08:00
redshift 8ae0288d95 docker now has current repo and also added xcashu refunds to the cli 2026-05-19 01:25:00 +08:00
redshift 3f14ae8084 Merge branch 'main' of github.com-red:Routstr/routstrd 2026-05-17 11:49:39 +08:00
redshift fdf65ab0c9 reusing routstrclietn 2026-05-17 11:49:28 +08:00
redshift fd8f433a36 feat: add Docker dev environment and fix logging/cashu-ts
- Add Dockerfile, docker-compose.yml, and .dockerignore for Bun dev container
- Fix sdkLogger to use logger.warn instead of logger.log for warnings
- Add proper warn method to logger (writes to file instead of console)
- Use console.log for daemon startup messages to keep them visible
- Update cashu-ts getDecodedToken call with explicit well-known-pubkeys
- Use proof.amount.toNumber() for updated cashu-ts Amount type
2026-05-16 16:22:16 +08:00
redshift f427cc75ea feat: pass routstrPubkey from config to routeRequests when set 2026-05-14 17:43:30 +05:30
redshift bcbf5bfc44 feat(daemon): wire SdkLogger through daemon with per-request reqId prefixing
- daemon/index.ts: add makeSdkLogger() factory, wire daemonSdkLogger into
  createBunSqliteDriver, createProviderRegistryFromStore, ModelManager, ProviderManager
- daemon/http/index.ts: add makeSdkLogger() factory, generate per-request
  reqId via randomBytes(4), pass reqLogger = sdkLogger.child("req:${reqId}")
  to routeRequests so every log line from a request is prefixed [req:XXXXXXXX]
- start-daemon.ts: remove >> logfile 2>&1 redirect and getTodayLogFile();
  all file logging now goes through the daemon's writeLog() with daily rotation

Result: Every log line from a request is prefixed [req:XXXXXXXX], all entries
have [ISO] [INFO/ERROR/DEBUG] timestamps, no duplicates, and the log file
rotates correctly at midnight.
2026-05-08 19:20:00 +08:00
redshiftandGitHub e881a312d0 Merge pull request #29 from Routstr/fix/not-enough-proofs-balance-error
fix: surface cocod "Not enough proofs" as InsufficientBalanceError
2026-05-07 15:29:11 +00:00
redshiftandClaude Sonnet 4 622afb04a5 fix: sync bootstrapped providers into store so providers list is complete
After bootstrapProviders runs, newly discovered URLs (e.g. privateprovider.xyz)
were only known to the ModelManager cache and never written into the store's
baseUrlsList. This caused `providers list` and `models -m <id>` to show
different sets of providers. Now the bootstrap step merges any new URLs into
the store so both commands draw from the same source of truth.

Co-Authored-By: Claude Sonnet 4 <noreply@anthropic.com>
2026-05-06 20:29:40 +08:00
redshiftandClaude Sonnet 4 3abc028395 fix: surface cocod "Not enough proofs" as InsufficientBalanceError
When cocod cannot assemble enough proofs to send (e.g. due to
denomination fragmentation or stale proof state), it returns
"Send failed: Not enough proofs to send". This was propagating
as a generic Error, causing the HTTP handler to return 500 instead
of the structured 402 insufficient_balance response.

Map that cocod error to InsufficientBalanceError in walletAdapter.sendToken
so the existing handler path returns the correct 402.

Co-Authored-By: Claude Sonnet 4 <noreply@anthropic.com>
2026-05-06 18:32:46 +08:00