Files
probably-decentralized/src/Decentralized.Domain/BmOrders.cs
T

288 lines
17 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
namespace Decentralized.Domain
{
public enum PayMode { Escrow, Advance }
/// <summary>商家类型:矿卡(全新 / 二手)、矿架能源、模组、军火、枪匠配件、证件芯片、药物、化学、酿酒、水培、养殖、矿工、水务、仓储、工具、奢侈品;大宗商家随机出现。</summary>
public enum MerchantType { GpuNew, GpuUsed, Rigs, Modules, Arms, GunMods, Docs, Pharma, Chem, Brewer, Farm, Husbandry, Miner, Water, Storage, Tools, Luxury, Bulk }
public enum OrderState { Pending, Ready, Done, Refunded, Lost }
/// <summary>黑市上的卖家:成交数与好评率公开;是不是骗子是隐藏的。</summary>
public sealed class BmSeller
{
public string Name;
public int Trades;
public int Rating; // 好评率 %
public bool Scam;
public MerchantType Type;
/// <summary>商家的价格系数(订单价 = 基础价 × 系数,各家不同)。</summary>
public double Factor;
public int Days => Type == MerchantType.Bulk ? Tuning.BmBulkDays : Tuning.BmDoorDays;
/// <summary>只有成交数够多的卖家才接受提前放款。</summary>
public bool Advance => Trades >= Tuning.BmAdvanceMinTrades;
}
/// <summary>商家货架上的一种货:卖家、货、单价(订单价)、库存。</summary>
public sealed class BmListing : BmGood
{
public int Seller;
public int Qty;
}
public sealed class BmOrder
{
public string Item;
public string Seller;
public bool SellerScam;
public PayMode Mode;
public int Count = 1;
public string Model, FakeOf;
public double Health;
public int Price;
public string Asset;
public double Qty;
/// <summary>付款时留在卖家那边的污点与成本:退款时一并还回,免得"付脏币再退款"洗钱。</summary>
public double Taint, Basis;
public int PlacedDay, DueDay;
/// <summary>被截获后执法选择了上门:到货时快递员是执法人员,签收即记罪证。</summary>
public bool Controlled;
public OrderState State = OrderState.Pending;
/// <summary>终态的原因:done / scam / rug / intercept / theft / refund。</summary>
public string Why;
}
/// <summary>一笔会被追查的交易:到期日、金额(信用点)、来源(honeypot / seller / controlled)。</summary>
public sealed class BmTrap
{
public int Day;
public double Amount;
public string Why;
public string Item;
}
/// <summary>夜间发生的订单事件,供日志与新闻使用。</summary>
public sealed class BmEvent
{
public string Kind; // ready / scam_refund / scam_loss / rug / intercept / reopen
public BmOrder Order;
public BmSale Sale;
public double Amount;
}
public sealed partial class BlackMarket
{
public List<BmSeller> Sellers = new List<BmSeller>();
public List<BmListing> Catalog = new List<BmListing>();
public List<BmOrder> Orders = new List<BmOrder>();
public List<string> Forum = new List<string>();
/// <summary>平台跑路后关闭到这一天(含)。</summary>
public int ClosedUntil = -1;
/// <summary>执法接管平台的最后一天(含);期间的交易之后会被追查。</summary>
public int HoneypotUntil = -1;
public List<BmTrap> Traps = new List<BmTrap>();
public bool Honeypot(int day) => day <= HoneypotUntil;
public static double HoneypotChance(int secRep) => Math.Min(Tuning.BmHoneypotMax, Tuning.BmHoneypotBase + Math.Max(0, secRep) * Tuning.BmHoneypotPerSecRep);
private static readonly string[] NameA = { "rat", "grey", "static", "null", "dust", "iron", "pale", "wire", "salt", "ghost" };
private static readonly string[] NameB = { "king", "mule", "broker", "hand", "cat", "fox", "tooth", "lamp", "nine", "dealer" };
public bool Closed(int day) => day <= ClosedUntil;
/// <summary>托管中和已提前放款但尚未交付的资金(信用点),平台跑路的概率随它增加。</summary>
public double Held => Orders.Where(o => o.State == OrderState.Pending).Sum(o => (double)o.Price) + HeldSales;
/// <summary>批量折扣:一次订 5 件以上 95 折,10 件以上 9 折。</summary>
public static double BulkDiscount(int count) => count >= Tuning.BmBulk2Count ? Tuning.BmBulk2Discount : count >= Tuning.BmBulk1Count ? Tuning.BmBulk1Discount : 0;
public static int OrderTotal(int unit, int count) => (int)Math.Max(1, Math.Round(unit * count * (1 - BulkDiscount(count))));
public static int EscrowFee(int price) => (int)Math.Ceiling(price * Tuning.BmEscrowFee);
/// <summary>下单实付(信用点):托管 = 订单价 + 托管费;提前放款 = 订单价打折。</summary>
public static int Pay(int price, PayMode m) => m == PayMode.Escrow ? price + EscrowFee(price) : (int)Math.Round(price * (1 - Tuning.BmAdvanceDiscount));
public double RugChance => Math.Min(Tuning.BmRugMax, Tuning.BmRugBase + Held / 10000.0 * Tuning.BmRugPerTenK);
/// <summary>每周必有的"矿工路线"商家类型(从中抽 2 家),其余按全部类型抽。</summary>
private static readonly MerchantType[] Core = { MerchantType.GpuNew, MerchantType.GpuUsed, MerchantType.Rigs, MerchantType.Modules };
private static readonly MerchantType[] Others = { MerchantType.Arms, MerchantType.GunMods, MerchantType.Docs, MerchantType.Pharma, MerchantType.Chem, MerchantType.Brewer,
MerchantType.Farm, MerchantType.Husbandry, MerchantType.Miner, MerchantType.Water, MerchantType.Storage, MerchantType.Tools, MerchantType.Luxury };
private static double F(Rng rng, double lo, double hi) => lo + rng.NextDouble() * (hi - lo);
/// <summary>商家类型对应的货(含货种、库存),违禁品按声望放开等级。</summary>
private List<BmListing> MerchantGoods(int idx, BmSeller s, int day, int rep, Rng rng, Func<string, long> value)
{
var list = new List<BmListing>();
int n = s.Type == MerchantType.Bulk ? 2 : Tuning.BmMerchantListings;
bool gpuKind = s.Type == MerchantType.GpuNew || s.Type == MerchantType.GpuUsed;
var entries = s.Type == MerchantType.Bulk ? Merchants.Table.Values.SelectMany(x => x).GroupBy(x => x.Id).Select(g => g.First()).ToList()
: gpuKind ? new List<BmEntry>() : Merchants.Table[s.Type].ToList();
entries = entries.Where(e => e.Kind != GoodKind.Contraband || e.Level <= MaxLevel(rep)).ToList();
var gpus = UsedDealers.Pool(day);
for (int i = 0; i < n; i++)
{
int qty = s.Type == MerchantType.Bulk ? rng.Range(Tuning.BmBulkQtyMin, Tuning.BmBulkQtyMax) : s.Type == MerchantType.GpuNew ? rng.Range(Math.Max(1, Tuning.BmQtyMin - 1), Tuning.BmQtyMax - 2) : rng.Range(Tuning.BmQtyMin, Tuning.BmQtyMax);
double jitter = F(rng, 0.97, 1.03);
BmListing l;
if (gpuKind)
{
bool fresh = s.Type == MerchantType.GpuNew;
var c = UsedDealers.Card(gpus, fresh ? 0 : Tuning.BmGpuFake, 0, rng);
if (fresh) c.Health = 100;
l = new BmListing { Item = "gpu:" + c.Model, Kind = GoodKind.Gpu, Level = 2, Model = c.Model, FakeOf = c.FakeOf, Health = c.Health, Price = (int)Math.Max(1, Math.Round(CardValue.Of(c.Model, c.Health) * s.Factor * jitter)) };
}
else
{
if (entries.Count == 0) break;
int k = rng.Range(0, entries.Count - 1);
var e = entries[k]; entries.RemoveAt(k);
long v = value(e.Id);
if (v <= 0 || v > Tuning.BmMaxUnitValue) { i--; continue; }
l = new BmListing { Item = e.Id, Kind = e.Kind, Level = e.Level, Price = (int)Math.Max(1, Math.Round(v * s.Factor * jitter)) };
}
l.Seller = idx; l.Qty = qty;
list.Add(l);
}
return list;
}
/// <summary>每周重新生成商家、货架和论坛情报(与现货同一天刷新):从 6 种类型里抽 BmMerchantCount 家,另有概率出现一家大宗商家。</summary>
public void RefreshOrders(int day, int rep, Rng rng, Func<string, long> value)
{
Sellers.Clear(); Catalog.Clear(); Forum.Clear();
var types = Core.OrderBy(_ => rng.NextDouble()).Take(Tuning.BmCoreMerchants).ToList();
types.AddRange(Others.OrderBy(_ => rng.NextDouble()).Take(Tuning.BmMerchantCount - Tuning.BmCoreMerchants));
if (rng.Chance(Tuning.BmBulkChance)) types.Add(MerchantType.Bulk);
foreach (var t in types)
{
bool scam = rng.Chance(Tuning.BmScamSellerShare);
// 骗子多半是新号,也有刷过好评的老号
bool fresh = scam ? rng.Chance(0.6) : rng.Chance(0.25);
double lo = t == MerchantType.GpuNew ? Tuning.BmFactorNewMin : t == MerchantType.GpuUsed ? Tuning.BmFactorUsedMin : t == MerchantType.Bulk ? Tuning.BmFactorBulkMin : Tuning.BmFactorMin;
double hi = t == MerchantType.GpuNew ? Tuning.BmFactorNewMax : t == MerchantType.GpuUsed ? Tuning.BmFactorUsedMax : t == MerchantType.Bulk ? Tuning.BmFactorBulkMax : Tuning.BmFactorMax;
var s = new BmSeller
{
Name = NameA[rng.Range(0, NameA.Length - 1)] + "_" + NameB[rng.Range(0, NameB.Length - 1)] + rng.Range(1, 99),
Scam = scam, Type = t, Factor = F(rng, lo, hi),
Trades = fresh ? rng.Range(1, 12) : rng.Range(25, 220),
Rating = scam && !fresh ? rng.Range(94, 99) : fresh ? rng.Range(70, 100) : rng.Range(90, 99),
};
Sellers.Add(s);
if (scam && rng.Chance(0.5)) Forum.Add("scam:" + s.Name);
}
for (int i = 0; i < Sellers.Count; i++) Catalog.AddRange(MerchantGoods(i, Sellers[i], day, rep, rng, value));
if (RugChance > Tuning.BmRugBase * 3) Forum.Add("rug");
}
/// <summary>目录里全部货按订单价算的总值(信用点),用来核对每周周转量。</summary>
public double CatalogValue => Catalog.Sum(l => (double)l.Price * l.Qty);
/// <summary>下单:钱包里的币按实付折算扣除,污点与成本按比例留在卖家那边(记在订单上)。成功返回订单。</summary>
public BmOrder Place(BmListing l, int count, PayMode mode, Wallet w, string asset, int day, Func<string, double> price)
{
if (l == null || count < 1 || count > l.Qty || asset == Assets.CRC || Closed(day)) return null;
var seller = Sellers[l.Seller];
if (mode == PayMode.Advance && !seller.Advance) return null;
double p = price(asset);
if (p <= 0) return null;
int credits = Pay(OrderTotal(l.Price, count), mode);
double qty = credits / p;
if (w.Avail(asset) + 1e-9 < qty) return null;
double total = w.Value(price);
double share = total > 0 ? Math.Min(1, credits / total) : 0;
double taint = w.Taint * share, basis = w.Basis * share;
w.Taint -= taint; w.Basis -= basis;
w.Add(asset, -qty);
var o = new BmOrder
{
Item = l.Item, Seller = seller.Name, SellerScam = seller.Scam, Mode = mode, Count = count, Model = l.Model, FakeOf = l.FakeOf, Health = l.Health, Price = credits, Asset = asset, Qty = qty,
Taint = taint, Basis = basis, PlacedDay = day, DueDay = day + seller.Days,
};
l.Qty -= count;
if (l.Qty <= 0) Catalog.Remove(l);
Orders.Add(o);
if (Honeypot(day)) Traps.Add(new BmTrap { Day = day + Tuning.BmTrapDelay, Amount = credits, Why = "honeypot", Item = l.Item });
return o;
}
private static void Refund(Wallet w, BmOrder o)
{
w.Add(o.Asset, o.Qty);
w.Taint += o.Taint; w.Basis += o.Basis;
}
/// <summary>每晚推进订单:平台跑路、到期的订单(卖家跑路、被截获、死投被挖走)、转入可取状态。镇压期间到期顺延一天。</summary>
public List<BmEvent> Night(int day, bool crackdown, Wallet w, Rng rng, int secRep = 0, Func<string, double> price = null)
{
var ev = new List<BmEvent>();
if (!Honeypot(day) && rng.Chance(HoneypotChance(secRep))) { HoneypotUntil = day + Tuning.BmHoneypotDays; if (!Forum.Contains("easy")) Forum.Add("easy"); }
if (ClosedUntil == day) ev.Add(new BmEvent { Kind = "reopen" });
if (!Closed(day) && (Orders.Any(o => o.State == OrderState.Pending) || Sales.Any(x => x.State == SaleState.Listed || x.State == SaleState.Sold)) && rng.Chance(RugChance))
{
foreach (var o in Orders.Where(o => o.State == OrderState.Pending))
{
o.State = OrderState.Lost; o.Why = "rug";
ev.Add(new BmEvent { Kind = "rug", Order = o, Amount = o.Price });
}
foreach (var sl in Sales.Where(x => x.State == SaleState.Listed || x.State == SaleState.Sold))
{
ev.Add(new BmEvent { Kind = "sale_rug", Sale = sl, Amount = sl.State == SaleState.Sold ? sl.Proceeds : sl.ListPrice });
sl.State = SaleState.Lost; sl.Why = "rug";
}
ClosedUntil = day + Tuning.BmRugClosedDays;
Offers.Clear(); Catalog.Clear(); Sellers.Clear();
return ev;
}
foreach (var o in Orders.Where(x => x.State == OrderState.Pending).ToList())
{
if (day < o.DueDay) continue;
if (crackdown) { o.DueDay = day + 1; continue; }
if (o.SellerScam)
{
if (o.Mode == PayMode.Escrow) { Refund(w, o); o.State = OrderState.Refunded; o.Why = "scam"; ev.Add(new BmEvent { Kind = "scam_refund", Order = o, Amount = o.Price }); }
else { o.State = OrderState.Lost; o.Why = "scam"; ev.Add(new BmEvent { Kind = "scam_loss", Order = o, Amount = o.Price }); }
continue;
}
double ic = Tuning.BmInterceptDoor + (crackdown ? Tuning.BmInterceptCrackdown : 0);
if (rng.Chance(ic))
{
if (rng.Chance(Tuning.BmControlled)) { o.Controlled = true; o.State = OrderState.Ready; ev.Add(new BmEvent { Kind = "ready", Order = o }); continue; }
o.State = OrderState.Lost; o.Why = "intercept"; ev.Add(new BmEvent { Kind = "intercept", Order = o, Amount = o.Price }); continue;
}
o.State = OrderState.Ready;
ev.Add(new BmEvent { Kind = "ready", Order = o });
}
if (price != null) SalesNight(day, crackdown, w, price, rng, ev);
// 卖家落网:近期成交过的卖家各有小概率被抓,他们留存的订单记录之后会连累买家
foreach (var name in Orders.Where(x => x.State == OrderState.Done && day - x.DueDay <= 14).Select(x => x.Seller).Distinct().ToList())
{
if (!rng.Chance(Tuning.BmSellerBust)) continue;
foreach (var o in Orders.Where(x => x.State == OrderState.Done && x.Seller == name && day - x.DueDay <= 14))
Traps.Add(new BmTrap { Day = day + Tuning.BmTrapDelay, Amount = o.Price, Why = "seller", Item = o.Item });
Forum.Add("busted:" + name);
}
foreach (var t in Traps.Where(x => day >= x.Day).ToList())
{
Traps.Remove(t);
ev.Add(new BmEvent { Kind = "trap", Amount = t.Amount, Order = new BmOrder { Item = t.Item, Seller = t.Why } });
}
Orders.RemoveAll(o => o.State != OrderState.Pending && o.State != OrderState.Ready && day - o.DueDay > 14);
return ev;
}
/// <summary>受控交付:签收则当场记罪证(返回金额)并查封,不交货;拒签则损失货款,不留罪证。</summary>
public double Sign(BmOrder o, bool accept)
{
o.State = OrderState.Lost;
o.Why = accept ? "seized" : "refused";
return accept ? o.Price : 0;
}
public void Deliver(BmOrder o) { o.State = OrderState.Done; o.Why = "done"; }
public IEnumerable<BmOrder> Ready => Orders.Where(o => o.State == OrderState.Ready);
}
}