Mirror exactly the sent sats, keeping the cost per sat

This commit is contained in:
ai-bot committed 2026-11-15 10:39:55 +00:00
1 parent 2840767c3a
commit 456a66151b
1 file changed
+12 -21
+12 -21
View File
@@ -321,30 +321,20 @@ def _split_capped(total, weights):
return cuts 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): def _mirror_transfer(conn, tx):
"""Create the destination lots of a generated transfer_in. """Create the destination lots of a generated transfer_in.
One lot per consumed part of the matching transfer_out, keeping the original The sent sats arrive in full, so the mirrored lots cover exactly the sent
acquisition date and cost. The sats fee lowers what arrives and the NOK fee amount: one lot per consumed part of the matching transfer_out, in order,
raises the cost basis. 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"] group = tx["transfer_group"]
if not group: if not group:
return [] return []
source = conn.execute( source = conn.execute(
"SELECT id FROM transactions WHERE type = 'transfer_out' AND transfer_group = ?" "SELECT id, leg_out_sats FROM transactions"
" ORDER BY id LIMIT 1", " WHERE type = 'transfer_out' AND transfer_group = ? ORDER BY id LIMIT 1",
(group,), (group,),
).fetchone() ).fetchone()
if source is None: if source is None:
@@ -358,17 +348,18 @@ def _mirror_transfer(conn, tx):
parts = [dict(row) for row in rows] parts = [dict(row) for row in rows]
if not parts: if not parts:
return [] return []
weights = [part["sats"] for part in parts] mirrored = _split_capped(
sats_cuts = _split_capped(tx["fee_sats"] or 0, weights) source["leg_out_sats"] or 0, [part["sats"] for part in parts]
ore_cuts = _split_even(tx["fee_ore"] or 0, weights) )
created = [] created = []
for index, part in enumerate(parts): for index, part in enumerate(parts):
sats = part["sats"] - sats_cuts[index] sats = mirrored[index]
if sats <= 0: if sats <= 0:
continue continue
created.append( created.append(
_insert_lot(conn, tx["market_id"], part["acquired_date"], tx["id"], _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 return created