diff --git a/ledger.py b/ledger.py index b49f41e..3434fc9 100644 --- a/ledger.py +++ b/ledger.py @@ -321,30 +321,20 @@ def _split_capped(total, weights): return cuts -def _split_even(total, weights): - """Hand out `total` over the weights so that the parts sum to exactly `total`.""" - total = int(total) - weight_sum = sum(weights) - if total <= 0 or not weights or weight_sum <= 0: - return [0] * len(weights) - cuts = [total * weight // weight_sum for weight in weights] - cuts[-1] = total - sum(cuts[:-1]) - return cuts - - def _mirror_transfer(conn, tx): """Create the destination lots of a generated transfer_in. - One lot per consumed part of the matching transfer_out, keeping the original - acquisition date and cost. The sats fee lowers what arrives and the NOK fee - raises the cost basis. + The sent sats arrive in full, so the mirrored lots cover exactly the sent + amount: one lot per consumed part of the matching transfer_out, in order, + keeping the acquisition date and the cost per sat. The sats of a fee, and + their share of the cost, stay behind with the fee (docs/spec.md section 3.3). """ group = tx["transfer_group"] if not group: return [] source = conn.execute( - "SELECT id FROM transactions WHERE type = 'transfer_out' AND transfer_group = ?" - " ORDER BY id LIMIT 1", + "SELECT id, leg_out_sats FROM transactions" + " WHERE type = 'transfer_out' AND transfer_group = ? ORDER BY id LIMIT 1", (group,), ).fetchone() if source is None: @@ -358,17 +348,18 @@ def _mirror_transfer(conn, tx): parts = [dict(row) for row in rows] if not parts: return [] - weights = [part["sats"] for part in parts] - sats_cuts = _split_capped(tx["fee_sats"] or 0, weights) - ore_cuts = _split_even(tx["fee_ore"] or 0, weights) + mirrored = _split_capped( + source["leg_out_sats"] or 0, [part["sats"] for part in parts] + ) created = [] for index, part in enumerate(parts): - sats = part["sats"] - sats_cuts[index] + sats = mirrored[index] if sats <= 0: continue created.append( _insert_lot(conn, tx["market_id"], part["acquired_date"], tx["id"], - part["source_lot_id"], index, sats, part["cost_ore"] + ore_cuts[index]) + part["source_lot_id"], index, sats, + _cost_for(part["cost_ore"], part["sats"], sats)) ) return created