-
Notifications
You must be signed in to change notification settings - Fork 43
/
lnurl-withdraw.go
330 lines (297 loc) · 12 KB
/
lnurl-withdraw.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
package telegram
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/url"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
"github.com/LightningTipBot/LightningTipBot/internal/str"
lnurl "github.com/fiatjaf/go-lnurl"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
)
var (
withdrawConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
btnCancelWithdraw = paymentConfirmationMenu.Data("🚫 Cancel", "cancel_withdraw")
btnWithdraw = paymentConfirmationMenu.Data("✅ Withdraw", "confirm_withdraw")
)
// LnurlWithdrawState saves the state of the user for an LNURL payment
type LnurlWithdrawState struct {
*transaction.Base
From *lnbits.User `json:"from"`
LNURLWithdrawResponse lnurl.LNURLWithdrawResponse `json:"LNURLWithdrawResponse"`
LNURResponse lnurl.LNURLResponse `json:"LNURLResponse"`
Amount int `json:"amount"`
Comment string `json:"comment"`
LanguageCode string `json:"languagecode"`
Success bool `json:"success"`
Invoice lnbits.BitInvoice `json:"invoice"`
Message string `json:"message"`
}
// lnurlWithdrawHandler is invoked when the first lnurl response was a lnurl-withdraw response
// at this point, the user hans't necessarily entered an amount yet
func (bot *TipBot) lnurlWithdrawHandler(ctx context.Context, m *tb.Message, withdrawParams LnurlWithdrawState) {
user := LoadUser(ctx)
if user.Wallet == nil {
return
}
// object that holds all information about the send payment
id := fmt.Sprintf("lnurlw-%d-%s", m.Sender.ID, RandStringRunes(5))
LnurlWithdrawState := LnurlWithdrawState{
Base: transaction.New(transaction.ID(id)),
From: user,
LNURLWithdrawResponse: withdrawParams.LNURLWithdrawResponse,
LanguageCode: ctx.Value("publicLanguageCode").(string),
}
// first we check whether an amount is present in the command
amount, amount_err := decodeAmountFromCommand(m.Text)
// amount is already present in the command, i.e., /lnurl <amount> <LNURL>
// amount not in allowed range from LNURL
if amount_err == nil &&
(int64(amount) > (LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable/1000) || int64(amount) < (LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable/1000)) &&
(LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable != 0 && LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable != 0) { // only if max and min are set
err := fmt.Errorf("amount not in range")
log.Warnf("[lnurlWithdrawHandler] Error: %s", err.Error())
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable/1000, LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable/1000))
ResetUserState(user, bot)
return
}
// set also amount in the state of the user
LnurlWithdrawState.Amount = amount * 1000 // save as mSat
// add result to persistent struct
runtime.IgnoreError(LnurlWithdrawState.Set(LnurlWithdrawState, bot.Bunt))
// now we actualy check whether the amount was in the command and if not, ask for it
if amount_err != nil || amount < 1 {
// // no amount was entered, set user state and ask for amount
bot.askForAmount(ctx, id, "LnurlWithdrawState", LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable, LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable, m.Text)
return
}
// We need to save the pay state in the user state so we can load the payment in the next handler
paramsJson, err := json.Marshal(LnurlWithdrawState)
if err != nil {
log.Errorf("[lnurlWithdrawHandler] Error: %s", err.Error())
// bot.trySendMessage(m.Sender, err.Error())
return
}
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(paramsJson))
// directly go to confirm
bot.lnurlWithdrawHandlerWithdraw(ctx, m)
return
}
// lnurlWithdrawHandlerWithdraw is invoked when the user has delivered an amount and is ready to pay
func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx context.Context, m *tb.Message) {
user := LoadUser(ctx)
if user.Wallet == nil {
return
}
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlPreparingWithdraw"))
// assert that user has entered an amount
if user.StateKey != lnbits.UserHasEnteredAmount {
log.Errorln("[lnurlWithdrawHandlerWithdraw] state keys don't match")
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
}
// read the enter amount state from user.StateData
var enterAmountData EnterAmountStateData
err := json.Unmarshal([]byte(user.StateData), &enterAmountData)
if err != nil {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
}
// use the enter amount state of the user to load the LNURL payment state
tx := &LnurlWithdrawState{Base: transaction.New(transaction.ID(enterAmountData.ID))}
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
}
var lnurlWithdrawState *LnurlWithdrawState
switch fn.(type) {
case *LnurlWithdrawState:
lnurlWithdrawState = fn.(*LnurlWithdrawState)
default:
log.Errorf("[lnurlWithdrawHandlerWithdraw] invalid type")
}
confirmText := fmt.Sprintf(Translate(ctx, "confirmLnurlWithdrawMessage"), lnurlWithdrawState.Amount/1000)
if len(lnurlWithdrawState.LNURLWithdrawResponse.DefaultDescription) > 0 {
confirmText = confirmText + fmt.Sprintf(Translate(ctx, "confirmPayAppendMemo"), str.MarkdownEscape(lnurlWithdrawState.LNURLWithdrawResponse.DefaultDescription))
}
lnurlWithdrawState.Message = confirmText
// create inline buttons
withdrawButton := paymentConfirmationMenu.Data(Translate(ctx, "withdrawButtonMessage"), "confirm_withdraw")
btnCancelWithdraw := paymentConfirmationMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_withdraw")
withdrawButton.Data = lnurlWithdrawState.ID
btnCancelWithdraw.Data = lnurlWithdrawState.ID
withdrawConfirmationMenu.Inline(
withdrawConfirmationMenu.Row(
withdrawButton,
btnCancelWithdraw),
)
bot.tryEditMessage(statusMsg, confirmText, withdrawConfirmationMenu)
// // add response to persistent struct
// lnurlWithdrawState.LNURResponse = response2
runtime.IgnoreError(lnurlWithdrawState.Set(lnurlWithdrawState, bot.Bunt))
}
// confirmPayHandler when user clicked pay on payment confirmation
func (bot *TipBot) confirmWithdrawHandler(ctx context.Context, c *tb.Callback) {
tx := &LnurlWithdrawState{Base: transaction.New(transaction.ID(c.Data))}
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[confirmWithdrawHandler] Error: %s", err.Error())
return
}
var lnurlWithdrawState *LnurlWithdrawState
switch fn.(type) {
case *LnurlWithdrawState:
lnurlWithdrawState = fn.(*LnurlWithdrawState)
default:
log.Errorf("[confirmWithdrawHandler] invalid type")
}
// onnly the correct user can press
if lnurlWithdrawState.From.Telegram.ID != c.Sender.ID {
return
}
// immediatelly set intransaction to block duplicate calls
err = lnurlWithdrawState.Lock(lnurlWithdrawState, bot.Bunt)
if err != nil {
log.Errorf("[confirmWithdrawHandler] %s", err)
bot.tryDeleteMessage(c.Message)
bot.tryEditMessage(c.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
return
}
if !lnurlWithdrawState.Active {
log.Errorf("[confirmPayHandler] send not active anymore")
bot.tryEditMessage(c.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
bot.tryDeleteMessage(c.Message)
return
}
defer lnurlWithdrawState.Release(lnurlWithdrawState, bot.Bunt)
user := LoadUser(ctx)
if user.Wallet == nil {
bot.tryDeleteMessage(c.Message)
return
}
// reset state immediately
ResetUserState(user, bot)
// update button text
bot.tryEditMessage(
c.Message,
lnurlWithdrawState.Message,
&tb.ReplyMarkup{
InlineKeyboard: [][]tb.InlineButton{
{tb.InlineButton{Text: i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlPreparingWithdraw")}},
},
},
)
// lnurlWithdrawState loaded
client, err := bot.GetHttpClient()
if err != nil {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
return
}
callbackUrl, err := url.Parse(lnurlWithdrawState.LNURLWithdrawResponse.Callback)
if err != nil {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
return
}
// generate an invoice and add the pr to the request
// generate invoice
invoice, err := user.Wallet.Invoice(
lnbits.InvoiceParams{
Out: false,
Amount: int64(lnurlWithdrawState.Amount) / 1000,
Memo: "Withdraw",
Webhook: internal.Configuration.Lnbits.WebhookServer},
bot.Client)
if err != nil {
errmsg := fmt.Sprintf("[lnurlWithdrawHandlerWithdraw] Could not create an invoice: %s", err)
log.Errorln(errmsg)
return
}
lnurlWithdrawState.Invoice = invoice
qs := callbackUrl.Query()
// add amount to query string
qs.Set("pr", invoice.PaymentRequest)
qs.Set("k1", lnurlWithdrawState.LNURLWithdrawResponse.K1)
callbackUrl.RawQuery = qs.Encode()
res, err := client.Get(callbackUrl.String())
if err != nil || res.StatusCode >= 300 {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Failed.")
bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
return
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
return
}
// parse the response
var response2 lnurl.LNURLResponse
json.Unmarshal(body, &response2)
if response2.Status == "OK" {
// bot.trySendMessage(c.Sender, Translate(ctx, "lnurlWithdrawSuccess"))
// update button text
bot.tryEditMessage(
c.Message,
lnurlWithdrawState.Message,
&tb.ReplyMarkup{
InlineKeyboard: [][]tb.InlineButton{
{tb.InlineButton{Text: i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawSuccess")}},
},
},
)
} else {
log.Errorf("[lnurlWithdrawHandlerWithdraw] LNURLWithdraw failed.")
// bot.trySendMessage(c.Sender, Translate(ctx, "lnurlWithdrawFailed"))
// update button text
bot.tryEditMessage(
c.Message,
lnurlWithdrawState.Message,
&tb.ReplyMarkup{
InlineKeyboard: [][]tb.InlineButton{
{tb.InlineButton{Text: i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawFailed")}},
},
},
)
return
}
// add response to persistent struct
lnurlWithdrawState.LNURResponse = response2
runtime.IgnoreError(lnurlWithdrawState.Set(lnurlWithdrawState, bot.Bunt))
}
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
func (bot *TipBot) cancelWithdrawHandler(ctx context.Context, c *tb.Callback) {
// reset state immediately
user := LoadUser(ctx)
ResetUserState(user, bot)
tx := &LnurlWithdrawState{Base: transaction.New(transaction.ID(c.Data))}
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[cancelWithdrawHandler] Error: %s", err.Error())
return
}
var lnurlWithdrawState *LnurlWithdrawState
switch fn.(type) {
case *LnurlWithdrawState:
lnurlWithdrawState = fn.(*LnurlWithdrawState)
default:
log.Errorf("[cancelWithdrawHandler] invalid type")
}
// onnly the correct user can press
if lnurlWithdrawState.From.Telegram.ID != c.Sender.ID {
return
}
bot.tryEditMessage(c.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawCancelled"), &tb.ReplyMarkup{})
lnurlWithdrawState.InTransaction = false
lnurlWithdrawState.Inactivate(lnurlWithdrawState, bot.Bunt)
}