aboutsummaryrefslogtreecommitdiff
path: root/internal/game/predictions_test.go
blob: f10f8498a7edbd045daed0764248ff6799158820 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
package game

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strings"
	"sync/atomic"
	"testing"
	"time"

	"thehouseoficarus/internal/combat"
	"thehouseoficarus/internal/net"
	"thehouseoficarus/internal/player"
	"thehouseoficarus/internal/prediction"
	"thehouseoficarus/internal/world"
)

func predictionFixture(t *testing.T) (*Game, *net.Session, *casinoTestConn, prediction.Market) {
	t.Helper()
	dir := t.TempDir()
	if err := os.MkdirAll(filepath.Join(dir, "rooms"), 0755); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(filepath.Join(dir, "rooms", "1.yaml"), []byte("name: Test Counter\nprediction_exchange: true\n"), 0644); err != nil {
		t.Fatal(err)
	}
	if err := os.MkdirAll(filepath.Join(dir, "players", "characters"), 0700); err != nil {
		t.Fatal(err)
	}
	g := &Game{Deps: Deps{World: world.New(dir), AccountStore: player.NewAccountStore(dir)}, Combat: combat.NewTracker()}
	p := player.New("alice")
	p.RoomID = 1
	p.Credits = 10000
	p.Options = map[string]any{"color": "none", "wrap_width": 0}
	conn := &casinoTestConn{}
	s := &net.Session{Player: p, Conn: conn}
	s.SetState(net.StateGame)
	m := prediction.Market{ID: "1", Question: "Will the sun rise?", Description: "Resolve Yes when the sun rises.", Outcomes: `["Yes","No"]`, Tokens: `["101","102"]`, Prices: `["0.421","0.579"]`, Active: true, Accepting: true, End: time.Now().Add(time.Hour).UTC().Format(time.RFC3339)}
	return g, s, conn, m
}
func TestPredictionBuySellDurable(t *testing.T) {
	g, s, conn, m := predictionFixture(t)
	buy := predictionRequest{action: "buy", id: "1", outcome: 1, quantity: 10}
	g.tradePrediction(s, buy, m)
	if s.Player.Credits != 9570 || len(s.Player.PredictionContracts) != 1 {
		t.Fatalf("buy failed: %s", conn.data)
	}
	loaded, err := g.AccountStore.LoadCharacter("alice")
	if err != nil {
		t.Fatal(err)
	}
	if loaded.Credits != 9570 || len(loaded.PredictionContracts) != 1 || loaded.PredictionContracts[0].Token != "101" {
		t.Fatal("ledger not persisted with debit")
	}
	s.Player = loaded
	m.Prices = `["0.60","0.40"]`
	g.predictionActive(s, map[string]prediction.Market{"1": m})
	if !strings.Contains(string(conn.data), "+170") || !strings.Contains(string(conn.data), "ACTIVE CONTRACTS") {
		t.Fatalf("missing portfolio P/L: %s", conn.data)
	}
	g.tradePrediction(s, predictionRequest{action: "sell", lot: 0}, m)
	if s.Player.Credits != 10170 || s.Player.PredictionContracts[0].Status != "sold" {
		t.Fatal("sale failed")
	}
	g.tradePrediction(s, predictionRequest{action: "sell", lot: 0}, m)
	if s.Player.Credits != 10170 {
		t.Fatal("duplicate sale paid twice")
	}
	loaded, err = g.AccountStore.LoadCharacter("alice")
	if err != nil || loaded.Credits != 10170 || loaded.PredictionContracts[0].Proceeds != 600 {
		t.Fatal("sale not durable")
	}
}
func TestPredictionResolutionCollectExactlyOnceAcrossReload(t *testing.T) {
	g, s, _, m := predictionFixture(t)
	g.tradePrediction(s, predictionRequest{action: "buy", outcome: 1, quantity: 10}, m)
	m.Accepting = false
	m.Prices = `["0.6","0.4"]`
	g.settlePredictions(s, map[string]prediction.Market{"1": m})
	if s.Player.Credits != 9570 || s.Player.PredictionContracts[0].Status != "open" {
		t.Fatal("non-terminal close resolved a contract")
	}
	m.Closed = true
	m.Prices = `["1","0"]`
	if !g.settlePredictions(s, map[string]prediction.Market{"1": m}) {
		t.Fatal("settlement failed")
	}
	// Resolution records the 100/share payout but moves no credits.
	if s.Player.Credits != 9570 || s.Player.PredictionContracts[0].Status != "resolved" || s.Player.PredictionContracts[0].Proceeds != 1000 {
		t.Fatalf("resolution wrong: credits=%d status=%s proceeds=%d", s.Player.Credits, s.Player.PredictionContracts[0].Status, s.Player.PredictionContracts[0].Proceeds)
	}
	loaded, err := g.AccountStore.LoadCharacter("alice")
	if err != nil {
		t.Fatal(err)
	}
	s.Player = loaded
	g.collectPredictions(s)
	if s.Player.Credits != 10570 || s.Player.PredictionContracts[0].Status != "collected" {
		t.Fatal("collect did not pay or mark the contract")
	}
	loaded, err = g.AccountStore.LoadCharacter("alice")
	if err != nil {
		t.Fatal(err)
	}
	s.Player = loaded
	g.collectPredictions(s)
	if s.Player.Credits != 10570 {
		t.Fatal("collect paid twice")
	}
}
func TestPredictionBuyByOutcomeName(t *testing.T) {
	g, s, _, m := predictionFixture(t)
	if !g.tradePrediction(s, predictionRequest{action: "buy", id: "1", quantity: 10, outcomeName: "yes"}, m) {
		t.Fatal("buy by outcome name failed")
	}
	if s.Player.PredictionContracts[0].Outcome != "Yes" {
		t.Fatalf("wrong outcome: %s", s.Player.PredictionContracts[0].Outcome)
	}
	if g.tradePrediction(s, predictionRequest{action: "buy", id: "1", quantity: 10, outcomeName: "maybe"}, m) {
		t.Fatal("unknown outcome name accepted")
	}
	if g.tradePrediction(s, predictionRequest{action: "buy", id: "1", quantity: 10, outcome: 9}, m) {
		t.Fatal("out-of-range outcome number accepted")
	}
}

func TestPredictionBuyByPartialOutcomeName(t *testing.T) {
	g, s, _, m := predictionFixture(t)
	m.Outcomes = `["Natus Vincere","9z"]`
	m.Tokens = `["a","b"]`
	m.Prices = `["0.70","0.30"]`
	for _, name := range []string{"natus", "natus vincere", "NATUS VINCERE"} {
		if !g.tradePrediction(s, predictionRequest{action: "buy", id: "1", quantity: 1, outcomeName: name}, m) {
			t.Fatalf("partial name %q failed", name)
		}
		if got := s.Player.PredictionContracts[len(s.Player.PredictionContracts)-1].Outcome; got != "Natus Vincere" {
			t.Fatalf("name %q matched %q", name, got)
		}
	}
}

func TestPredictionRejectsClosed(t *testing.T) {
	g, s, _, m := predictionFixture(t)
	r := predictionRequest{action: "buy", outcome: 1, quantity: 10}
	m.Closed = true
	g.tradePrediction(s, r, m)
	m.Closed = false
	m.End = time.Now().Add(-time.Minute).Format(time.RFC3339)
	g.tradePrediction(s, r, m)
	if s.Player.Credits != 10000 || len(s.Player.PredictionContracts) != 0 {
		t.Fatal("unsafe purchase accepted")
	}
}
func TestPredictionSaveRollback(t *testing.T) {
	g, s, _, m := predictionFixture(t)
	g.tradePrediction(s, predictionRequest{action: "buy", outcome: 1, quantity: 10}, m)
	bad := filepath.Join(t.TempDir(), "file")
	if err := os.WriteFile(bad, []byte("not a directory"), 0600); err != nil {
		t.Fatal(err)
	}
	g.AccountStore = player.NewAccountStore(bad)
	g.tradePrediction(s, predictionRequest{action: "buy", outcome: 1, quantity: 10}, m)
	if s.Player.Credits != 9570 || len(s.Player.PredictionContracts) != 1 {
		t.Fatal("failed debit not rolled back")
	}
	g.tradePrediction(s, predictionRequest{action: "sell", lot: 0}, m)
	if s.Player.Credits != 9570 || s.Player.PredictionContracts[0].Status != "open" {
		t.Fatal("failed sale not rolled back")
	}
	m.Closed = true
	m.Resolution = "resolved"
	m.Prices = `["1","0"]`
	if g.settlePredictions(s, map[string]prediction.Market{"1": m}) {
		t.Fatal("failed settlement reported success")
	}
	if s.Player.Credits != 9570 || s.Player.PredictionContracts[0].Status != "open" {
		t.Fatal("failed settlement not rolled back")
	}
}
func TestPredictionCounterInteractionAndOutage(t *testing.T) {
	g, s, conn, m := predictionFixture(t)
	var failed atomic.Bool
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if failed.Load() {
			w.WriteHeader(503)
			return
		}
		switch r.URL.Path {
		case "/markets":
			json.NewEncoder(w).Encode([]prediction.Market{m})
		case "/markets/1":
			json.NewEncoder(w).Encode(m)
		case "/prices-history":
			w.Write([]byte(`{"history":[{"t":100,"p":0.3},{"t":200,"p":0.4}]}`))
		default:
			w.WriteHeader(404)
		}
	}))
	defer server.Close()
	g.PredictionClient = prediction.NewClient()
	g.PredictionClient.Gamma = server.URL
	g.PredictionClient.CLOB = server.URL
	g.doUse(s, "predictions")
	if len(s.PredictionIDs) != 1 || !strings.Contains(string(conn.data), "Updating markets...") {
		t.Fatalf("no menu: %s", conn.data)
	}
	g.executePredictions(s, []string{"view", "1"}, "")
	if strings.Contains(string(conn.data), m.Description) || !strings.Contains(string(conn.data), "100%") {
		t.Fatalf("detail must show graph but not resolution text: %s", conn.data)
	}
	g.executePredictions(s, []string{"rules"}, "")
	if !strings.Contains(string(conn.data), m.Description) {
		t.Fatal("rules did not show resolution text")
	}
	failed.Store(true)
	conn.data = nil
	g.executePredictions(s, []string{"active"}, "") // Even an empty portfolio must check availability.
	if !strings.Contains(string(conn.data), "CLOSED") {
		t.Fatal("empty active list bypassed outage")
	}
	g.executePredictions(s, []string{"buy", "10", "1"}, "")
	if s.Player.Credits != 10000 || len(s.Player.PredictionContracts) != 0 {
		t.Fatal("traded stale cached price")
	}
	failed.Store(false)
	g.executePredictions(s, []string{"buy", "10", "1"}, "")
	if len(s.Player.PredictionContracts) != 1 {
		t.Fatal("counter did not recover")
	}
}
func TestPredictionFetchDoesNotBlockOwnerAndMovementCancels(t *testing.T) {
	g, s, _, m := predictionFixture(t)
	started, release := make(chan struct{}), make(chan struct{})
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { close(started); <-release; json.NewEncoder(w).Encode(m) }))
	defer server.Close()
	g.PredictionClient = prediction.NewClient()
	g.PredictionClient.Gamma = server.URL
	g.owner = newOwner()
	defer g.owner.stop()
	g.loggedInChars = map[string]*net.Session{"alice": s}
	s.PredictionIDs = []string{"1"}
	s.PredictionActive = true
	s.PredictionSelected = "1"
	s.PredictionScreen = "view"
	g.run(func() { g.executePredictions(s, []string{"buy", "10", "1"}, "") })
	select {
	case <-started:
	case <-time.After(time.Second):
		t.Fatal("fetch not started")
	}
	// This must run while the server is still stalled.
	moved := make(chan struct{})
	go func() { g.run(func() { s.Player.RoomID = 2 }); close(moved) }()
	select {
	case <-moved:
	case <-time.After(time.Second):
		close(release)
		t.Fatal("HTTP blocked the game owner")
	}
	close(release)
	deadline := time.Now().Add(2 * time.Second)
	for {
		busy := true
		g.run(func() { busy = s.PredictionBusy })
		if !busy {
			break
		}
		if time.Now().After(deadline) {
			t.Fatal("callback did not complete")
		}
		time.Sleep(time.Millisecond)
	}
	g.run(func() {
		if s.Player.Credits != 10000 || len(s.Player.PredictionContracts) != 0 {
			t.Error("trade completed after leaving counter")
		}
	})
}