fx.go248 lines, 8.2 KB
| 1 | package wallet |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "time" |
| 8 | |
| 9 | "github.com/fiston-user/payments/internal/fx" |
| 10 | "github.com/fiston-user/payments/internal/platform/apperr" |
| 11 | "github.com/fiston-user/payments/internal/wallet/walletdb" |
| 12 | "github.com/fiston-user/payments/internal/wallet/walletevents" |
| 13 | "github.com/google/uuid" |
| 14 | "github.com/jackc/pgx/v5" |
| 15 | ) |
| 16 | |
| 17 | // The house's system accounts for conversions, one of each per currency: our |
| 18 | // position in the currency, and the fees we've earned in it. |
| 19 | const ( |
| 20 | FXAccount = "fx" |
| 21 | FXFeesAccount = "fx_fees" |
| 22 | ) |
| 23 | |
| 24 | type FXQuote = walletdb.FXQuote |
| 25 | |
| 26 | var ( |
| 27 | ErrQuoteNotFound = fmt.Errorf("quote %w", apperr.ErrNotFound) |
| 28 | ErrQuoteExpired = apperr.NewRule("quote_expired", "quote expired: ask for a new one") |
| 29 | ErrQuoteUsed = apperr.NewRule("quote_used", "quote was already used") |
| 30 | ErrNoWallet = apperr.NewRule("wallet_required", "open a wallet in that currency first") |
| 31 | ) |
| 32 | |
| 33 | // FX is how a Service converts: where rates come from, how long a quote's |
| 34 | // price holds, and our fee, in basis points of what the customer sells. |
| 35 | type FX struct { |
| 36 | Rates fx.Provider |
| 37 | QuoteTTL time.Duration |
| 38 | FeeBps int64 |
| 39 | } |
| 40 | |
| 41 | // WithFX returns a Service that converts between currencies, as cfg says. |
| 42 | func (s *Service) WithFX(cfg FX) *Service { |
| 43 | c := *s |
| 44 | c.fx = cfg |
| 45 | return &c |
| 46 | } |
| 47 | |
| 48 | // A QuoteRequest asks the price of selling From for To: either how much of |
| 49 | // From to sell, or how much of To to buy. |
| 50 | type QuoteRequest struct { |
| 51 | From string `json:"from"` |
| 52 | To string `json:"to"` |
| 53 | SellAmount int64 `json:"sell_amount"` |
| 54 | BuyAmount int64 `json:"buy_amount"` |
| 55 | } |
| 56 | |
| 57 | // Quote prices a conversion for owner, at the provider's rate plus our fee, |
| 58 | // and keeps the price for QuoteTTL: the owner can take it, once. |
| 59 | func (s *Service) Quote(ctx context.Context, owner uuid.UUID, req QuoteRequest) (FXQuote, error) { |
| 60 | var v apperr.ValidationError |
| 61 | for field, currency := range map[string]string{"from": req.From, "to": req.To} { |
| 62 | _, err := s.store.SystemAccount(ctx, FXAccount, currency) |
| 63 | if errors.Is(err, ErrAccountNotFound) { |
| 64 | v.Add(field, "unsupported currency") |
| 65 | } else if err != nil { |
| 66 | return FXQuote{}, err |
| 67 | } |
| 68 | } |
| 69 | if req.From == req.To { |
| 70 | v.Add("to", "must be a different currency") |
| 71 | } |
| 72 | sell, buy := req.SellAmount, req.BuyAmount |
| 73 | if (sell == 0) == (buy == 0) { |
| 74 | v.Add("sell_amount", "set either sell_amount or buy_amount") |
| 75 | } |
| 76 | for field, n := range map[string]int64{"sell_amount": sell, "buy_amount": buy} { |
| 77 | if n < 0 || n > MaxAmount { |
| 78 | v.Add(field, fmt.Sprintf("must be between 1 and %d", MaxAmount)) |
| 79 | } |
| 80 | } |
| 81 | if err := v.Err(); err != nil { |
| 82 | return FXQuote{}, err |
| 83 | } |
| 84 | |
| 85 | rate, err := s.fx.Rates.Rate(ctx, req.From, req.To) |
| 86 | if err != nil { |
| 87 | return FXQuote{}, fmt.Errorf("rate for %s/%s: %w", req.From, req.To, err) |
| 88 | } |
| 89 | // What the customer gets rounds down, and what they pay rounds up: the |
| 90 | // fraction of a cent in between is never ours to give away. |
| 91 | if sell > 0 { |
| 92 | buy, err = fx.Convert(sell, req.From, req.To, rate, fx.Down) |
| 93 | } else { |
| 94 | sell, err = fx.Cost(buy, req.From, req.To, rate) |
| 95 | } |
| 96 | if err != nil { |
| 97 | return FXQuote{}, err |
| 98 | } |
| 99 | switch { |
| 100 | case buy == 0: |
| 101 | v.Add("sell_amount", "too small to buy anything") |
| 102 | case sell > MaxAmount: |
| 103 | v.Add("buy_amount", fmt.Sprintf("would cost more than %d", MaxAmount)) |
| 104 | } |
| 105 | if err := v.Err(); err != nil { |
| 106 | return FXQuote{}, err |
| 107 | } |
| 108 | return s.store.CreateQuote(ctx, walletdb.CreateQuoteParams{ |
| 109 | ID: uuid.Must(uuid.NewV7()), OwnerID: owner, |
| 110 | SellCurrency: req.From, SellAmount: sell, BuyCurrency: req.To, BuyAmount: buy, |
| 111 | Fee: fx.Fee(sell, s.fx.FeeBps), Rate: rate, TtlSeconds: s.fx.QuoteTTL.Seconds(), |
| 112 | }) |
| 113 | } |
| 114 | |
| 115 | // Convert takes quote id, for owner: it moves exactly what the quote says, |
| 116 | // between the owner's wallets in its two currencies, or nothing at all. |
| 117 | func (s *Service) Convert(ctx context.Context, owner, id uuid.UUID) (FXQuote, error) { |
| 118 | return s.store.Convert(ctx, owner, id) |
| 119 | } |
| 120 | |
| 121 | // CreateQuote stores a quote. It expires TtlSeconds from now, by the |
| 122 | // database's clock. |
| 123 | func (s *Store) CreateQuote(ctx context.Context, p walletdb.CreateQuoteParams) (FXQuote, error) { |
| 124 | quote, err := s.q.CreateQuote(ctx, p) |
| 125 | if err != nil { |
| 126 | return FXQuote{}, fmt.Errorf("create quote: %w", err) |
| 127 | } |
| 128 | return quote, nil |
| 129 | } |
| 130 | |
| 131 | // Convert posts quote id as one transaction, and marks it used in the same |
| 132 | // one: however many requests race for a quote, it converts once. It returns |
| 133 | // the quote, with the transaction that used it. |
| 134 | func (s *Store) Convert(ctx context.Context, owner, id uuid.UUID) (FXQuote, error) { |
| 135 | var used FXQuote |
| 136 | err := s.inTx(ctx, func(q *walletdb.Queries) error { |
| 137 | quote, err := q.LockQuote(ctx, walletdb.LockQuoteParams{ID: id, OwnerID: owner}) |
| 138 | switch { |
| 139 | case errors.Is(err, pgx.ErrNoRows): |
| 140 | return ErrQuoteNotFound |
| 141 | case err != nil: |
| 142 | return fmt.Errorf("lock quote %s: %w", id, err) |
| 143 | case quote.TransactionID != nil: |
| 144 | return fmt.Errorf("quote %s: %w", id, ErrQuoteUsed) |
| 145 | case quote.Expired: |
| 146 | return fmt.Errorf("quote %s: %w", id, ErrQuoteExpired) |
| 147 | } |
| 148 | |
| 149 | sell, buy := quote.SellCurrency, quote.BuyCurrency |
| 150 | from, err := ownWallet(ctx, q, owner, sell) |
| 151 | if err != nil { |
| 152 | return err |
| 153 | } |
| 154 | to, err := ownWallet(ctx, q, owner, buy) |
| 155 | if err != nil { |
| 156 | return err |
| 157 | } |
| 158 | if err := lockInOrder(ctx, q, from.ID, to.ID); err != nil { |
| 159 | return err |
| 160 | } |
| 161 | b, err := q.GetAccountBalance(ctx, from.ID) |
| 162 | if err != nil { |
| 163 | return fmt.Errorf("get balance %s: %w", from.ID, err) |
| 164 | } |
| 165 | if b.Balance < quote.SellAmount+quote.Fee { |
| 166 | return fmt.Errorf("wallet %s: %w", from.ID, ErrInsufficientFunds) |
| 167 | } |
| 168 | |
| 169 | fxSell, err := systemAccount(ctx, q, FXAccount, sell) |
| 170 | if err != nil { |
| 171 | return err |
| 172 | } |
| 173 | fxBuy, err := systemAccount(ctx, q, FXAccount, buy) |
| 174 | if err != nil { |
| 175 | return err |
| 176 | } |
| 177 | fees, err := systemAccount(ctx, q, FXFeesAccount, sell) |
| 178 | if err != nil { |
| 179 | return err |
| 180 | } |
| 181 | |
| 182 | // Four entries convert, and each currency balances on its own: their |
| 183 | // dollars go to our dollar account, and our euro account pays them euros. |
| 184 | postings := []Posting{ |
| 185 | {AccountID: from.ID, Direction: Debit, Amount: quote.SellAmount, Currency: sell}, |
| 186 | {AccountID: fxSell.ID, Direction: Credit, Amount: quote.SellAmount, Currency: sell}, |
| 187 | {AccountID: fxBuy.ID, Direction: Debit, Amount: quote.BuyAmount, Currency: buy}, |
| 188 | {AccountID: to.ID, Direction: Credit, Amount: quote.BuyAmount, Currency: buy}, |
| 189 | } |
| 190 | // Two more pay the fee, from the customer to our revenue. |
| 191 | if quote.Fee > 0 { |
| 192 | postings = append(postings, |
| 193 | Posting{AccountID: from.ID, Direction: Debit, Amount: quote.Fee, Currency: sell}, |
| 194 | Posting{AccountID: fees.ID, Direction: Credit, Amount: quote.Fee, Currency: sell}, |
| 195 | ) |
| 196 | } |
| 197 | posted, err := insertTransaction(ctx, q, NewTransaction{ |
| 198 | Description: "fx conversion", Postings: postings, |
| 199 | }) |
| 200 | if err != nil { |
| 201 | return err |
| 202 | } |
| 203 | used, err = q.UseQuote(ctx, walletdb.UseQuoteParams{ID: id, TransactionID: &posted.ID}) |
| 204 | if err != nil { |
| 205 | return fmt.Errorf("use quote %s: %w", id, err) |
| 206 | } |
| 207 | return enqueue(ctx, q, walletevents.ConversionCompleted, from.ID, walletevents.Conversion{ |
| 208 | TransactionID: posted.ID, |
| 209 | QuoteID: id, |
| 210 | From: eventWallet(from), |
| 211 | To: eventWallet(to), |
| 212 | Sold: quote.SellAmount, |
| 213 | Fee: quote.Fee, |
| 214 | Bought: quote.BuyAmount, |
| 215 | Rate: quote.Rate, |
| 216 | }) |
| 217 | }) |
| 218 | if err != nil { |
| 219 | return FXQuote{}, fmt.Errorf("convert: %w", err) |
| 220 | } |
| 221 | return used, nil |
| 222 | } |
| 223 | |
| 224 | // ownWallet returns owner's wallet in currency cur, if they have one, and if |
| 225 | // it can move money. |
| 226 | func ownWallet(ctx context.Context, q *walletdb.Queries, owner uuid.UUID, cur string) (Account, error) { |
| 227 | w, err := q.GetWalletByCurrency(ctx, walletdb.GetWalletByCurrencyParams{ |
| 228 | OwnerID: &owner, Currency: cur, |
| 229 | }) |
| 230 | switch { |
| 231 | case errors.Is(err, pgx.ErrNoRows): |
| 232 | return Account{}, fmt.Errorf("no %s wallet: %w", cur, ErrNoWallet) |
| 233 | case err != nil: |
| 234 | return Account{}, fmt.Errorf("get %s wallet: %w", cur, err) |
| 235 | case w.Frozen: |
| 236 | return Account{}, fmt.Errorf("wallet %s: %w", w.ID, ErrWalletFrozen) |
| 237 | } |
| 238 | return w, nil |
| 239 | } |
| 240 | |
| 241 | // systemAccount returns one of our accounts, inside a transaction. |
| 242 | func systemAccount(ctx context.Context, q *walletdb.Queries, name, currency string) (Account, error) { |
| 243 | acc, err := q.GetSystemAccount(ctx, walletdb.GetSystemAccountParams{Name: name, Currency: currency}) |
| 244 | if err != nil { |
| 245 | return Account{}, fmt.Errorf("%s account %s: %w", name, currency, err) |
| 246 | } |
| 247 | return acc, nil |
| 248 | } |