"""BTC year-end rates and the money conversion helpers. Amounts are integer ore (NOK) and integer sats (BTC). No floating point is used. """ import database SATS_PER_BTC = 100_000_000 ORE_PER_NOK = 100 SPACE = "\u00a0" def year_end_date(tax_year): """Return the 1 January date that carries the rate for a tax year.""" return "%04d-01-01" % (int(tax_year) + 1) def get_rate(tax_year, conn=None): """Return the year-end rate for a tax year in ore per BTC, or None.""" own = conn is None if own: conn = database.connect() try: row = conn.execute( "SELECT nok_per_btc_ore FROM prices WHERE asset = 'BTC' AND date = ?", (year_end_date(tax_year),), ).fetchone() finally: if own: conn.close() return row["nok_per_btc_ore"] if row else None def set_rate(date, nok_per_btc_ore, source="", conn=None): """Set or override one BTC rate, in ore per BTC.""" own = conn is None if own: conn = database.connect() try: conn.execute( "INSERT INTO prices (asset, date, nok_per_btc_ore, source)" " VALUES ('BTC', ?, ?, ?)" " ON CONFLICT(asset, date) DO UPDATE SET" " nok_per_btc_ore = excluded.nok_per_btc_ore, source = excluded.source", (date, int(nok_per_btc_ore), source), ) conn.commit() finally: if own: conn.close() def list_rates(conn=None): """Return every stored BTC rate, newest date first.""" own = conn is None if own: conn = database.connect() try: rows = conn.execute( "SELECT date, nok_per_btc_ore, source FROM prices" " WHERE asset = 'BTC' ORDER BY date DESC" ).fetchall() finally: if own: conn.close() return [dict(row) for row in rows] def _strip(text): return str(text).replace(SPACE, " ").replace(" ", "").strip() def _split(text): """Split a decimal string into (negative, whole digits, fraction digits).""" cleaned = _strip(text) if not cleaned: raise ValueError("empty amount") if "," in cleaned and "." in cleaned: raise ValueError("mixed decimal separators") cleaned = cleaned.replace(",", ".") negative = cleaned.startswith("-") if negative: cleaned = cleaned[1:] if cleaned.count(".") > 1: raise ValueError("more than one decimal separator") whole, _, fraction = cleaned.partition(".") if not whole and not fraction: raise ValueError("no digits") if whole and not whole.isdigit(): raise ValueError("not a number") if fraction and not fraction.isdigit(): raise ValueError("not a number") return negative, whole or "0", fraction def _apply_sign(negative, amount): return -amount if negative else amount def group_int(digits): """Insert spaces as thousands separators into a whole number.""" digits = str(int(digits)) parts = [] while len(digits) > 3: parts.insert(0, digits[-3:]) digits = digits[:-3] parts.insert(0, digits) return " ".join(parts) def nok_to_ore(text): """Convert a NOK amount to integer ore. Accepts ',' or '.' as separator.""" negative, whole, fraction = _split(text) if len(fraction) > 2: raise ValueError("more than 2 decimals") return _apply_sign(negative, int(whole) * ORE_PER_NOK + int(fraction.ljust(2, "0"))) def ore_to_nok(ore): """Format integer ore as a Norwegian amount without the currency.""" ore = int(ore) negative = ore < 0 ore = abs(ore) text = "%s,%02d" % (group_int(ore // ORE_PER_NOK), ore % ORE_PER_NOK) return "-" + text if negative else text def parse_btc_to_sats(text): """Convert a BTC amount to integer sats. Accepts ',' or '.' as separator.""" negative, whole, fraction = _split(text) if len(fraction) > 8: raise ValueError("more than 8 decimals") return _apply_sign(negative, int(whole) * SATS_PER_BTC + int(fraction.ljust(8, "0"))) def sats_to_btc(sats): """Format integer sats as a BTC amount with 8 decimals.""" sats = int(sats) negative = sats < 0 sats = abs(sats) text = "%d,%08d" % (sats // SATS_PER_BTC, sats % SATS_PER_BTC) return "-" + text if negative else text