get_balance_controller.go raw
1 package controllers
2
3 import (
4 "context"
5
6 "github.com/getAlby/go-nostr"
7 "github.com/getAlby/hub/db"
8 "github.com/getAlby/hub/db/queries"
9 "github.com/getAlby/hub/logger"
10 "github.com/getAlby/hub/nip47/models"
11 "github.com/sirupsen/logrus"
12 )
13
14 const (
15 MSAT_PER_SAT = 1000
16 )
17
18 type getBalanceResponse struct {
19 Balance int64 `json:"balance"`
20 // MaxAmount int `json:"max_amount"`
21 // BudgetRenewal string `json:"budget_renewal"`
22 }
23
24 func (controller *nip47Controller) HandleGetBalanceEvent(ctx context.Context, nip47Request *models.Request, requestEventId uint, app *db.App, publishResponse publishFunc) {
25
26 logger.Logger.WithFields(logrus.Fields{
27 "request_event_id": requestEventId,
28 }).Debug("Getting balance")
29
30 balanceMsat := int64(0)
31 if app.Isolated {
32 var err error
33 balanceMsat, err = queries.GetIsolatedBalanceMsat(controller.db, app.ID)
34 if err != nil {
35 logger.Logger.WithFields(logrus.Fields{
36 "request_event_id": requestEventId,
37 }).WithError(err).Error("Failed to fetch isolated balance")
38 publishResponse(&models.Response{
39 ResultType: nip47Request.Method,
40 Error: mapNip47Error(err),
41 }, nostr.Tags{})
42 return
43 }
44 } else {
45 balances, err := controller.lnClient.GetBalances(ctx, true)
46 if err != nil {
47 logger.Logger.WithFields(logrus.Fields{
48 "request_event_id": requestEventId,
49 }).WithError(err).Error("Failed to fetch balance")
50 publishResponse(&models.Response{
51 ResultType: nip47Request.Method,
52 Error: mapNip47Error(err),
53 }, nostr.Tags{})
54 return
55 }
56 balanceMsat = balances.Lightning.TotalSpendableMsat
57 }
58
59 responsePayload := &getBalanceResponse{
60 Balance: balanceMsat,
61 }
62
63 // this is not part of the spec and does not seem to be used
64 /*appPermission := db.AppPermission{}
65 controller.db.Where("app_id = ? AND request_method = ?", app.ID, models.PAY_INVOICE_METHOD).First(&appPermission)
66
67 maxAmount := appPermission.MaxAmount
68 if maxAmount > 0 {
69 responsePayload.MaxAmount = maxAmount * MSAT_PER_SAT
70 responsePayload.BudgetRenewal = appPermission.BudgetRenewal
71 }*/
72
73 publishResponse(&models.Response{
74 ResultType: nip47Request.Method,
75 Result: responsePayload,
76 }, nostr.Tags{})
77 }
78