cost.gno
1.63 Kb · 48 lines
1package lastcall
2
3// Spot cost basis. The desk records what each holder has paid for their current
4// sStock position so the UI can show an average entry price and unrealized P&L on
5// spot — the desk itself only needs balances, this is bookkeeping for the trader.
6//
7// spotCost[{owner,ticker}] is the total micro-USD paid (sum of price*units/1e6 at each
8// buy, fee excluded), reduced pro-rata on every sell so the average per share is
9// preserved. Plain stock transfers are not tracked (received shares carry no recorded
10// cost); for a testnet desk that is acceptable.
11
12type costKey struct {
13 owner address
14 ticker string
15}
16
17var spotCost = map[costKey]int64{}
18
19// addCost records the tUSD notional (micro) a buyer paid toward their cost basis.
20func addCost(owner address, ticker string, paid int64) {
21 spotCost[costKey{owner, ticker}] += paid
22}
23
24func costOf(owner address, ticker string) int64 { return spotCost[costKey{owner, ticker}] }
25
26// reduceCost removes the cost of `sold` units from a holder whose balance BEFORE the
27// sale was `heldBefore`, keeping the average per-share cost unchanged.
28func reduceCost(owner address, ticker string, sold, heldBefore int64) {
29 if heldBefore <= 0 {
30 return
31 }
32 k := costKey{owner, ticker}
33 spotCost[k] -= mulDiv(spotCost[k], sold, heldBefore)
34 if spotCost[k] < 0 {
35 spotCost[k] = 0
36 }
37}
38
39// AvgEntry returns the owner's average entry price for ticker in micro-USD per share,
40// or 0 if they hold none.
41func AvgEntry(ticker string, owner address) int64 {
42 held := mustStock(ticker).token.BalanceOf(owner)
43 if held <= 0 {
44 return 0
45 }
46 cost := spotCost[costKey{owner, ticker}]
47 return mulDiv(cost, microUSD, held)
48}