000007_fx.up.sql35 lines, 1.6 KB
| 1 | BEGIN; |
| 2 | |
| 3 | -- The house's side of every conversion, one account per currency. It takes in |
| 4 | -- what customers sell, and pays out what they buy: its balances are our |
| 5 | -- position in each currency. Fees are revenue, in an account of their own. |
| 6 | INSERT INTO accounts (kind, name, currency, normal_balance) VALUES |
| 7 | ('system', 'fx', 'EUR', 'credit'), |
| 8 | ('system', 'fx', 'GBP', 'credit'), |
| 9 | ('system', 'fx', 'JPY', 'credit'), |
| 10 | ('system', 'fx', 'USD', 'credit'), |
| 11 | ('system', 'fx_fees', 'EUR', 'credit'), |
| 12 | ('system', 'fx_fees', 'GBP', 'credit'), |
| 13 | ('system', 'fx_fees', 'JPY', 'credit'), |
| 14 | ('system', 'fx_fees', 'USD', 'credit'); |
| 15 | |
| 16 | -- A price we promised: this much of one currency, for that much of another, |
| 17 | -- until it expires. Clients only ever send its ID back, never the terms. |
| 18 | CREATE TABLE fx_quotes ( |
| 19 | id uuid PRIMARY KEY, |
| 20 | owner_id uuid NOT NULL, |
| 21 | sell_currency text NOT NULL, |
| 22 | sell_amount bigint NOT NULL CHECK (sell_amount > 0), |
| 23 | buy_currency text NOT NULL CHECK (buy_currency <> sell_currency), |
| 24 | buy_amount bigint NOT NULL CHECK (buy_amount > 0), |
| 25 | -- in the sell currency, on top of sell_amount |
| 26 | fee bigint NOT NULL CHECK (fee >= 0), |
| 27 | -- buy per sell, in ten-billionths: fx.Rate |
| 28 | rate bigint NOT NULL CHECK (rate > 0), |
| 29 | expires_at timestamptz NOT NULL, |
| 30 | created_at timestamptz NOT NULL DEFAULT now(), |
| 31 | -- the conversion that used it: a quote is used once, at most |
| 32 | transaction_id uuid UNIQUE REFERENCES transactions (id) |
| 33 | ); |
| 34 | |
| 35 | COMMIT; |