Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions docs/invoice-payments-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
```

Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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. |
Expand Down
2 changes: 1 addition & 1 deletion internal/api/analytics.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
41 changes: 11 additions & 30 deletions internal/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"fmt"
"net"
"net/url"
"os"
"strings"
"time"

Expand Down Expand Up @@ -159,7 +158,7 @@ func init() {
panic(err)
}
Configuration.Bot.LNURLHostUrl = hostname
checkLnbitsConfiguration()
normalizeLnbitsConfiguration()
setAPISendDefaults()
setAPIAnalyticsDefaults()
}
Expand All @@ -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 {
Expand Down
17 changes: 12 additions & 5 deletions internal/lnbits/settlement.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
}

Expand Down
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ func setLogger() {
func main() {
// set logger
setLogger()
internal.CheckLnbitsConfiguration()

// Create bot first
bot := telegram.NewBot()
Expand Down
Loading