75 lines
2.1 KiB
Go
75 lines
2.1 KiB
Go
package handler
|
|
|
|
import (
|
|
"database/sql"
|
|
"time"
|
|
|
|
"git.ekzyis.com/ekzyis/delphi.market/server/router/context"
|
|
"git.ekzyis.com/ekzyis/delphi.market/server/router/pages/components"
|
|
"git.ekzyis.com/ekzyis/delphi.market/types"
|
|
"github.com/a-h/templ"
|
|
"github.com/labstack/echo/v4"
|
|
"github.com/lightningnetwork/lnd/lnrpc/invoicesrpc"
|
|
"github.com/lightningnetwork/lnd/lntypes"
|
|
"github.com/lightningnetwork/lnd/lnwire"
|
|
)
|
|
|
|
func HandleCreate(sc context.Context) echo.HandlerFunc {
|
|
return func(c echo.Context) error {
|
|
var (
|
|
db = sc.Db
|
|
lnd = sc.Lnd
|
|
tx *sql.Tx
|
|
ctx = c.Request().Context()
|
|
u = c.Get("session").(types.User)
|
|
question = c.FormValue("question")
|
|
description = c.FormValue("description")
|
|
endDate = c.FormValue("end_date")
|
|
hash lntypes.Hash
|
|
paymentRequest string
|
|
amount = lnwire.MilliSatoshi(1000)
|
|
expiry = int64(600)
|
|
expiresAt = time.Now().Add(time.Second * time.Duration(expiry))
|
|
invoiceId int
|
|
qr templ.Component
|
|
err error
|
|
)
|
|
// TODO: validation
|
|
|
|
if tx, err = db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted}); err != nil {
|
|
return err
|
|
}
|
|
|
|
if hash, paymentRequest, err = lnd.Client.AddInvoice(ctx,
|
|
&invoicesrpc.AddInvoiceData{
|
|
Value: amount,
|
|
Expiry: expiry,
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
|
|
if err = db.QueryRowContext(ctx, ""+
|
|
"INSERT INTO invoices (user_id, msats, hash, bolt11, expires_at) "+
|
|
"VALUES ($1, $2, $3, $4, $5) "+
|
|
"RETURNING id",
|
|
u.Id, amount, hash.String(), paymentRequest, expiresAt).Scan(&invoiceId); err != nil {
|
|
return err
|
|
}
|
|
|
|
if _, err = tx.ExecContext(ctx, ""+
|
|
"INSERT INTO markets (question, description, end_date, user_id, invoice_id) "+
|
|
"VALUES ($1, $2, $3, $4, $5)",
|
|
question, description, endDate, u.Id, invoiceId); err != nil {
|
|
return err
|
|
}
|
|
|
|
if err = tx.Commit(); err != nil {
|
|
return err
|
|
}
|
|
|
|
qr = components.Invoice(hash.String(), paymentRequest, int(amount), int(expiry), false)
|
|
|
|
return components.Modal(qr).Render(context.RenderContext(sc, c), c.Response().Writer)
|
|
}
|
|
}
|