Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

cost.gno

1.54 Kb · 46 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
24// reduceCost removes the cost of `sold` units from a holder whose balance BEFORE the
25// sale was `heldBefore`, keeping the average per-share cost unchanged.
26func reduceCost(owner address, ticker string, sold, heldBefore int64) {
27	if heldBefore <= 0 {
28		return
29	}
30	k := costKey{owner, ticker}
31	spotCost[k] -= mulDiv(spotCost[k], sold, heldBefore)
32	if spotCost[k] < 0 {
33		spotCost[k] = 0
34	}
35}
36
37// AvgEntry returns the owner's average entry price for ticker in micro-USD per share,
38// or 0 if they hold none.
39func AvgEntry(ticker string, owner address) int64 {
40	held := mustStock(ticker).token.BalanceOf(owner)
41	if held <= 0 {
42		return 0
43	}
44	cost := spotCost[costKey{owner, ticker}]
45	return mulDiv(cost, microUSD, held)
46}