diff --git a/docs/invoice-payments-api.md b/docs/invoice-payments-api.md index cb3e99d7..d5b6802a 100644 --- a/docs/invoice-payments-api.md +++ b/docs/invoice-payments-api.md @@ -192,11 +192,11 @@ If the invoice amount exceeds the wallet's admin‑approval threshold, the payme { "success": false, "status": "awaiting_approval", - "message": "Transaction requires admin approval (amount: 60000 > threshold: 50000). Approval request sent to you via Telegram. Transaction ID: pending-yourprovider-invoice-3d2f...-1699999999", + "message": "Transaction requires admin approval (amount: 150000 > threshold: 100000). Approval request sent to you via Telegram. Transaction ID: pending-yourprovider-invoice-3d2f...-1699999999", "from_user": "yourprovider", "to_user": "lnbc10u1p3xyz...", - "amount": 60000, - "amount_lkr": "1,950.00" + "amount": 150000, + "amount_lkr": "4,875.00" } ``` @@ -229,8 +229,8 @@ The `{transaction_id}` is the ID from the `202` response `message`. "status": "executed", "from_user": "yourprovider", "to_user": "lnbc10u1p3xyz...", - "amount": 60000, - "amount_lkr": "1,950.00", + "amount": 150000, + "amount_lkr": "4,875.00", "memo": "order-12345", "payment_hash": "3d2f...e91a", "request_timestamp": "2026-07-17T10:00:00Z", @@ -340,7 +340,7 @@ These apply to invoice payments via `POST /api/v1/send`. | **Amountless invoices** | **Not supported** — rejected with `400`. The invoice must encode an amount. | | **Minimum amount** | Invoice amount must be greater than `min_amount` (default **1 sat**). | | **Maximum amount** | Invoice amount must not exceed the wallet's `max_amount` (global default **1,000,000 sats**; may be set lower per wallet). | -| **Admin approval threshold** | Amounts above `admin_approval_threshold` (global default **50,000 sats**; may be per wallet) are held for operator approval and return `202` instead of paying immediately. | +| **Admin approval threshold** | Amounts above `admin_approval_threshold` (global default **100,000 sats**; may be per wallet) are held for operator approval and return `202` instead of paying immediately. | | **Routing‑fee reserve** | Your available balance must cover the amount **plus ~2%** for routing fees. If `amount > balance * 0.98`, the request is rejected even if `balance >= amount`. | | **Idempotency** | Requests are de‑duplicated on the invoice **payment hash**. Concurrent or retried attempts to pay the same invoice will not double‑pay. | | **Concurrent payments** | Different invoices can be paid **in parallel** from the same wallet. Each in‑flight payment's amount plus fee reserve is held against your available balance until the Lightning backend accepts it, so parallel requests are rejected with the insufficient‑balance errors once the balance is used up. | diff --git a/internal/api/analytics.go b/internal/api/analytics.go index 07cf5e3c..66a77f0b 100644 --- a/internal/api/analytics.go +++ b/internal/api/analytics.go @@ -502,7 +502,7 @@ func (s Service) GetUserTransactionHistory(w http.ResponseWriter, r *http.Reques json.NewEncoder(w).Encode(response) } -// fetchPaymentsWithRateLimit waits for the shared LNbits rate limiter token, then fetches +// fetchPaymentsWithRateLimit waits for the analytics LNbits rate limiter token, then fetches // payments for the given user. On HTTP 429 it retries up to 3 times with exponential backoff // (2s, 4s, 8s) before giving up. func fetchPaymentsWithRateLimit(ctx context.Context, s Service, user *lnbits.User, count int) ([]lnbits.Payment, error) { diff --git a/internal/config.go b/internal/config.go index bdaf16a2..485d8ac7 100644 --- a/internal/config.go +++ b/internal/config.go @@ -4,7 +4,6 @@ import ( "fmt" "net" "net/url" - "os" "strings" "time" @@ -159,7 +158,7 @@ func init() { panic(err) } Configuration.Bot.LNURLHostUrl = hostname - checkLnbitsConfiguration() + normalizeLnbitsConfiguration() setAPISendDefaults() setAPIAnalyticsDefaults() } @@ -179,37 +178,19 @@ func GetWebhookURLParsed() *url.URL { return Configuration.Lnbits.WebhookPublicUrlParsed } -// underTest reports whether this binary is a `go test` binary. -// -// Package init runs before the testing package registers its flags, so -// flag.Lookup("test.v") is not yet usable here and os.Args is the only -// reliable signal. This exists because most packages reach this one through -// the import graph (lnbits -> satdress -> network -> internal), so without it -// a unit test that never talks to lnbits still cannot run unless a full -// operator config.yaml sits in its package directory. -func underTest() bool { - if strings.HasSuffix(os.Args[0], ".test") || strings.HasSuffix(os.Args[0], ".test.exe") { - return true - } - for _, arg := range os.Args[1:] { - if strings.HasPrefix(arg, "-test.") { - return true - } - } - return false -} - -// checkLnbitsConfiguration validates the lnbits configuration -func checkLnbitsConfiguration() { +// CheckLnbitsConfiguration panics when no lnbits url is configured: the bot +// cannot move sats without one. main calls it at startup. It is not run from +// init because most packages import this one (lnbits -> satdress -> network -> +// internal), and a unit test that never talks to lnbits must not need a full +// operator config.yaml to load. +func CheckLnbitsConfiguration() { if Configuration.Lnbits.Url == "" { - // A missing lnbits url stays fatal in production: the bot cannot move - // sats without it. Under `go test` there is no wallet to talk to, so - // refusing to link would only make the package untestable. - if underTest() { - return - } panic(fmt.Errorf("please configure a lnbits url")) } +} + +// normalizeLnbitsConfiguration fills in derived lnbits settings. +func normalizeLnbitsConfiguration() { if Configuration.Lnbits.LnbitsPublicUrl == "" { log.Warnf("Please specify a lnbits public url otherwise users won't be able to") } else { diff --git a/internal/lnbits/settlement.go b/internal/lnbits/settlement.go index c25e1939..c6f02d91 100644 --- a/internal/lnbits/settlement.go +++ b/internal/lnbits/settlement.go @@ -12,9 +12,16 @@ import ( "golang.org/x/time/rate" ) -// RateLimiter enforces a shared rate limit of 150 req/min (safely below LNbits' -// 200/min limit) across every caller that polls lnbits in a loop. -var RateLimiter = rate.NewLimiter(rate.Every(400*time.Millisecond), 1) +// LNbits allows 200 requests a minute. The callers that poll it in a loop get +// separate budgets that together stay below that, so heavy analytics traffic +// cannot starve a settlement check into reporting a settled payment as unknown. +var ( + // RateLimiter is the analytics budget: 120 req/min. + RateLimiter = rate.NewLimiter(rate.Every(500*time.Millisecond), 1) + // settlementLimiter is the payment settlement budget: 60 req/min, with a + // small burst so a new payment's first checks do not queue. + settlementLimiter = rate.NewLimiter(rate.Every(time.Second), 3) +) // rateLimitGrace lets a settlement check wait this long for a rate limit slot // past its own deadline, so a zero-timeout lookup still gets its one check. @@ -115,7 +122,7 @@ func (c Client) WaitForOutgoingPayment(w Wallet, paymentHash string, timeout tim interval := settlementPollInitial for { ctx, cancel := context.WithTimeout(context.Background(), time.Until(deadline)+rateLimitGrace) - err := RateLimiter.Wait(ctx) + err := settlementLimiter.Wait(ctx) cancel() if err != nil { if last.Err == nil { @@ -163,7 +170,7 @@ func (c Client) PriorPayment(w Wallet, paymentHash string) (settlement PaymentSe } ctx, cancel := context.WithTimeout(context.Background(), rateLimitGrace) defer cancel() - if err := RateLimiter.Wait(ctx); err != nil { + if err := settlementLimiter.Wait(ctx); err != nil { return PaymentSettlement{}, false, err } diff --git a/main.go b/main.go index 5ba14526..d1c064ee 100644 --- a/main.go +++ b/main.go @@ -38,6 +38,7 @@ func setLogger() { func main() { // set logger setLogger() + internal.CheckLnbitsConfiguration() // Create bot first bot := telegram.NewBot()