forked from getAlby/nostr-wallet-connect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handle_balance_request.go
89 lines (75 loc) · 2.39 KB
/
handle_balance_request.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"context"
"fmt"
"github.com/nbd-wtf/go-nostr"
"github.com/sirupsen/logrus"
)
const (
MSAT_PER_SAT = 1000
)
func (svc *Service) HandleGetBalanceEvent(ctx context.Context, request *Nip47Request, event *nostr.Event, app App, ss []byte) (result *nostr.Event, err error) {
nostrEvent := NostrEvent{App: app, NostrId: event.ID, Content: event.Content, State: "received"}
err = svc.db.Create(&nostrEvent).Error
if err != nil {
svc.Logger.WithFields(logrus.Fields{
"eventId": event.ID,
"eventKind": event.Kind,
"appId": app.ID,
}).Errorf("Failed to save nostr event: %v", err)
return nil, err
}
hasPermission, code, message := svc.hasPermission(&app, event, request.Method, 0)
if !hasPermission {
svc.Logger.WithFields(logrus.Fields{
"eventId": event.ID,
"eventKind": event.Kind,
"appId": app.ID,
}).Errorf("App does not have permission: %s %s", code, message)
return svc.createResponse(event, Nip47Response{
ResultType: NIP_47_GET_BALANCE_METHOD,
Error: &Nip47Error{
Code: code,
Message: message,
}}, ss)
}
svc.Logger.WithFields(logrus.Fields{
"eventId": event.ID,
"eventKind": event.Kind,
"appId": app.ID,
}).Info("Fetching balance")
balance, err := svc.lnClient.GetBalance(ctx, event.PubKey)
if err != nil {
svc.Logger.WithFields(logrus.Fields{
"eventId": event.ID,
"eventKind": event.Kind,
"appId": app.ID,
}).Infof("Failed to fetch balance: %v", err)
nostrEvent.State = NOSTR_EVENT_STATE_HANDLER_ERROR
svc.db.Save(&nostrEvent)
return svc.createResponse(event, Nip47Response{
ResultType: NIP_47_GET_BALANCE_METHOD,
Error: &Nip47Error{
Code: NIP_47_ERROR_INTERNAL,
Message: fmt.Sprintf("Something went wrong while fetching balance: %s", err.Error()),
},
}, ss)
}
responsePayload := &Nip47BalanceResponse{
Balance: balance * MSAT_PER_SAT,
}
appPermission := AppPermission{}
svc.db.Where("app_id = ? AND request_method = ?", app.ID, NIP_47_PAY_INVOICE_METHOD).First(&appPermission)
maxAmount := appPermission.MaxAmount
if maxAmount > 0 {
responsePayload.MaxAmount = maxAmount * MSAT_PER_SAT
responsePayload.BudgetRenewal = appPermission.BudgetRenewal
}
nostrEvent.State = NOSTR_EVENT_STATE_HANDLER_EXECUTED
svc.db.Save(&nostrEvent)
return svc.createResponse(event, Nip47Response{
ResultType: NIP_47_GET_BALANCE_METHOD,
Result: responsePayload,
},
ss)
}