Repository navigation
Expand file tree
/
Copy pathNeutralFlip.lua
More file actions
643 lines (596 loc) · 30.9 KB
/
Copy pathNeutralFlip.lua
File metadata and controls
643 lines (596 loc) · 30.9 KB
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
-- NeutralFlip: faction AH vs neutral AH price comparison for WoW: Forever. Written from scratch (MIT).
-- It never buys, posts, or clicks anything: it records prices you see at each auction house and tells
-- you which items are worth carrying from one house to the other after the auction house cut.
local ADDON, ns = ...
local C, Core = ns.Compat, ns.Core
local L = Core.L
local NF = {}
KennyNeutralFlip = NF
local SCHEMA = 2
local SCAN_COOLDOWN = 15 * 60
local SCAN_TIMEOUT = 120
local NEUTRAL = "Neutral"
local DEFAULTS = {
cutFaction = 0.05, -- faction AH cut (ahledger.com/wow-forever/auction-house); override with /nflip cut
cutNeutral = 0.15, -- neutral AH cut (same source)
maxAgeHours = 24, -- ignore prices older than this when comparing
minMargin = 0.20, -- profit must be at least 20% of the buy price...
minProfit = 50, -- ...and at least this many copper per unit
maxRatio = 20, -- sell/buy above this is flagged "thin market, check by hand"
keepDays = 14, -- prices older than this are pruned at login
tooltip = true,
listSize = 15,
}
-- English names of the three goblin towns and their zones. The zone list matters because those
-- zones have no faction auctioneer, so any AH opened there is the neutral one.
NF.NEUTRAL_NAMES = { ["Booty Bay"] = true, ["Gadgetzan"] = true, ["Everlook"] = true,
["Tanaris"] = true, ["Winterspring"] = true, ["Stranglethorn Vale"] = true, ["The Cape of Stranglethorn"] = true }
-- Classic-era uiMapIDs (Stranglethorn Vale 1434, Tanaris 1446, Winterspring 1452). UNCONFIRMED for
-- Forever; names and /nflip here are the fallbacks.
NF.NEUTRAL_MAPS = { [1434] = true, [1446] = true, [1452] = true }
local db, settings
local ahOpen, house, currentKind, location, classification = false, nil, nil, nil, "closed"
local session, scanToken, scanState = 0, 0, nil
local recordingReady = false
local lastScanStatus = "none"
local FACTION_NAMES = {
["Stormwind City"] = "Alliance", ["Stormwind"] = "Alliance", ["Ironforge"] = "Alliance",
["Darnassus"] = "Alliance", ["Exodar"] = "Alliance", ["The Exodar"] = "Alliance",
["Orgrimmar"] = "Horde", ["Thunder Bluff"] = "Horde", ["Undercity"] = "Horde",
["Silvermoon City"] = "Horde",
}
local migrations = {
[1] = function(old) return { houses = {}, overrides = {}, rates = {}, settings = old.settings or {} } end,
-- 0.3.3: deposit rates learned by 0.3.2 and earlier may be the 1s minimum deposit, not the house's rate.
-- Forget them; the next auction house visit learns them again.
[2] = function(old) old.rates = {}; return old end,
}
-- Location / house ------------------------------------------------------------------------
local function realmName()
return tostring(GetRealmName and C.Safe(GetRealmName()) or "realm")
end
local function playerFaction()
return tostring(UnitFactionGroup and C.Safe(UnitFactionGroup("player")) or "faction")
end
function NF.LocationKey()
local zone = GetRealZoneText and C.Safe(GetRealZoneText()) or ""
local sub = GetSubZoneText and C.Safe(GetSubZoneText()) or ""
return tostring(zone) .. "/" .. tostring(sub), tostring(zone), tostring(sub)
end
-- "Neutral" or the player's faction, plus how we decided.
function NF.DetectKind()
local key, zone, sub = NF.LocationKey()
local o = key ~= "/" and db.overrides[key] or nil
if o == "neutral" then return NEUTRAL, "your /nflip here setting" end
if o == "faction" then
local faction = playerFaction()
if faction == "Alliance" or faction == "Horde" then return faction, "your /nflip here setting" end
return nil, "player faction unavailable"
end
local mapID = C_Map and C_Map.GetBestMapForUnit and C.SafeNumber(C_Map.GetBestMapForUnit("player"))
local namedNeutral = NF.NEUTRAL_NAMES[sub] or NF.NEUTRAL_NAMES[zone]
local namedFaction = FACTION_NAMES[sub] or FACTION_NAMES[zone]
local mappedNeutral = mapID and NF.NEUTRAL_MAPS[mapID]
if namedFaction and (namedNeutral or mappedNeutral or namedFaction ~= playerFaction()) then
return nil, "conflicting location or player faction " .. key
end
if namedNeutral then return NEUTRAL, "zone " .. key end
if namedFaction then return namedFaction, "zone " .. key end
if mappedNeutral then return NEUTRAL, "map " .. mapID end
return nil, "unrecognized location " .. key
end
local function houseData(kind)
local key = realmName() .. "-" .. kind
local h = db.houses[key]
if not h then h = { items = {}, lastScan = 0 }; db.houses[key] = h end
return h, key
end
NF.HouseData = function(kind) return houseData(kind) end
-- Price records: items[id] = { p = lowest unit price, q = units at that price (nil = unknown),
-- n = units listed in total, t = time seen }.
function NF.Record(h, itemID, p, q, n, t)
if not (itemID and p and p > 0) then return end
h.items[itemID] = { p = math.floor(p), q = q, n = n, t = t or C.Now() }
end
-- Deposit rate check ----------------------------------------------------------------------
-- Forever has no API that says "this is the neutral AH". The deposit is a multiple of vendor price
-- and differs between houses, so we learn deposit/vendor here and use it to double-check the zone.
-- Returns deposit/vendor for the shortest (2 hour) listing, measured on an item in your bags (stored by the caller).
-- WoW: Forever's minimum deposit per auction was 1 silver at launch; the November 10 hotfix notes set it to
-- 1 copper, and it went live with the November 17 maintenance. Deposits are whole copper. So a cheap item's
-- deposit is the floor or mostly rounding, not the house's rate. The probe tries the items with the highest
-- vendor price first and keeps a reading only when:
-- * the 20-unit deposit is above PROBE_MIN_DEPOSIT (20c: past a 1c-per-auction and a 1c-per-unit floor), and
-- * the 40-unit deposit is twice the 20-unit one, give or take 1c of rounding. A per-auction minimum of any
-- size (1c, 1s, or a future change) does not double, so a clamped deposit is never taken as the rate.
-- The rate is read from the 40-unit deposit (above 40c, so rounding is under 2.5%).
-- No such item = no reading (nil), never a skewed one.
NF.PROBE_QTY = 20
NF.PROBE_MIN_DEPOSIT = 20
NF.PROBE_MAX_TRIES = 20
local function deposit(itemID, qty)
local ok, dep = pcall(C_AuctionHouse.CalculateCommodityDeposit, itemID, 1, qty)
return ok and C.SafeNumber(dep) or nil
end
function NF.ProbeDepositRate()
if not (C_AuctionHouse and C_AuctionHouse.CalculateCommodityDeposit) then return nil end
local items = {}
for itemID in pairs(C.GetBagCounts()) do
local info = C.GetItemInfo(itemID)
if info and info.sellPrice and info.sellPrice > 0 then items[#items + 1] = { id = itemID, sell = info.sellPrice } end
end
table.sort(items, function(a, b) if a.sell ~= b.sell then return a.sell > b.sell end return a.id < b.id end)
local q = NF.PROBE_QTY
for i = 1, math.min(#items, NF.PROBE_MAX_TRIES) do
local it = items[i]
local dep = deposit(it.id, q)
if dep and dep > NF.PROBE_MIN_DEPOSIT then
local dep2 = deposit(it.id, 2 * q)
if dep2 and math.abs(dep2 - 2 * dep) <= 1 then
return dep2 / (it.sell * 2 * q)
end
end
end
return nil
end
-- Returns a warning string when the learned deposit rates say this house is the other kind.
function NF.CrossCheck(kind, rate)
local f, n = db.rates.faction, db.rates.neutral
if not (rate and f and n) or math.abs(n - f) < 0.5 * math.min(n, f) then return nil end
local looksNeutral = math.abs(rate - n) < math.abs(rate - f)
if looksNeutral and kind ~= NEUTRAL then
return "deposits here look like the NEUTRAL house. If so, type /nflip here neutral"
elseif not looksNeutral and kind == NEUTRAL then
return "deposits here look like a FACTION house. If so, type /nflip here faction"
end
end
-- Capturing prices (only what the AH already shows you) -------------------------------------
-- A session owns its market and each scan owns its callbacks. Never commit a partial snapshot.
local function sameHouse()
return ahOpen and house and NF.LocationKey() == location
end
local function activeHouse()
return recordingReady and sameHouse()
end
local function cancelScan(reason, notify)
if scanState and reason then
lastScanStatus = reason
if notify then Core.Print("full scan " .. reason .. "; no full scan recorded.") end
end
scanToken = scanToken + 1
scanState = nil
end
local function beginScan(phase)
cancelScan()
local state = { token = scanToken, session = session, house = house, kind = currentKind,
phase = phase, deadline = C.Clock() + SCAN_TIMEOUT }
scanState = state
C_Timer.After(SCAN_TIMEOUT, function()
if scanState == state and C.Clock() >= state.deadline then cancelScan("timed out (" .. state.phase .. ")", true) end
end)
return state
end
local function validScan(state)
return scanState == state and state.token == scanToken and state.session == session
and activeHouse() and state.house == house and state.kind == currentKind
end
local function positiveInteger(v)
return v and v > 0 and v < math.huge and v == math.floor(v)
end
-- The shared helper conflates incomplete rows and valid bid-only auctions. Inspect
-- the documented fields here so a bid-only auction can be skipped safely.
local function scanRow(i)
local _, _, count, _, _, _, _, _, _, buyout, _, _, _, _, _, _, itemID, hasAll =
(ns.LegacyRawRow or C_AuctionHouse.GetReplicateItemInfo)(i)
if C.Safe(hasAll) ~= true then return nil, "incomplete row" end
itemID, count, buyout = C.SafeNumber(itemID), C.SafeNumber(count), C.SafeNumber(buyout)
if not (positiveInteger(itemID) and positiveInteger(count) and buyout and buyout >= 0
and buyout < math.huge and buyout == math.floor(buyout)) then return nil, "invalid row" end
if buyout == 0 then return nil end -- complete bid-only auction, not a price observation
if buyout < count then return nil, "invalid unit price" end
return itemID, nil, count, math.floor(buyout / count)
end
function NF.ProcessReplicate(state)
state = state or scanState
if not state or not validScan(state) or state.phase == "processing" then return end
local n = C.AHNumReplicate()
if not positiveInteger(n) then cancelScan("returned no usable rows", true); return end
state.phase = "processing"
local acc, i, accepted, now = {}, 0, 0, C.Now()
local function finish()
if not validScan(state) then return end
if accepted == 0 then cancelScan("contained no usable buyouts", true); return end
local k = 0
for id, a in pairs(acc) do
local previous = state.house.items[id]
if not previous or not C.SafeNumber(previous.t) or previous.t <= now then
NF.Record(state.house, id, a.min, a.qmin, a.qty, now)
end
k = k + 1
end
state.house.lastScan = now
lastScanStatus = ("complete: %d rows, %d buyouts, %d items (%s)"):format(n, accepted, k, NF.KindLabel(state.kind))
cancelScan()
Core.Print(("saved %d prices for the %s auction house."):format(k, NF.KindLabel(state.kind)))
end
local step, run
step = function()
if not validScan(state) then return end
if C.Clock() >= state.deadline then cancelScan("timed out (processing)", true); return end
if C.InCombat() then C_Timer.After(1, run); return end
if C.AHNumReplicate() ~= n then cancelScan("row count changed during processing", true); return end
local stop = math.min(i + 500, n)
while i < stop do
local itemID, err, count, unit = scanRow(i)
if err then cancelScan(err .. " at " .. (i + 1), true); return end
if itemID then
local a = acc[itemID]
if not a then a = { min = unit, qmin = 0, qty = 0 }; acc[itemID] = a end
if unit < a.min then a.min, a.qmin = unit, 0 end
if unit == a.min then a.qmin = a.qmin + count end
a.qty = a.qty + count
accepted = accepted + 1
end
i = i + 1
end
if i < n then C_Timer.After(0, run) else finish() end
end
run = function()
if not validScan(state) then return end
if not Core.SafeCall("scan", step) and scanState == state then cancelScan("failed", true) end
end
run()
end
local function OnBrowse()
if not activeHouse() then return end
for _, r in ipairs(C.AHBrowse()) do NF.Record(house, r.itemID, r.price, nil, r.quantity) end
end
local function OnCommodity(itemID)
itemID = C.SafeNumber(itemID)
if not (activeHouse() and itemID) then return end
local minP, qmin, total = nil, 0, 0
for _, r in ipairs(C.AHCommodity(itemID)) do
if not minP or r.price < minP then minP, qmin = r.price, 0 end
if r.price == minP then qmin = qmin + r.quantity end
total = total + r.quantity
end
if minP then NF.Record(house, itemID, minP, qmin, total) end
end
-- The verdict -------------------------------------------------------------------------------
function NF.CurrentKind() return currentKind end
function NF.KindLabel(kind) return kind == NEUTRAL and "neutral" or (kind or "?") end
local function fresh(rec, now)
if type(rec) ~= "table" then return false end
local p, t = C.SafeNumber(rec.p), C.SafeNumber(rec.t)
if not (p and p > 0 and p < math.huge and t and t > 0 and t <= now
and now - t <= settings.maxAgeHours * 3600) then return false end
-- Missing listing quantities are permitted; malformed or secret quantities are not.
for _, key in ipairs({ "q", "n" }) do
if rec[key] ~= nil then
local n = C.SafeNumber(rec[key])
if not n or n < 0 or n >= math.huge or n ~= math.floor(n) then return false end
end
end
return true
end
-- One route: buy at `from` for buy.p, list at `to` 1c under its lowest listing.
local function route(itemID, buy, sell, cut, from, to, now, bags)
if not (buy and sell) then return nil end
local listAt = sell.p - 1
local net = math.floor(listAt * (1 - cut))
local profit = net - buy.p
if profit < settings.minProfit or profit < buy.p * settings.minMargin then return nil end
local qty = buy.q and buy.q > 0 and buy.q or 1
if sell.n and sell.n > 0 then qty = math.min(qty, sell.n) end -- don't carry more than the other side lists
local info = C.GetItemInfo(itemID)
local rate = db.rates[to == NEUTRAL and "neutral" or "faction"]
return {
itemID = itemID, name = (info and info.name) or C.GetItemName(itemID) or ("item " .. itemID),
from = from, to = to, buy = buy.p, listAt = listAt, net = net, profit = profit, qty = qty,
qtyKnown = buy.q ~= nil, total = profit * qty, carried = bags[itemID] or 0,
thin = sell.p > buy.p * settings.maxRatio,
deposit = (rate and info and info.sellPrice) and math.floor(rate * info.sellPrice * qty) or nil,
age = math.max(now - buy.t, now - sell.t), buyAge = now - buy.t, sellAge = now - sell.t,
}
end
-- Cash recovery scenario: unsold stock is assigned zero cash proceeds, not zero asset value.
-- Deposit is refundable on units sold; one failed posting per unsold unit.
function NF.CashScenario(o, sold)
if not o or not o.deposit or not o.qty or o.qty <= 0 or type(sold) ~= "number" or sold < 0 or sold > o.qty or sold ~= math.floor(sold) then return nil end
local capital = o.buy * o.qty
local lost = math.ceil(o.deposit * (o.qty - sold) / o.qty)
return sold * o.net - capital - lost
end
function NF.RecoveryUnits(o)
if not o or not o.qty or o.qty <= 0 or not o.deposit then return nil end
local lo, hi = 0, o.qty
while lo < hi do
local mid = math.floor((lo + hi) / 2)
if NF.CashScenario(o, mid) >= 0 then hi = mid else lo = mid + 1 end
end
if NF.CashScenario(o, lo) >= 0 then return lo end
end
-- Both routes for one item (0, 1 or 2 entries).
function NF.ItemRoutes(itemID, now, bags)
local fac = playerFaction()
local a, b = houseData(fac).items[itemID], houseData(NEUTRAL).items[itemID]
local out = {}
if fresh(a, now) and fresh(b, now) then
out[#out + 1] = route(itemID, a, b, settings.cutNeutral, fac, NEUTRAL, now, bags)
out[#out + 1] = route(itemID, b, a, settings.cutFaction, NEUTRAL, fac, now, bags)
end
return out
end
function NF.Opportunities(now)
now = now or C.Now()
local home, neu = houseData(playerFaction()), houseData(NEUTRAL)
local bags, out = C.GetBagCounts(), {}
for id in pairs(home.items) do
if neu.items[id] then
for _, o in ipairs(NF.ItemRoutes(id, now, bags)) do out[#out + 1] = o end
end
end
table.sort(out, function(x, y)
if x.thin ~= y.thin then return y.thin end
if x.total ~= y.total then return x.total > y.total end
return x.itemID < y.itemID
end)
return out
end
local function ago(sec)
if sec < 3600 then return math.max(1, math.floor(sec / 60)) .. "m" end
return math.floor(sec / 3600) .. "h"
end
function NF.FormatLine(i, o)
local s = ("%d. %s: BUY at %s AH at %s or less (%s%d) -> LIST at %s AH at %s -> +%s each, about %s if all sell"):format(
i, o.name, NF.KindLabel(o.from), C.Money(o.buy), o.qtyKnown and "x" or "x?", o.qty,
NF.KindLabel(o.to), C.Money(o.listAt), C.Money(o.profit), C.Money(o.total))
local notes = { ("%s %s %s, %s %s %s"):format(NF.KindLabel(o.from), L["price"], ago(o.buyAge), NF.KindLabel(o.to), L["price"], ago(o.sellAge)) .. " " .. L["old"] }
if not o.qtyKnown then notes[#notes + 1] = "quantity at lowest buy price unknown" end
if o.deposit then notes[#notes + 1] = "deposit at risk " .. C.Money(o.deposit) else notes[#notes + 1] = "deposit unknown" end
local recovery = NF.RecoveryUnits(o)
if recovery then notes[#notes + 1] = ("cash recovery: sell %d/%d (one posting)"):format(recovery, o.qty) end
if o.carried > 0 then notes[#notes + 1] = "you carry " .. o.carried end
if o.thin then notes[#notes + 1] = "THIN MARKET: check by hand" end
return s .. " [" .. table.concat(notes, ", ") .. "]"
end
function NF.ListText(now)
local list = NF.Opportunities(now)
local lines = {}
local fac = playerFaction()
lines[1] = ("%s: %s AH vs neutral AH. Cuts %g%% / %g%%. Prices older than %gh ignored.")
:format(realmName(), fac, settings.cutFaction * 100, settings.cutNeutral * 100, settings.maxAgeHours)
if #list == 0 then
lines[2] = L["Nothing worth carrying yet. Search or /nflip scan at BOTH your faction AH and a neutral AH (Booty Bay, Gadgetzan, Everlook), then check again."]
local fresh1, fresh2 = houseData(fac).lastScan, houseData(NEUTRAL).lastScan
lines[3] = ("%s: %s %s, %s %s"):format(L["Last full scan"], fac, fresh1 > 0 and date("%d %b %H:%M", fresh1) or L["never"],
L["neutral"], fresh2 > 0 and date("%d %b %H:%M", fresh2) or L["never"])
end
for i = 1, math.min(#list, settings.listSize) do lines[#lines + 1] = NF.FormatLine(i, list[i]) end
lines[#lines + 1] = ""
lines[#lines + 1] = "You press every buy and post. Observed listings are not completed sales or proof of demand. Prices may have moved; unsold auctions can lose the deposit."
return table.concat(lines, "\n"), #list
end
-- Tooltip: at most two lines, only added, never replacing anything another addon shows.
local function OnItemTooltip(tooltip, data)
if not (settings and settings.tooltip) then return end
local itemID = data and C.SafeNumber(data.id)
if not itemID then return end
local now, fac = C.Now(), playerFaction()
local a, b = houseData(fac).items[itemID], houseData(NEUTRAL).items[itemID]
if not (fresh(a, now) or fresh(b, now)) then return end
local function part(label, r) return label .. " " .. (fresh(r, now) and C.Money(r.p) or "-") end
if tooltip.Claim then tooltip.Claim("price.auction") end -- MatTooltip then skips its own AH price line
tooltip:AddLine("|cff33ff99NeutralFlip|r " .. part(fac, a) .. " | " .. part("Neutral", b))
for _, o in ipairs(NF.ItemRoutes(itemID, now, {})) do
if not o.thin then
tooltip:AddLine(("|cff33ff99 buy at %s, list at %s: +%s each|r"):format(NF.KindLabel(o.from), NF.KindLabel(o.to), C.Money(o.profit)))
break
end
end
end
-- Events ----------------------------------------------------------------------------------
local f = CreateFrame("Frame")
f:RegisterEvent("ADDON_LOADED")
f:RegisterEvent("PLAYER_LOGIN")
f:RegisterEvent("AUCTION_HOUSE_SHOW")
f:RegisterEvent("AUCTION_HOUSE_CLOSED")
-- Each client knows only its own AH events (registering an unknown one is an error), so try them all.
for _, ev in ipairs({ "REPLICATE_ITEM_LIST_UPDATE", "AUCTION_HOUSE_BROWSE_RESULTS_UPDATED",
"COMMODITY_SEARCH_RESULTS_UPDATED", "AUCTION_ITEM_LIST_UPDATE" }) do pcall(f.RegisterEvent, f, ev) end
local function OnReplicateUpdate()
if not sameHouse() then return end
local state = beginScan("waiting for rows")
C_Timer.After(2, function()
if validScan(state) and not Core.SafeCall("scan start", NF.ProcessReplicate, state) and scanState == state then
cancelScan("failed to start", true)
end
end)
end
local announced = {}
function NF.OnAHShow()
cancelScan("cancelled: market changed", true)
session = session + 1
local generation = session
ahOpen, recordingReady = true, false
local kind, why = NF.DetectKind()
location, classification = NF.LocationKey(), why
currentKind = kind
house = kind and houseData(kind) or nil
if not kind then
Core.Print("auction house market unknown (" .. why .. "); recording paused. Use /nflip here neutral|faction.")
return
end
-- One line per auction house per session (not on every visit), unless there are flips to report.
local _, n = NF.ListText()
local key = NF.LocationKey()
if n > 0 or not announced[key] then
announced[key] = true
Core.Print(("this is the %s auction house (%s). %s"):format(NF.KindLabel(kind), why,
n > 0 and (n .. " flips found: /nflip") or "Search or /nflip scan to record prices."))
end
C_Timer.After(1, function()
if not sameHouse() or session ~= generation or currentKind ~= kind then return end
local ok = Core.SafeCall("deposit", function()
local rate = not C.InCombat() and NF.ProbeDepositRate() or nil
local warn = NF.CrossCheck(kind, rate)
if warn then
Core.Print(warn)
if not db.overrides[location] then
classification = "deposit mismatch; recording paused pending /nflip here override"
cancelScan("cancelled: deposit mismatch", true)
house = nil
return
end
elseif rate then db.rates[kind == NEUTRAL and "neutral" or "faction"] = rate end
recordingReady = true
end)
if not ok then
classification = "deposit check failed; recording paused"
cancelScan("cancelled: deposit check failed", true)
end
end)
end
f:SetScript("OnEvent", function(_, event, arg1)
if event == "ADDON_LOADED" then
if arg1 ~= ADDON then return end
db = Core.Migrate(KennyNeutralFlipDB, migrations, SCHEMA)
db.houses, db.overrides, db.rates = db.houses or {}, db.overrides or {}, db.rates or {}
KennyNeutralFlipDB = db
settings = Core.Settings(db.settings, DEFAULTS)
-- Shared tooltip block with our other addons (prices first, then verdicts); works the same alone.
ns.Hub.AddTooltip(ADDON, 20, function(tt, _, data) Core.SafeCall("tooltip", OnItemTooltip, tt, data) end)
return
end
if not db then return end
if event == "PLAYER_LOGIN" then
local cutoff = C.Now() - settings.keepDays * 86400
for key, h in pairs(db.houses) do
for id, r in pairs(h.items) do if r.t < cutoff then h.items[id] = nil end end
if next(h.items) == nil then db.houses[key] = nil end
end
elseif event == "AUCTION_HOUSE_SHOW" then Core.SafeCall("show", NF.OnAHShow)
elseif event == "AUCTION_HOUSE_CLOSED" then
cancelScan("cancelled: auction house closed", true)
session = session + 1
ahOpen, house, currentKind, location, classification = false, nil, nil, nil, "closed"
recordingReady = false
elseif event == "REPLICATE_ITEM_LIST_UPDATE" then OnReplicateUpdate() -- also catches a scan started by PriceLog or MatTooltip
elseif event == "AUCTION_ITEM_LIST_UPDATE" then -- Classic Era only: answers both searches and full scans
if C.AHListKind and C.AHListKind() == "replicate" then OnReplicateUpdate()
elseif not C.InCombat() then Core.SafeCall("browse", OnBrowse) end
elseif C.InCombat() then return
elseif event == "AUCTION_HOUSE_BROWSE_RESULTS_UPDATED" then Core.SafeCall("browse", OnBrowse)
elseif event == "COMMODITY_SEARCH_RESULTS_UPDATED" then Core.SafeCall("commodity", OnCommodity, arg1)
end
end)
-- Slash commands --------------------------------------------------------------------------
local function setNumber(key, v, lo, hi, label)
v = tonumber(v)
if not v or v < lo or v > hi then Core.Print(("%s must be a number from %s to %s."):format(label, lo, hi)) return end
settings[key] = v
Core.Print(label .. " set to " .. v .. ".")
end
local HELP = "/nflip (list flips) | scan | here neutral|faction|auto | status | cut faction|neutral 0.05"
.. " | age <hours> | margin 0.2 | tooltip | way [bootybay|gadgetzan|everlook] | debug | report | wipe"
-- Startup self-check: one loud warning if Forever lacks an API we need; first-run guide; /nflip debug.
NF.REQUIRED_APIS = C.LEGACY_AH and { "QueryAuctionItems", "CanSendAuctionQuery", "GetNumAuctionItems", "GetAuctionItemInfo",
"C_Container.GetContainerItemInfo", "TooltipDataProcessor.AddTooltipPostCall" } or { "C_AuctionHouse.ReplicateItems", "C_AuctionHouse.GetNumReplicateItems", "C_AuctionHouse.GetReplicateItemInfo",
"C_AuctionHouse.GetBrowseResults", "C_AuctionHouse.GetNumCommoditySearchResults", "C_AuctionHouse.GetCommoditySearchResultInfo",
"C_AuctionHouse.IsThrottledMessageSystemReady", "C_Container.GetContainerItemInfo", "TooltipDataProcessor.AddTooltipPostCall" }
Core.Setup({ cmd = "/nflip", required = NF.REQUIRED_APIS, optional = { "C_Map.GetBestMapForUnit", "TomTom", "LibStub", "KennyPriceLog" },
db = function() return db end,
firstRun = { L["Welcome! Search or /nflip scan at your faction AH and at a neutral AH, then /nflip lists what to carry where."] }, -- one line on first install only
debugLines = function()
local out = { L["location"] .. ": " .. NF.LocationKey() .. " -> " .. NF.KindLabel((NF.DetectKind())) }
for key, h in pairs(db.houses) do
local n = 0
for _ in pairs(h.items) do n = n + 1 end
out[#out + 1] = ("%s: %d %s, %s %s"):format(key, n, L["prices"], L["last full scan"], h.lastScan > 0 and date("%d %b %H:%M", h.lastScan) or L["never"])
end
return out
end })
-- Enrichment for our other addons (e.g. GoldPerSpot's per-item list): the best fresh flip for an item, or nil.
ns.Hub.Provide("flip", ADDON, function(itemID)
if not db then return nil end
for _, o in ipairs(NF.ItemRoutes(itemID, C.Now(), {})) do
if not o.thin then return { profit = o.profit, from = NF.KindLabel(o.from), to = NF.KindLabel(o.to), buy = o.buy, listAt = o.listAt } end
end
end)
Core.RegisterTextPanel("Flips", function() return (NF.ListText()) end) -- a tab in DEB's window when DEB hosts panels
SLASH_KENNYNEUTRALFLIP1 = "/nflip"
SLASH_KENNYNEUTRALFLIP2 = "/neutralflip"
SlashCmdList.KENNYNEUTRALFLIP = function(msg)
if not db then return end
local cmd, rest = (msg or ""):match("^(%S*)%s*(.-)$")
cmd = cmd:lower()
if cmd == "" or cmd == "list" then
Core.OpenView(function() Core.ShowText("List", "NeutralFlip: what to carry where (Ctrl+C copies)", (NF.ListText())) end)
elseif cmd == "scan" then
if not ahOpen then Core.Print("open an auction house first.") return end
if not activeHouse() then Core.Print("market not ready; wait for the deposit check or use /nflip here neutral|faction if unknown.") return end
if scanState then Core.Print("a full scan is already " .. scanState.phase .. ".") return end
if C.InCombat() then Core.Print("not in combat.") return end
local wait = SCAN_COOLDOWN - (C.Now() - (house.lastScan or 0))
if wait > 0 then Core.Print(("full scan available in %d min. Your searches are still recorded."):format(math.ceil(wait / 60))) return end
if not C.AHReady() then Core.Print("AH busy, try again shortly.") return end
local mine, by, left = ns.Hub.ClaimScan(ADDON)
if not mine then Core.Print(("%s %s; %s %d min. %s"):format(L["a full scan was already started by"], by or "?", L["next one in"], math.ceil(left / 60), L["Its results are recorded here too."])) return end
beginScan("waiting for results")
local ok, requested = Core.SafeCall("replicate", C.AHReplicate)
if not ok or not requested then cancelScan("request failed", true); return end
Core.Print("full scan requested. Stay at the AH until it reports.")
elseif cmd == "here" then
local key = NF.LocationKey()
local v = rest:lower()
if key == "/" then Core.Print("location unavailable; cannot set a location override.") return end
if v == "neutral" or v == "faction" then db.overrides[key] = v
elseif v == "auto" then db.overrides[key] = nil
else Core.Print("usage: /nflip here neutral|faction|auto") return end
Core.Print(("auction houses at %s are now treated as: %s."):format(key, v))
if ahOpen then NF.OnAHShow() end
elseif cmd == "cut" then
local which, v = rest:match("^(%a+)%s+(%S+)$")
if which == "faction" then setNumber("cutFaction", v, 0, 0.5, "faction cut")
elseif which == "neutral" then setNumber("cutNeutral", v, 0, 0.5, "neutral cut")
else Core.Print("usage: /nflip cut faction 0.05 | /nflip cut neutral 0.15") end
elseif cmd == "age" then setNumber("maxAgeHours", rest, 1, 336, "max price age (hours)")
elseif cmd == "margin" then setNumber("minMargin", rest, 0, 10, "minimum margin")
elseif cmd == "tooltip" then
settings.tooltip = not settings.tooltip
Core.Print("tooltip lines " .. (settings.tooltip and "on." or "off."))
elseif cmd == "status" then
Core.Print("market: " .. (ahOpen and NF.KindLabel(currentKind) or "closed") .. " (" .. classification .. "); recording " .. (activeHouse() and "enabled" or "paused") .. ".")
Core.Print("scan: " .. (scanState and scanState.phase or "idle") .. "; last result: " .. lastScanStatus .. ".")
if next(db.houses) == nil then Core.Print("no prices recorded yet. Search or /nflip scan at an auction house.") end
for key, h in pairs(db.houses) do
local n = 0
for _ in pairs(h.items) do n = n + 1 end
Core.Print(("%s: %d prices, last full scan %s."):format(key, n, h.lastScan > 0 and date("%d %b %H:%M", h.lastScan) or "never"))
end
Core.Print(("deposit/vendor rate learned: faction %s, neutral %s."):format(
db.rates.faction and ("%.2f"):format(db.rates.faction) or "?", db.rates.neutral and ("%.2f"):format(db.rates.neutral) or "?"))
elseif cmd == "report" then
local lines = { "schema " .. tostring(db.schema), "kind " .. tostring(currentKind), "location " .. NF.LocationKey(),
"classification " .. classification, "AH open " .. tostring(ahOpen),
"recording " .. (activeHouse() and "enabled" or "paused"),
"scan " .. (scanState and scanState.phase or "idle"), "last scan result " .. lastScanStatus,
"deposit rates: faction " .. tostring(db.rates.faction) .. ", neutral " .. tostring(db.rates.neutral) }
for key, h in pairs(db.houses) do
local n = 0
for _ in pairs(h.items) do n = n + 1 end
lines[#lines + 1] = key .. " items " .. n .. ", last full scan " .. tostring(h.lastScan or 0)
end
Core.ShowReport(lines)
elseif cmd == "debug" then Core.PrintDebug()
elseif cmd == "way" then
NF.Waypoint(rest)
elseif cmd == "wipe" then
cancelScan("cancelled: prices wiped", true)
db.houses = {}
if sameHouse() and currentKind then house = houseData(currentKind) end -- keep recording at the open AH
Core.Print("all recorded prices wiped.")
else
Core.Print(HELP)
end
end