listings.go raw

   1  package bridge
   2  
   3  import (
   4  	"context"
   5  	"fmt"
   6  	"strconv"
   7  	"time"
   8  
   9  	"git.smesh.lol/nostrino/pkg/listing"
  10  	"git.smesh.lol/nostrino/pkg/nwc"
  11  	"git.smesh.lol/nostrino/pkg/relay"
  12  )
  13  
  14  // wallet opens the operator's NWC connection. Every money path goes through here, so there is one
  15  // place that knows how a wallet is reached and what it means to have none configured.
  16  func (s *Server) wallet(ctx context.Context) (*nwc.Client, error) {
  17  	s.billingMu.Lock()
  18  	connection := s.billing.Wallet
  19  	s.billingMu.Unlock()
  20  
  21  	if connection == "" {
  22  		return nil, fmt.Errorf("no wallet is configured: send billing-set -arg wallet=nostr+walletconnect://…")
  23  	}
  24  
  25  	conn, err := nwc.ParseURI(connection)
  26  
  27  	if err != nil {
  28  		return nil, err
  29  	}
  30  
  31  	transport, err := relay.DialTransport(conn.RelayURL)
  32  
  33  	if err != nil {
  34  		return nil, err
  35  	}
  36  
  37  	return nwc.Dial(ctx, conn, transport)
  38  }
  39  
  40  // quoteListing prices a swap and asks the wallet for an invoice for it. The listing is not lodged
  41  // until that invoice settles, which is what quoteListingIDLodged reports.
  42  func (s *Server) quoteListing(ctx context.Context, id string, btcSats int64) (map[string]any, error) {
  43  	if id == "" {
  44  		return nil, fmt.Errorf("listing-quote needs -arg id=<swap id>")
  45  	}
  46  
  47  	if btcSats <= 0 {
  48  		return nil, fmt.Errorf("listing-quote needs -arg btc_sats=<the BTC leg of the swap>")
  49  	}
  50  
  51  	s.billingMu.Lock()
  52  	fee := s.billing.ListingFee(btcSats)
  53  	margin := s.billing.SwapFeeBPS
  54  	s.billingMu.Unlock()
  55  
  56  	reply := map[string]any{"id": id, "btc_sats": btcSats, "fee_sats": fee, "swap_fee_bps": margin}
  57  
  58  	// A gateway that charges nothing has nothing to gate.
  59  	if fee == 0 {
  60  		reply["lodged"] = true
  61  		reply["free"] = true
  62  
  63  		return reply, nil
  64  	}
  65  
  66  	if s.listings != nil && s.listings.Lodged(id) {
  67  		reply["lodged"] = true
  68  		reply["already_paid"] = true
  69  
  70  		return reply, nil
  71  	}
  72  
  73  	client, err := s.wallet(ctx)
  74  
  75  	if err != nil {
  76  		return nil, err
  77  	}
  78  
  79  	defer client.Close()
  80  
  81  	made, err := client.MakeInvoice(ctx, fee, "listing "+id)
  82  
  83  	if err != nil {
  84  		return nil, fmt.Errorf("the wallet did not make an invoice: %w", err)
  85  	}
  86  
  87  	// The wallet's payment hash is the reference the listing is bound to.
  88  	hash := made.PaymentHash
  89  	invoice := made.Invoice
  90  
  91  	if s.listings != nil {
  92  		if err := s.listings.Record(listing.Quote{
  93  			ID:          id,
  94  			PaymentHash: hash,
  95  			Invoice:     invoice,
  96  			AmountSats:  fee,
  97  			FeeBPS:      margin,
  98  			CreatedAt:   time.Now().UTC().Format(time.RFC3339),
  99  		}); err != nil {
 100  			return nil, err
 101  		}
 102  	}
 103  
 104  	reply["invoice"] = invoice
 105  	reply["payment_hash"] = hash
 106  	reply["lodged"] = false
 107  
 108  	return reply, nil
 109  }
 110  
 111  // settleListing asks the wallet whether the invoice was paid, and records the answer.
 112  func (s *Server) settleListing(ctx context.Context, id string) (map[string]any, error) {
 113  	if s.listings == nil {
 114  		return nil, fmt.Errorf("this gateway keeps no listing quotes")
 115  	}
 116  
 117  	quote, ok := s.listings.Quotes[id]
 118  
 119  	if !ok {
 120  		return nil, fmt.Errorf("no quote for %s", id)
 121  	}
 122  
 123  	if s.listings.Lodged(id) {
 124  		return map[string]any{"id": id, "lodged": true, "paid_at": quote.PaidAt}, nil
 125  	}
 126  
 127  	client, err := s.wallet(ctx)
 128  
 129  	if err != nil {
 130  		return nil, err
 131  	}
 132  
 133  	defer client.Close()
 134  
 135  	invoice, err := client.LookupInvoice(ctx, quote.PaymentHash)
 136  
 137  	if err != nil {
 138  		return nil, err
 139  	}
 140  
 141  	settled := invoice.SettledAt > 0 || invoice.Preimage != ""
 142  
 143  	if !settled {
 144  		return map[string]any{"id": id, "lodged": false, "fee_sats": quote.AmountSats}, nil
 145  	}
 146  
 147  	paidAt := time.Now()
 148  
 149  	if invoice.SettledAt > 0 {
 150  		paidAt = time.Unix(invoice.SettledAt, 0)
 151  	}
 152  
 153  	if err := s.listings.Settle(id, paidAt); err != nil {
 154  		return nil, err
 155  	}
 156  
 157  	return map[string]any{"id": id, "lodged": true, "fee_sats": quote.AmountSats,
 158  		"paid_at": paidAt.UTC().Format(time.RFC3339)}, nil
 159  }
 160  
 161  // listingStatus reports what is waiting for payment.
 162  func (s *Server) listingStatus() map[string]any {
 163  	if s.listings == nil {
 164  		return map[string]any{"pending": []any{}}
 165  	}
 166  
 167  	pending := s.listings.Pending()
 168  	out := make([]map[string]any, 0, len(pending))
 169  
 170  	for _, quote := range pending {
 171  		out = append(out, map[string]any{
 172  			"id": quote.ID, "fee_sats": quote.AmountSats,
 173  			"payment_hash": quote.PaymentHash, "created_at": quote.CreatedAt,
 174  		})
 175  	}
 176  
 177  	return map[string]any{"pending": out}
 178  }
 179  
 180  func parseSats(value string) (int64, error) {
 181  	n, err := strconv.ParseInt(value, 10, 64)
 182  
 183  	if err != nil {
 184  		return 0, fmt.Errorf("%q is not a whole number of sats", value)
 185  	}
 186  
 187  	if n < 0 {
 188  		return 0, fmt.Errorf("a negative amount is not a price")
 189  	}
 190  
 191  	return n, nil
 192  }
 193