refactor(repo)!: move apps, shared packages, and patch definitions
Everything sat in packages/: two programs next to the small libraries
they use, and the patch data loose at the root. The programs now live in
apps/ and the shared libraries in packages/:
apps/server the local server (was packages/local-service),
package @wto/server
packages/patcher builds the game copy (was packages/build),
package @wto/patcher
patches/exe exe patch definitions (was exe-patches)
patches/gui GUI script patches (was gui-patches)
Inside the server, the network layer folder becomes transport/ so it is
not server/server/, the entry module is server.ts, and startLocalService
and its types become startServer, ServerOptions and RunningServer. The
health answer names the app wto-server, and the TLS files in the data
folder are server.key and server.crt (made again on the next start).
Comments, logs and tool texts say "local server".
The patcher no longer reaches into the server's folder. It read the
default tuning/store.jsonc by a relative path to register bundle GUIDs
for the multi-vehicle packs, which also ignored the player's overrides
in <data>/tuning/. It now takes the pack ids from its caller; the
server exports multiVehiclePackIds(dataFolder), which reads them the way
the running server does. rebuildGuiPack takes the patch folder from its
caller as well.
The development build moves out of the patcher to
scripts/build-game-copy.ts, since it uses both the server and the
patcher. It needs --data (the folder the server will run with) and
defaults the patch folders and the hook library to this repository.
Checked with the root typecheck, check-patches, check-gui,
check-offsets, the native build, a run of build-game-copy.ts into a
scratch folder (12 exe patches, 35 GUI patches, 496 bundle GUIDs as
before) and a server start from apps/server answering wto-server.
BREAKING CHANGE: Use @wto/server and @wto/patcher from the new workspace paths. Run the development build with scripts/build-game-copy.ts and pass --data.
This commit is contained in:
1 parent
9c813ccf7d
commit
930ea07630
476 files changed
+275
-251
No files matched your search
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* External Silver-Lion supply chests and their keyless open generators (implementation notes sections
|
||||
* 6-8). Which chests exist, their prices and prizes are tuning (tuning/supply-chests.jsonc);
|
||||
* prize groups resolve deterministically against the game data.
|
||||
*/
|
||||
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
|
||||
import {
|
||||
makeLocalizedItemDef,
|
||||
QUALITY_COLORS,
|
||||
type ExternalItemPrice,
|
||||
type GeneratorDefinition,
|
||||
type GeneratorDrop,
|
||||
type LocalizedItemDef,
|
||||
} from './itemdef-types.ts';
|
||||
import type { ChestPrizeSpec, SupplyChestSpec, SupplyChestTuning } from './supply-chest-tuning.ts';
|
||||
|
||||
export interface SupplyChestSources {
|
||||
readonly wrappersByPart: ReadonlyMap<number, readonly number[]>;
|
||||
readonly skinCouponIds: readonly number[];
|
||||
readonly decalCouponIds: readonly number[];
|
||||
readonly attachableCouponIds: readonly number[];
|
||||
/** Sorted deterministically by (rank, country, name). */
|
||||
readonly sortedMarketVehicles: readonly CatalogueVehicle[];
|
||||
}
|
||||
|
||||
export interface SupplyChestBuildResult {
|
||||
readonly defs: readonly LocalizedItemDef[];
|
||||
readonly prices: readonly ExternalItemPrice[];
|
||||
readonly generators: readonly GeneratorDefinition[];
|
||||
}
|
||||
|
||||
export function buildSupplyChests(sources: SupplyChestSources, tuning: SupplyChestTuning): SupplyChestBuildResult {
|
||||
const pairs = tuning.chests.map((spec) => createChestPair(spec, spec.prizes.flatMap((prize) => resolveDrops(prize, sources)), tuning.maxPerPurchase));
|
||||
return {
|
||||
defs: pairs.flatMap((pair) => pair.defs),
|
||||
prices: pairs.map((pair) => pair.price),
|
||||
generators: pairs.map((pair) => pair.generator),
|
||||
};
|
||||
}
|
||||
|
||||
/** Turn one prize group of the tuning file into concrete drops. */
|
||||
function resolveDrops(prize: ChestPrizeSpec, sources: SupplyChestSources): GeneratorDrop[] {
|
||||
const drops = (ids: readonly number[]) => ids.map((itemdefId) => ({ itemdefId, weight: prize.weightEach }));
|
||||
switch (prize.kind) {
|
||||
case 'classicItems':
|
||||
return drops((sources.wrappersByPart.get(prize.recyclePart) ?? []).slice(0, prize.pick));
|
||||
case 'coupons': {
|
||||
const ids = prize.couponKind === 'skin' ? sources.skinCouponIds : prize.couponKind === 'decal' ? sources.decalCouponIds : sources.attachableCouponIds;
|
||||
return drops(ids.slice(prize.skip, prize.skip + prize.pick));
|
||||
}
|
||||
case 'marketVehicles': {
|
||||
const inRange = sources.sortedMarketVehicles.filter((v) => v.rank >= prize.minRank && v.rank <= prize.maxRank);
|
||||
return drops(pickAcrossCountries(inRange, prize.pick).map((v) => v.marketplaceItemdefId!));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deterministically select `limit` vehicles from an already `(rank, country, name)`-sorted list,
|
||||
* rotating across distinct countries first so every major nation is represented before repeating.
|
||||
*/
|
||||
export function pickAcrossCountries(sorted: readonly CatalogueVehicle[], limit: number): CatalogueVehicle[] {
|
||||
const picked: CatalogueVehicle[] = [];
|
||||
const usedNames = new Set<string>();
|
||||
const seenCountriesInPass = new Set<string>();
|
||||
|
||||
while (picked.length < limit && picked.length < sorted.length) {
|
||||
seenCountriesInPass.clear();
|
||||
let addedInPass = false;
|
||||
for (const vehicle of sorted) {
|
||||
if (usedNames.has(vehicle.name) || seenCountriesInPass.has(vehicle.country)) continue;
|
||||
seenCountriesInPass.add(vehicle.country);
|
||||
usedNames.add(vehicle.name);
|
||||
picked.push(vehicle);
|
||||
addedInPass = true;
|
||||
if (picked.length >= limit) break;
|
||||
}
|
||||
if (!addedInPass) break;
|
||||
}
|
||||
return picked;
|
||||
}
|
||||
|
||||
function createChestPair(spec: SupplyChestSpec, drops: readonly GeneratorDrop[], maxPerPurchase: number): {
|
||||
readonly defs: readonly LocalizedItemDef[];
|
||||
readonly price: ExternalItemPrice;
|
||||
readonly generator: GeneratorDefinition;
|
||||
} {
|
||||
const color = QUALITY_COLORS[spec.quality] ?? '';
|
||||
const chestDef = makeLocalizedItemDef(spec.id, {
|
||||
type: 'item',
|
||||
marketable: false,
|
||||
item_quality: spec.quality,
|
||||
name_color: color,
|
||||
used_to_create: `${spec.openerId}x1`,
|
||||
tags: [
|
||||
'type:chest',
|
||||
'openingWndStyle:silverCommon',
|
||||
'showChances:yes',
|
||||
`allowToBuyAmount:${maxPerPurchase}`,
|
||||
'isAllowSkipOpeningAnim:yes',
|
||||
'hideMarketablePropDesc:yes',
|
||||
].join(';'),
|
||||
icon_url: spec.icon,
|
||||
}, spec.title, spec.description);
|
||||
|
||||
const genDef = makeLocalizedItemDef(spec.openerId, {
|
||||
type: 'generator',
|
||||
marketable: false,
|
||||
item_quality: spec.quality,
|
||||
name_color: color,
|
||||
exchange: `${spec.id}x1`,
|
||||
bundle: drops.map((d) => `${d.itemdefId}x1`).join(';'),
|
||||
tags: 'devItem:yes',
|
||||
icon_url: spec.icon,
|
||||
}, spec.title, { en: '', zh: '' });
|
||||
|
||||
return {
|
||||
defs: [chestDef, genDef],
|
||||
price: { itemdefId: spec.id, silverLions: spec.silverLions, goldenEagles: 0 },
|
||||
generator: {
|
||||
itemdefId: spec.openerId,
|
||||
isChestGenerator: true,
|
||||
chestItemdefId: spec.id,
|
||||
recipes: [{ components: [{ itemdefId: spec.id, quantity: 1 }] }],
|
||||
drops,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Content signature generation for `inventory-proxy` HTTP responses.
|
||||
*
|
||||
* Source: aces.exe 2.61.0.37:
|
||||
* - `scripts/inventory/inventoryContentSign.nut` calls `inventory.addContentPublicKey(pem)`
|
||||
* (`0x459b090 -> 0x4e6e840 -> 0x4e6ea30`), storing the SPKI DER public key on the inventory
|
||||
* `CharServerClient` (`[client + 0x58]`).
|
||||
* - `CharServerClient::loadOnlineDataCore` (`0x336ec10`) / `saveOnlineDataCore` (`0x3370bd0`)
|
||||
* captures HTTP response headers `chardContentSign` and `chardContentSignHashAlgo` (`0x336f5d0`),
|
||||
* and `0x336d590` (`0x336d9ac..0x336da05`) verifies the raw HTTP response body via `0x4e6eba0`
|
||||
* -> `0x3c38270` (`EVP_get_digestbyname` + single-line Base64 decode + `EVP_VerifyFinal`
|
||||
* RSASSA-PKCS1-v1_5). When `content_sign_check` is enabled (`GetItemDefsClient`), worker
|
||||
* `0x40cc070` requires verification code `1`, otherwise returning `CONTENT_SIGN_VALIDATION_FAILED`.
|
||||
*
|
||||
* GUI patch `inventory/local-content-public-key` replaces Gaijin's public key in
|
||||
* `inventoryContentSign.nut` with the public key paired with `local-inventory-content.key.pem`.
|
||||
*/
|
||||
import { createPrivateKey, sign, type KeyObject } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import type { ServiceResponse } from '../../transport/exchange.ts';
|
||||
|
||||
const CONTENT_SIGN_HASH_ALGO = 'SHA256';
|
||||
const SIGNING_ALGORITHM = 'RSA-SHA256';
|
||||
|
||||
let contentKey: KeyObject | undefined;
|
||||
|
||||
function localContentKey(): KeyObject {
|
||||
contentKey ??= createPrivateKey(readFileSync(join(import.meta.dirname, 'local-inventory-content.key.pem')));
|
||||
return contentKey;
|
||||
}
|
||||
|
||||
/** Build a UTF-8 JSON response signed with `chardContentSign` and `chardContentSignHashAlgo`. */
|
||||
export function signedInventoryJsonResponse(payload: unknown, summary?: string): ServiceResponse {
|
||||
const body = Buffer.from(JSON.stringify(payload), 'utf8');
|
||||
const signature = sign(SIGNING_ALGORITHM, body, localContentKey()).toString('base64');
|
||||
return {
|
||||
status: 200,
|
||||
headers: {
|
||||
'content-type': 'application/json; charset=utf-8',
|
||||
chardContentSign: signature,
|
||||
chardContentSignHashAlgo: CONTENT_SIGN_HASH_ALGO,
|
||||
},
|
||||
body,
|
||||
...(summary ? { logNotes: { summary } } : {}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDlTzqcj/V/y6zv
|
||||
drlOfwo2NytbJPqhnPPXy4Lh4fgsz5VogmUa/MDRRYwy/z+i1f67wzfAGX+442/f
|
||||
3BzfzZ14rFM+ajSBZvVzBnxJ6o1S9AmXkfEPTNI+UDYttAXCgDdojidJhxoVXtq3
|
||||
tcamH80d1hu1IIl6LQ3uGKpZ54gdxJiNmmYGTkpSz8T444Oq4gjmWKiXkuIL0Ce8
|
||||
UJUdxPjWaWJOB0e38sqIttzQChUIMd1UwE8Q+5kCf0xAml8g8l17FTwfOfjEFD0r
|
||||
Y3IhJhLt5HDGtq00901QeLFrDq3K5QIMRXYQsBjDmvChoWyo/szvpK5sFFk5tnwN
|
||||
SCxlloSVAgMBAAECggEAGqus5wHNbYg8fHukEO+wud6P0eGKrxpouBwpBGm6akfY
|
||||
mle0N7/XE2AR7uqGNcPLBX6usM6mbtQxMmnRB+zL2Hm+kt9abQSTHsZN1XEM7+2H
|
||||
YhQs4/ks6Od+bbFnDBjKmQQTqLcofvzR1pUzXiYLvuEkxtvacZXk7WD8C0nlKIT5
|
||||
Rg5Hd/ACSCF8RL63z53A3gMwvbygtJEp1myHaIM+nTgzDT6UmqoWA5p7r61LuJx+
|
||||
ky29pINz4biqKS8U7RRm+26NZ/IdL2HmpDR9/Zggznf/ncjMFrF0CxikC6Wb62F7
|
||||
4jnbUVPBEW0mRTKxyyS58VomsZ/8g9XZAnkf5xUJsQKBgQD+TEmcIucLvtatUYSV
|
||||
elAcvI5thaehTckaANjLHkeejMuuf1smkpXrg2+CSzWBkiR9/hvoJOfYDT7OWDfX
|
||||
RrLPRGbvfXXJB7KlDmf1oCbb+8BA3b0eDJEHPxDzGaL2NnwGCXeZMvymp4WMR5Or
|
||||
HtbpLD8sy5QUhnOwt2ZzisbGzQKBgQDm2CBTMUDqtk3ynmvCCAOkIbpJR1+gSNIx
|
||||
xA2mZZDCq5bO8hmSEQmgE41m1s+5+B5tXv6EGUu+O1eAWQUk/YSe3ET7oB66BXV1
|
||||
cz2KgX8owMc9CD7D0a6kFkCHR5vb0WuLdhe214TZsiZczOGb7h7JCz98oV5CUltM
|
||||
sXrOQhHk6QKBgHnbusZsX0VcnOkPEDbFFxC+No47JvoAGWcxkrG6/9z1YUFsXBSe
|
||||
1+K06EGKoshFbOFHXL4guUzqA/fDhHbPtS3nfGA1QbUk0DGSNrUYmqZ9/EHZQB/f
|
||||
K7xKN2gXF+VedI48CSjLqxB9ZFy1jAjLTXcNMfTYVUyEpXnAWQLzNI/dAoGAN40N
|
||||
AlgY8iKa0WbUMaYyEh5XsOivF2hOxNEUI9XPJzmZmgVip+bXtSDfZz8MUAlocRNq
|
||||
FinsM0Qeg3ForoUflAcXxqG6ozNLF896oMkW65ywlXxVdlQQPcZpEuTlmdlkkvQB
|
||||
MuvcOXMIjk5zgE2mNOUzCu/eOgGNnQAcuGPn4HkCgYEAh6EEP4g/QKTe83vKZKOc
|
||||
UGV1wN/4WKZdb79ZgXe0gXcH3JM/f69qbs2UPikJ5sFGhne1z7Fi7XdSlbmwjxEB
|
||||
+aueOSPxyMonM13i+DzoKX5YgiVlB9grjK4nheSj9GxwPPZvrYVVEP2VuENEujQd
|
||||
Dnv7bv/JlG4rzqQ/qYAZVDw=
|
||||
-----END PRIVATE KEY-----
|
||||
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* Decorator coupons (skins, decals, attachables), unlock/profile-icon coupons, and hidden
|
||||
* workshop stub itemdefs.
|
||||
*/
|
||||
import type {
|
||||
ExternalItemSources,
|
||||
MarketplaceDecorCoupon,
|
||||
MarketplaceUnlockCoupon,
|
||||
} from '../../game-data/datasets/external-item-sources.ts';
|
||||
import {
|
||||
makeLocalizedItemDef,
|
||||
QUALITY_COLORS,
|
||||
type CouponAction,
|
||||
type LocalizedItemDef,
|
||||
type MarketplaceListing,
|
||||
} from '../itemdef-types.ts';
|
||||
import { cosmeticCouponPrice, type MarketplaceTuning } from '../marketplace-tuning.ts';
|
||||
|
||||
const ICON_BY_KIND = {
|
||||
skin: '!#ui/gameuiskin#item_type_skin.svg',
|
||||
decal: '!#ui/gameuiskin#item_type_decal.svg',
|
||||
attachable: '!#ui/gameuiskin#item_type_attachable.svg',
|
||||
} as const;
|
||||
|
||||
const LABEL_ZH_BY_KIND = {
|
||||
skin: '涂装兑换券',
|
||||
decal: '贴花兑换券',
|
||||
attachable: '3D 装饰挂件兑换券',
|
||||
} as const;
|
||||
|
||||
export interface CosmeticCouponBuildResult {
|
||||
readonly defs: readonly LocalizedItemDef[];
|
||||
readonly coupons: ReadonlyArray<readonly [number, CouponAction]>;
|
||||
readonly listings: readonly MarketplaceListing[];
|
||||
/** Sorted ascending by itemdefId per category for deterministic chest selection. */
|
||||
readonly skinCouponIds: readonly number[];
|
||||
readonly decalCouponIds: readonly number[];
|
||||
readonly attachableCouponIds: readonly number[];
|
||||
readonly workshopStubs: readonly LocalizedItemDef[];
|
||||
}
|
||||
|
||||
export function buildCosmeticCoupons(sources: ExternalItemSources, tuning: MarketplaceTuning): CosmeticCouponBuildResult {
|
||||
const defs: LocalizedItemDef[] = [];
|
||||
const coupons: Array<readonly [number, CouponAction]> = [];
|
||||
const listings: MarketplaceListing[] = [];
|
||||
const skinCouponIds: number[] = [];
|
||||
const decalCouponIds: number[] = [];
|
||||
const attachableCouponIds: number[] = [];
|
||||
|
||||
const sortedDecors = [...sources.decorCoupons].sort((a, b) => a.itemdefId - b.itemdefId);
|
||||
for (const decor of sortedDecors) {
|
||||
const built = buildSingleDecorCoupon(decor, tuning);
|
||||
defs.push(built.def);
|
||||
coupons.push([decor.itemdefId, built.action]);
|
||||
listings.push(built.listing);
|
||||
if (decor.kind === 'skin') skinCouponIds.push(decor.itemdefId);
|
||||
else if (decor.kind === 'decal') decalCouponIds.push(decor.itemdefId);
|
||||
else attachableCouponIds.push(decor.itemdefId);
|
||||
}
|
||||
|
||||
const sortedUnlocks = [...sources.unlockCoupons].sort((a, b) => a.itemdefId - b.itemdefId);
|
||||
for (const unlock of sortedUnlocks) {
|
||||
const built = buildSingleUnlockCoupon(unlock, tuning);
|
||||
defs.push(built.def);
|
||||
coupons.push([unlock.itemdefId, built.action]);
|
||||
listings.push(built.listing);
|
||||
}
|
||||
|
||||
const workshopStubs = [...sources.workshopItemdefIds]
|
||||
.sort((a, b) => a - b)
|
||||
.map((workshopId) => makeLocalizedItemDef(workshopId, {
|
||||
type: 'item',
|
||||
marketable: false,
|
||||
item_quality: 1,
|
||||
tags: 'type:craft_part;devItem:yes;hideDesc:yes',
|
||||
icon_url: '!#ui/gameuiskin#item_type_craftpart.svg',
|
||||
}, { en: `Workshop Component #${workshopId}`, zh: `工坊组件 #${workshopId}` }, { en: '', zh: '' }));
|
||||
|
||||
return { defs, coupons, listings, skinCouponIds, decalCouponIds, attachableCouponIds, workshopStubs };
|
||||
}
|
||||
|
||||
function buildSingleDecorCoupon(decor: MarketplaceDecorCoupon, tuning: MarketplaceTuning): {
|
||||
readonly def: LocalizedItemDef;
|
||||
readonly action: CouponAction;
|
||||
readonly listing: MarketplaceListing;
|
||||
} {
|
||||
const { gjnCents, quality } = cosmeticCouponPrice(tuning, decor.kind, decor.resourceKey);
|
||||
const color = QUALITY_COLORS[quality] ?? '';
|
||||
const hashName = `${decor.kind}_${decor.itemdefId}`;
|
||||
const def = makeLocalizedItemDef(decor.itemdefId, {
|
||||
type: 'item',
|
||||
marketable: true,
|
||||
market_hash_name: hashName,
|
||||
item_quality: quality,
|
||||
name_color: color,
|
||||
tags: `type:${decor.kind}`,
|
||||
meta: `resource:t="${decor.resourceKey}"\nresourceType:t="${decor.kind}"`,
|
||||
icon_url: ICON_BY_KIND[decor.kind],
|
||||
}, decor.name, {
|
||||
en: `Coupon for ${decor.kind}: ${decor.name.en}.`,
|
||||
zh: `${LABEL_ZH_BY_KIND[decor.kind]}:${decor.name.zh}。`,
|
||||
});
|
||||
const action: CouponAction = { kind: 'decor', decorKind: decor.kind, resourceKey: decor.resourceKey };
|
||||
const listing: MarketplaceListing = {
|
||||
itemdefId: decor.itemdefId,
|
||||
marketHashName: hashName,
|
||||
category: decor.kind,
|
||||
gjnCostCents: gjnCents,
|
||||
quality,
|
||||
nameColor: color,
|
||||
title: decor.name,
|
||||
subtitle: { en: `${decor.kind} coupon`, zh: LABEL_ZH_BY_KIND[decor.kind] },
|
||||
targetKey: decor.resourceKey,
|
||||
};
|
||||
return { def, action, listing };
|
||||
}
|
||||
|
||||
function buildSingleUnlockCoupon(unlock: MarketplaceUnlockCoupon, tuning: MarketplaceTuning): {
|
||||
readonly def: LocalizedItemDef;
|
||||
readonly action: CouponAction;
|
||||
readonly listing: MarketplaceListing;
|
||||
} {
|
||||
const { gjnCents, quality } = cosmeticCouponPrice(tuning, 'unlock', unlock.unlockId);
|
||||
const color = QUALITY_COLORS[quality] ?? '';
|
||||
const hashName = `unlock_${unlock.itemdefId}`;
|
||||
const def = makeLocalizedItemDef(unlock.itemdefId, {
|
||||
type: 'item',
|
||||
marketable: true,
|
||||
market_hash_name: hashName,
|
||||
item_quality: quality,
|
||||
name_color: color,
|
||||
tags: 'type:unlock',
|
||||
meta: `unlock:t="${unlock.unlockId}"`,
|
||||
icon_url: '!#ui/gameuiskin#item_type_unlock.svg',
|
||||
}, unlock.name, {
|
||||
en: `Coupon for unlock: ${unlock.name.en}.`,
|
||||
zh: `头像/收藏解锁兑换券:${unlock.name.zh}。`,
|
||||
});
|
||||
const action: CouponAction = { kind: 'unlock', unlockId: unlock.unlockId };
|
||||
const listing: MarketplaceListing = {
|
||||
itemdefId: unlock.itemdefId,
|
||||
marketHashName: hashName,
|
||||
category: 'unlock',
|
||||
gjnCostCents: gjnCents,
|
||||
quality,
|
||||
nameColor: color,
|
||||
title: unlock.name,
|
||||
subtitle: { en: 'Profile icon / unlock coupon', zh: '头像与解锁兑换券' },
|
||||
targetKey: unlock.unlockId,
|
||||
};
|
||||
return { def, action, listing };
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* Marketplace vehicle coupon definitions (`shop.blk` `marketplaceItemdefId`, 233 vehicles in
|
||||
* 2.61.0.37; implementation notes).
|
||||
*/
|
||||
import type { LocalizedText } from '../../game-data/datasets/unit-names.ts';
|
||||
import type { CatalogueVehicle } from '../../game-data/datasets/vehicle-catalogue.ts';
|
||||
import { vehicleTypeOfClass } from '../../research/vehicle-types.ts';
|
||||
import {
|
||||
makeLocalizedItemDef,
|
||||
QUALITY_COLORS,
|
||||
type CouponAction,
|
||||
type LocalizedItemDef,
|
||||
type MarketplaceListing,
|
||||
} from '../itemdef-types.ts';
|
||||
import { vehicleCouponPrice, type MarketplaceTuning } from '../marketplace-tuning.ts';
|
||||
|
||||
export interface VehicleCouponBuildResult {
|
||||
readonly defs: readonly LocalizedItemDef[];
|
||||
readonly coupons: ReadonlyArray<readonly [number, CouponAction]>;
|
||||
readonly listings: readonly MarketplaceListing[];
|
||||
/** Marketplace vehicles sorted deterministically by (rank, country, name). */
|
||||
readonly sortedVehicles: readonly CatalogueVehicle[];
|
||||
}
|
||||
|
||||
export function buildVehicleCoupons(
|
||||
vehicles: readonly CatalogueVehicle[],
|
||||
unitNames: Readonly<Record<string, LocalizedText>>,
|
||||
tuning: MarketplaceTuning,
|
||||
): VehicleCouponBuildResult {
|
||||
const defs: LocalizedItemDef[] = [];
|
||||
const coupons: Array<readonly [number, CouponAction]> = [];
|
||||
const listings: MarketplaceListing[] = [];
|
||||
|
||||
const sortedVehicles = vehicles
|
||||
.filter((vehicle) => vehicle.marketplaceItemdefId !== undefined)
|
||||
.sort((a, b) => (a.rank - b.rank) || a.country.localeCompare(b.country) || a.name.localeCompare(b.name));
|
||||
|
||||
for (const vehicle of sortedVehicles) {
|
||||
const id = vehicle.marketplaceItemdefId!;
|
||||
const unitTitle = unitNames[vehicle.name] ?? { en: vehicle.name, zh: vehicle.name };
|
||||
const { gjnCents: gjnCostCents, quality } = vehicleCouponPrice(tuning, vehicle.name, vehicle.rank);
|
||||
const color = QUALITY_COLORS[quality] ?? '';
|
||||
const tagType = unitClassTag(vehicle.unitClass);
|
||||
|
||||
defs.push(makeLocalizedItemDef(id, {
|
||||
type: 'item',
|
||||
marketable: true,
|
||||
market_hash_name: vehicle.name,
|
||||
item_quality: quality,
|
||||
name_color: color,
|
||||
tags: `type:${tagType}`,
|
||||
meta: `unit:t="${vehicle.name}"`,
|
||||
icon_url: '!#ui/gameuiskin#item_type_blueprints.svg',
|
||||
icon_url_large: '!#ui/gameuiskin#item_type_blueprints.svg',
|
||||
}, unitTitle, {
|
||||
en: `Exchangeable coupon for ${unitTitle.en} (Rank ${vehicle.rank}).`,
|
||||
zh: `可兑换载具券:${unitTitle.zh}(${vehicle.rank} 级)。`,
|
||||
}));
|
||||
coupons.push([id, { kind: 'vehicle', unitName: vehicle.name, parts: vehicle.parts }]);
|
||||
listings.push({
|
||||
itemdefId: id,
|
||||
marketHashName: vehicle.name,
|
||||
category: 'vehicle',
|
||||
gjnCostCents,
|
||||
quality,
|
||||
nameColor: color,
|
||||
title: unitTitle,
|
||||
subtitle: { en: `Rank ${vehicle.rank} ${tagType}`, zh: `${vehicle.rank} 级载具兑换券` },
|
||||
country: vehicle.country,
|
||||
unitClass: marketUnitClassOf(vehicle.unitClass),
|
||||
rank: vehicle.rank,
|
||||
targetKey: vehicle.name,
|
||||
});
|
||||
}
|
||||
|
||||
return { defs, coupons, listings, sortedVehicles };
|
||||
}
|
||||
|
||||
function unitClassTag(unitClass: string): string {
|
||||
switch (vehicleTypeOfClass(unitClass)) {
|
||||
case 'Aircraft':
|
||||
return 'aircraft';
|
||||
case 'Helicopter':
|
||||
return 'helicopter';
|
||||
case 'Tank':
|
||||
return 'tank';
|
||||
case 'Ship':
|
||||
case 'Boat':
|
||||
return 'ship';
|
||||
default:
|
||||
return 'tank';
|
||||
}
|
||||
}
|
||||
|
||||
function marketUnitClassOf(unitClass: string): string {
|
||||
switch (vehicleTypeOfClass(unitClass)) {
|
||||
case 'Aircraft':
|
||||
return 'aircraft';
|
||||
case 'Helicopter':
|
||||
return 'helicopter';
|
||||
case 'Tank':
|
||||
return 'tank';
|
||||
case 'Ship':
|
||||
return 'ship';
|
||||
case 'Boat':
|
||||
return 'boat';
|
||||
default:
|
||||
return 'tank';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
/**
|
||||
* Pure domain rules for external inventory coupon consumption, item recycling, generator
|
||||
* exchanges (chest opening and workshop/recycle crafting), and GJN marketplace coupon purchases
|
||||
*. Wire JSON formatting lives in `inventory-wire.ts`.
|
||||
*/
|
||||
import type { BlkBlock, BlkParam } from '@wto/blk';
|
||||
import type { ItemCatalogue } from '../items/item-catalogue.ts';
|
||||
import { grantItem } from '../items/item-grants.ts';
|
||||
import { balanceOf, canAfford, pay, payGjnCents } from '../profile/profile-currency.ts';
|
||||
import {
|
||||
consumeExternalItem,
|
||||
externalItemByUid,
|
||||
grantExternalItem,
|
||||
type StoredExternalItem,
|
||||
} from '../profile/profile-external-inventory.ts';
|
||||
import { addOwnedVehicle, ownsVehicle } from '../profile/profile-hangar.ts';
|
||||
import { ownedItem, removeItem, setItemCount } from '../profile/profile-items.ts';
|
||||
import { addResource, ownsResource } from '../profile/profile-resources.ts';
|
||||
import { appendUserLog, EULT_OPEN_TROPHY, incrementTrophyOpenCount } from '../profile/profile-trophies-log.ts';
|
||||
import { addUnlock, earnedUnlocks } from '../profile/profile-unlocks.ts';
|
||||
import type { ServerTime } from '../profile/server-time.ts';
|
||||
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
|
||||
import type { ExchangeMaterialInput } from './inventory-wire.ts';
|
||||
import type { InventoryCatalogue } from './itemdef-catalogue.ts';
|
||||
import type { GeneratorDefinition, GeneratorDrop } from './itemdef-types.ts';
|
||||
|
||||
export function pickWeighted<T extends { readonly weight: number }>(entries: readonly T[]): T {
|
||||
const total = entries.reduce((sum, entry) => sum + entry.weight, 0);
|
||||
let roll = Math.random() * total;
|
||||
for (const entry of entries) {
|
||||
roll -= entry.weight;
|
||||
if (roll <= 0) return entry;
|
||||
}
|
||||
return entries[entries.length - 1]!;
|
||||
}
|
||||
|
||||
/** `cln_consume_inventory_item` (char_send_blk): consume coupon(s) into vehicles, decor, unlocks or items. */
|
||||
export function consumeInventoryCoupon(
|
||||
profile: BlkBlock,
|
||||
catalogue: InventoryCatalogue,
|
||||
classicItems: ItemCatalogue,
|
||||
itemUid: string,
|
||||
quantity: number,
|
||||
now: ServerTime,
|
||||
): RuleOutcome {
|
||||
if (!Number.isSafeInteger(quantity) || quantity < 1) return refused('BAD_PARAMS');
|
||||
const held = externalItemByUid(profile, itemUid);
|
||||
if (!held || held.quantity < quantity) return refused('NOT_AVAILABLE');
|
||||
|
||||
const action = catalogue.couponAction(held.itemDefId);
|
||||
if (!action) return refused('NOT_AVAILABLE');
|
||||
|
||||
switch (action.kind) {
|
||||
case 'vehicle': {
|
||||
if (ownsVehicle(profile, action.unitName) || !consumeExternalItem(profile, itemUid, 1)) return refused('NOT_AVAILABLE');
|
||||
addOwnedVehicle(profile, action.unitName);
|
||||
for (const part of action.parts) addOwnedVehicle(profile, part);
|
||||
return ACCEPTED;
|
||||
}
|
||||
case 'decor': {
|
||||
if (ownsResource(profile, action.resourceKey) || !consumeExternalItem(profile, itemUid, 1)) return refused('NOT_AVAILABLE');
|
||||
addResource(profile, action.resourceKey, { silverLions: 0, goldenEagles: 0 });
|
||||
return ACCEPTED;
|
||||
}
|
||||
case 'unlock': {
|
||||
if (earnedUnlocks(profile).has(action.unlockId) || !consumeExternalItem(profile, itemUid, 1)) return refused('NOT_AVAILABLE');
|
||||
addUnlock(profile, action.unlockId);
|
||||
return ACCEPTED;
|
||||
}
|
||||
case 'classic-item': {
|
||||
const def = classicItems.item(action.itemName);
|
||||
if (!def) return refused('BAD_PARAMS');
|
||||
if (!consumeExternalItem(profile, itemUid, quantity)) return refused('NOT_AVAILABLE');
|
||||
grantItem(profile, def, action.count * quantity, now);
|
||||
return ACCEPTED;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** `cln_multi_consume_inventory_item_json`: batch auto-consume of external items. */
|
||||
export function multiConsumeInventoryItems(
|
||||
profile: BlkBlock,
|
||||
catalogue: InventoryCatalogue,
|
||||
classicItems: ItemCatalogue,
|
||||
requests: ReadonlyArray<{ readonly itemId: number; readonly quantity: number }>,
|
||||
now: ServerTime,
|
||||
): { readonly revertedItems: number[] } {
|
||||
const revertedItems: number[] = [];
|
||||
for (const req of requests) {
|
||||
const outcome = consumeInventoryCoupon(profile, catalogue, classicItems, String(req.itemId), req.quantity, now);
|
||||
if (!outcome.ok) revertedItems.push(req.itemId);
|
||||
}
|
||||
return { revertedItems };
|
||||
}
|
||||
|
||||
/** `cln_inventory_purchase_item`: buy external inventory chests/items priced in GetItemPrices. */
|
||||
export function purchaseExternalInventoryItem(
|
||||
profile: BlkBlock,
|
||||
catalogue: InventoryCatalogue,
|
||||
itemDefId: number,
|
||||
amount: number,
|
||||
offeredWp: number,
|
||||
offeredGold: number,
|
||||
): RuleOutcome {
|
||||
if (!Number.isSafeInteger(amount) || amount < 1 || amount > 100) return refused('BAD_PARAMS');
|
||||
const unitPrice = catalogue.priceOf(itemDefId);
|
||||
if (!unitPrice) return refused('NOT_AVAILABLE');
|
||||
if (offeredWp !== unitPrice.silverLions || offeredGold !== unitPrice.goldenEagles) return refused('PRICE_CHANGED');
|
||||
|
||||
const totalPrice = { silverLions: unitPrice.silverLions * amount, goldenEagles: unitPrice.goldenEagles * amount };
|
||||
if (!canAfford(profile, totalPrice)) return refused('NOT_ENOUGH_MONEY');
|
||||
|
||||
pay(profile, totalPrice);
|
||||
grantExternalItem(profile, itemDefId, amount);
|
||||
return ACCEPTED;
|
||||
}
|
||||
|
||||
/** `cln_recycle_items`: convert classic profile items into external craft_part items (299000..299004). */
|
||||
export function recycleClassicItems(
|
||||
profile: BlkBlock,
|
||||
classicItems: ItemCatalogue,
|
||||
requests: ReadonlyArray<{ readonly uid: string; readonly count: number }>,
|
||||
): RuleOutcome {
|
||||
if (requests.length === 0) return refused('BAD_PARAMS');
|
||||
const countsByUid = new Map<string, number>();
|
||||
for (const entry of requests) {
|
||||
if (!entry.uid || !Number.isSafeInteger(entry.count) || entry.count < 1) return refused('BAD_PARAMS');
|
||||
countsByUid.set(entry.uid, (countsByUid.get(entry.uid) ?? 0) + entry.count);
|
||||
}
|
||||
|
||||
const validated: Array<{ readonly uid: string; readonly count: number; readonly remaining: number; readonly partId: number }> = [];
|
||||
for (const [uid, count] of countsByUid) {
|
||||
const owned = ownedItem(profile, uid);
|
||||
if (!owned || owned.count < count) return refused('NOT_AVAILABLE');
|
||||
const partId = classicItems.item(owned.id)?.recycleItemResult;
|
||||
if (!partId) return refused('NOT_AVAILABLE');
|
||||
validated.push({ uid, count, remaining: owned.count - count, partId });
|
||||
}
|
||||
|
||||
const nowIso = new Date().toISOString();
|
||||
for (const item of validated) {
|
||||
if (item.remaining <= 0) removeItem(profile, item.uid);
|
||||
else setItemCount(profile, item.uid, item.remaining);
|
||||
grantExternalItem(profile, item.partId, item.count, nowIso);
|
||||
}
|
||||
return ACCEPTED;
|
||||
}
|
||||
|
||||
export interface ExchangeItemDelta {
|
||||
readonly itemId: string;
|
||||
readonly itemDefId: number;
|
||||
readonly quantity: number;
|
||||
readonly timestamp: string;
|
||||
}
|
||||
|
||||
export type ExchangeOutcome =
|
||||
| { readonly ok: true; readonly delta: ExchangeItemDelta[] }
|
||||
| { readonly ok: false; readonly code: string };
|
||||
|
||||
/** `ExchangeItems` / `cln_inventory_exchange_items`: execute a generator recipe and roll drops. */
|
||||
export function exchangeInventoryItems(
|
||||
profile: BlkBlock,
|
||||
catalogue: InventoryCatalogue,
|
||||
outputItemDefId: number,
|
||||
quantity: number,
|
||||
materials: readonly ExchangeMaterialInput[],
|
||||
nowSec = Math.floor(Date.now() / 1000),
|
||||
): ExchangeOutcome {
|
||||
if (!Number.isSafeInteger(quantity) || quantity < 1 || quantity > 100 || materials.length === 0) {
|
||||
return { ok: false, code: 'BAD_PARAMS' };
|
||||
}
|
||||
const gen = catalogue.generator(outputItemDefId);
|
||||
if (!gen || gen.drops.length === 0) return { ok: false, code: 'UNKNOWN_GENERATOR' };
|
||||
|
||||
const validationError = validateRecipeMaterials(profile, gen, quantity, materials);
|
||||
if (validationError) return { ok: false, code: validationError };
|
||||
|
||||
const nowIso = new Date(nowSec * 1000).toISOString();
|
||||
const deltaByUid = new Map<string, ExchangeItemDelta>();
|
||||
|
||||
for (const mat of materials) {
|
||||
const uid = String(mat.itemid);
|
||||
const consumed = consumeExternalItem(profile, uid, mat.quantity, nowIso);
|
||||
if (!consumed) return { ok: false, code: 'NOT_ENOUGH_ITEMS' };
|
||||
deltaByUid.set(uid, { itemId: uid, itemDefId: consumed.itemDefId, quantity: consumed.remaining, timestamp: nowIso });
|
||||
}
|
||||
|
||||
rollGeneratorOutputs(profile, gen, quantity, nowSec, nowIso, deltaByUid);
|
||||
return { ok: true, delta: [...deltaByUid.values()] };
|
||||
}
|
||||
|
||||
function validateRecipeMaterials(
|
||||
profile: BlkBlock,
|
||||
gen: GeneratorDefinition,
|
||||
quantity: number,
|
||||
materials: readonly ExchangeMaterialInput[],
|
||||
): string | undefined {
|
||||
const providedByDef = new Map<number, number>();
|
||||
const providedByStack = new Map<string, number>();
|
||||
for (const mat of materials) {
|
||||
if (!mat.itemid || !Number.isSafeInteger(mat.quantity) || mat.quantity < 1) return 'BAD_MATERIALS';
|
||||
const held = externalItemByUid(profile, mat.itemid);
|
||||
const stackQuantity = (providedByStack.get(mat.itemid) ?? 0) + mat.quantity;
|
||||
if (!held || (mat.itemdefid !== undefined && held.itemDefId !== mat.itemdefid) || held.quantity < stackQuantity) {
|
||||
return 'NOT_ENOUGH_ITEMS';
|
||||
}
|
||||
providedByStack.set(mat.itemid, stackQuantity);
|
||||
providedByDef.set(held.itemDefId, (providedByDef.get(held.itemDefId) ?? 0) + mat.quantity);
|
||||
}
|
||||
const matches = gen.recipes.some((recipe) =>
|
||||
recipe.components.length === providedByDef.size
|
||||
&& recipe.components.every((comp) => providedByDef.get(comp.itemdefId) === comp.quantity * quantity));
|
||||
return matches ? undefined : 'RECIPE_MISMATCH';
|
||||
}
|
||||
|
||||
function rollGeneratorOutputs(
|
||||
profile: BlkBlock,
|
||||
gen: GeneratorDefinition,
|
||||
quantity: number,
|
||||
nowSec: number,
|
||||
nowIso: string,
|
||||
deltaByUid: Map<string, ExchangeItemDelta>,
|
||||
): void {
|
||||
for (let i = 0; i < quantity; i += 1) {
|
||||
const dropDefId = pickWeighted<GeneratorDrop>(gen.drops).itemdefId;
|
||||
const granted = grantExternalItem(profile, dropDefId, 1, nowIso);
|
||||
deltaByUid.set(granted.itemId, granted);
|
||||
|
||||
if (gen.isChestGenerator && gen.chestItemdefId !== undefined) {
|
||||
// Allocate a unique monotonically increasing open sequence ID so opening multiple chests
|
||||
// in one batch never overwrites same-itemDefId entries in buyAndOpenChestWnd.nut.
|
||||
const uniqueOpenId = incrementTrophyOpenCount(profile, 'trophyFromInventory', 1);
|
||||
const logParams: BlkParam[] = [
|
||||
{ name: 'id', value: { type: 'string', value: 'trophyFromInventory' } },
|
||||
{ name: 'fromInventory', value: { type: 'bool', value: true } },
|
||||
{ name: 'itemDefId', value: { type: 'int', value: gen.chestItemdefId } },
|
||||
{ name: 'itemId', value: { type: 'int', value: uniqueOpenId } },
|
||||
{ name: 'item', value: { type: 'int', value: dropDefId } },
|
||||
{ name: 'count', value: { type: 'int', value: 1 } },
|
||||
];
|
||||
appendUserLog(profile, { type: EULT_OPEN_TROPHY, timeSec: nowSec, bodyParams: logParams });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export type MarketBuyOutcome =
|
||||
| { readonly ok: true; readonly item: StoredExternalItem }
|
||||
| { readonly ok: false; readonly reason: 'NOT_FOUND' | 'NOT_ENOUGH_GJN' };
|
||||
|
||||
export function buyMarketplaceCoupon(
|
||||
profile: BlkBlock,
|
||||
catalogue: InventoryCatalogue,
|
||||
itemdefId: number,
|
||||
quantity: number,
|
||||
maxPerPurchase: number,
|
||||
): MarketBuyOutcome {
|
||||
const listing = validCouponPurchase(catalogue, itemdefId, quantity, maxPerPurchase);
|
||||
if (!listing) return { ok: false, reason: 'NOT_FOUND' };
|
||||
const totalCost = listing.gjnCostCents * quantity;
|
||||
if (balanceOf(profile).gjnCents < totalCost) return { ok: false, reason: 'NOT_ENOUGH_GJN' };
|
||||
|
||||
payGjnCents(profile, totalCost);
|
||||
return { ok: true, item: grantExternalItem(profile, itemdefId, quantity) };
|
||||
}
|
||||
|
||||
/** Claim a marketplace coupon with the free offline payment method. */
|
||||
export function buyFreeMarketplaceCoupon(
|
||||
profile: BlkBlock,
|
||||
catalogue: InventoryCatalogue,
|
||||
itemdefId: number,
|
||||
quantity: number,
|
||||
maxPerPurchase: number,
|
||||
): MarketBuyOutcome {
|
||||
const listing = validCouponPurchase(catalogue, itemdefId, quantity, maxPerPurchase);
|
||||
if (!listing) return { ok: false, reason: 'NOT_FOUND' };
|
||||
return { ok: true, item: grantExternalItem(profile, itemdefId, quantity) };
|
||||
}
|
||||
|
||||
function validCouponPurchase(
|
||||
catalogue: InventoryCatalogue,
|
||||
itemdefId: number,
|
||||
quantity: number,
|
||||
maxPerPurchase: number,
|
||||
) {
|
||||
if (!Number.isSafeInteger(quantity) || quantity < 1 || quantity > maxPerPurchase) return undefined;
|
||||
return catalogue.marketplaceListing(itemdefId);
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* External inventory HTTP service (`inventory-proxy-0{1,2}.gaijin.net/char`; implementation notes).
|
||||
*
|
||||
* Unlike CharService (which prepends the `0x69` uncompressed marker to binary BLK answers),
|
||||
* `charsq` (`0x459cac0 -> 0x459e020`) parses the raw HTTP body directly as UTF-8 JSON unless
|
||||
* it equals `"!OK"` or starts with `"!ERROR:"`.
|
||||
*/
|
||||
import type { Account, AccountStore } from '../accounts/account-store.ts';
|
||||
import { userIdFromToken } from '../login/session-credentials.ts';
|
||||
import type { PlayerProfiles } from '../profile/player-profiles.ts';
|
||||
import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts';
|
||||
import { signedInventoryJsonResponse } from './content-sign/content-signature.ts';
|
||||
import { exchangeInventoryItems, type ExchangeItemDelta } from './inventory-rules.ts';
|
||||
import { deltaToInventoryJson, parseExchangeItemsRequest, toInventoryJsonList } from './inventory-wire.ts';
|
||||
import type { InventoryCatalogue } from './itemdef-catalogue.ts';
|
||||
|
||||
const INVENTORY_HOST = /^inventory-proxy-[a-z0-9-]+\.gaijin\.net$/;
|
||||
const TEXT_HEADERS = { 'content-type': 'text/plain; charset=utf-8' };
|
||||
|
||||
export class InventoryService implements Service {
|
||||
readonly name = 'inventory';
|
||||
readonly #accounts: AccountStore;
|
||||
readonly #profiles: PlayerProfiles;
|
||||
readonly #catalogue: InventoryCatalogue;
|
||||
|
||||
constructor(accounts: AccountStore, profiles: PlayerProfiles, catalogue: InventoryCatalogue) {
|
||||
this.#accounts = accounts;
|
||||
this.#profiles = profiles;
|
||||
this.#catalogue = catalogue;
|
||||
}
|
||||
|
||||
accepts(request: ServiceRequest): boolean {
|
||||
return request.originalHost !== undefined && INVENTORY_HOST.test(request.originalHost);
|
||||
}
|
||||
|
||||
handle(request: ServiceRequest): ServiceResponse {
|
||||
const action = headerOf(request, 'action') ?? '';
|
||||
switch (action) {
|
||||
case 'GetInventory':
|
||||
return this.#getInventory(request);
|
||||
case 'GetItemDefsClient':
|
||||
return this.#getItemDefs(request);
|
||||
case 'GetItemPrices':
|
||||
return this.#getItemPrices(request);
|
||||
case 'GetItemDefChances':
|
||||
return this.#getItemDefChances(request);
|
||||
case 'ExchangeItems':
|
||||
return this.#exchangeItems(request);
|
||||
case 'CancelDelayedExchange':
|
||||
return signedInventoryJsonResponse({ response: { item_json: [] } }, 'CancelDelayedExchange -> 0 items');
|
||||
default:
|
||||
return signedInventoryJsonResponse({ response: {} }, `${action || '(no action)'} -> empty response`);
|
||||
}
|
||||
}
|
||||
|
||||
#getInventory(request: ServiceRequest): ServiceResponse {
|
||||
const account = this.#resolveAccount(request);
|
||||
if (!account) return errorResponse('UNAUTHORIZED', 'GetInventory: unknown account');
|
||||
const items = toInventoryJsonList(this.#profiles.profileOf(account.userId), account.userId);
|
||||
return signedInventoryJsonResponse({ response: { item_json: items } }, `GetInventory -> ${items.length} stack(s)`);
|
||||
}
|
||||
|
||||
#getItemDefs(request: ServiceRequest): ServiceResponse {
|
||||
const rawIds = headerOf(request, 'itemdefids') ?? '';
|
||||
const language = headerOf(request, 'language') ?? 'english';
|
||||
const ids = rawIds.split(',').map((part) => Number(part.trim())).filter((n) => Number.isSafeInteger(n) && n > 0);
|
||||
const defs = this.#catalogue.itemDefs(ids, language);
|
||||
return signedInventoryJsonResponse({ response: { itemdef_json: defs } }, `GetItemDefsClient (${defs.length} defs, lang=${language})`);
|
||||
}
|
||||
|
||||
#getItemPrices(request: ServiceRequest): ServiceResponse {
|
||||
const currency = headerOf(request, 'currency') === 'WTE' ? 'WTE' : 'WTS';
|
||||
const itemPrices = this.#catalogue.pricesForCurrency(currency);
|
||||
return signedInventoryJsonResponse({ response: { itemPrices } }, `GetItemPrices (${currency}) -> ${itemPrices.length} item(s)`);
|
||||
}
|
||||
|
||||
#getItemDefChances(request: ServiceRequest): ServiceResponse {
|
||||
const rawId = headerOf(request, 'itemdefs') ?? '';
|
||||
const generatorId = Number(rawId.trim());
|
||||
const chances = Number.isSafeInteger(generatorId) ? this.#catalogue.chancesForGenerator(generatorId) : undefined;
|
||||
const response: Record<string, unknown> = chances ? { [String(generatorId)]: chances } : {};
|
||||
return signedInventoryJsonResponse({ response }, `GetItemDefChances (${generatorId}) -> ${chances?.length ?? 0} drop(s)`);
|
||||
}
|
||||
|
||||
#exchangeItems(request: ServiceRequest): ServiceResponse {
|
||||
const account = this.#resolveAccount(request);
|
||||
if (!account) return errorResponse('UNAUTHORIZED', 'ExchangeItems: unknown account');
|
||||
|
||||
const parsed = parseExchangeItemsRequest(request.body.toString('utf8'));
|
||||
if (!parsed) return errorResponse('BAD_JSON', 'ExchangeItems: invalid JSON');
|
||||
|
||||
let delta: ExchangeItemDelta[] | undefined;
|
||||
let errorCode = 'EXCHANGE_FAILED';
|
||||
this.#profiles.updateWhen(account.userId, (saved) => {
|
||||
const res = exchangeInventoryItems(saved, this.#catalogue, parsed.outputItemDefId, parsed.quantity, parsed.materials);
|
||||
if (!res.ok) {
|
||||
errorCode = res.code;
|
||||
return false;
|
||||
}
|
||||
delta = res.delta;
|
||||
return true;
|
||||
});
|
||||
|
||||
if (!delta) return errorResponse(errorCode, `ExchangeItems (${parsed.outputItemDefId}) -> ${errorCode}`);
|
||||
const jsonDelta = deltaToInventoryJson(delta, account.userId);
|
||||
return signedInventoryJsonResponse({ response: { item_json: jsonDelta } }, `ExchangeItems (${parsed.outputItemDefId} x${parsed.quantity}) -> ${jsonDelta.length} delta item(s)`);
|
||||
}
|
||||
|
||||
#resolveAccount(request: ServiceRequest): Account | undefined {
|
||||
const uidHint = headerOf(request, 'uidhint');
|
||||
if (uidHint) return this.#accounts.byUserId(uidHint);
|
||||
const token = headerOf(request, 'token');
|
||||
const tokenUid = token ? userIdFromToken(token) : undefined;
|
||||
return tokenUid ? this.#accounts.byUserId(tokenUid) : undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function headerOf(request: ServiceRequest, name: string): string | undefined {
|
||||
const value = request.headers[name];
|
||||
const text = Array.isArray(value) ? value[0] : value;
|
||||
return text ? text : undefined;
|
||||
}
|
||||
|
||||
function errorResponse(code: string, summary: string): ServiceResponse {
|
||||
return { status: 200, headers: TEXT_HEADERS, body: `!ERROR:${code}`, logNotes: { summary } };
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* Protocol-layer JSON encoders and parsers for `inventory-proxy` (`GetInventory`,
|
||||
* `ExchangeItems`) and `cln_inventory_exchange_items`.
|
||||
*/
|
||||
import type { BlkBlock } from '@wto/blk';
|
||||
import { externalInventoryItems, type StoredExternalItem } from '../profile/profile-external-inventory.ts';
|
||||
import type { ExchangeItemDelta } from './inventory-rules.ts';
|
||||
import type { InventoryItemJson } from './itemdef-types.ts';
|
||||
|
||||
export interface ExchangeMaterialInput {
|
||||
readonly itemid: string;
|
||||
/** Present in the object form. The native tuple identifies the stack by itemid. */
|
||||
readonly itemdefid?: number;
|
||||
readonly quantity: number;
|
||||
}
|
||||
|
||||
export interface ParsedExchangeRequest {
|
||||
readonly outputItemDefId: number;
|
||||
readonly quantity: number;
|
||||
readonly materials: readonly ExchangeMaterialInput[];
|
||||
}
|
||||
|
||||
export function toInventoryJsonList(profile: BlkBlock, accountId: string): InventoryItemJson[] {
|
||||
return externalInventoryItems(profile).map((item) => toInventoryJson(item, accountId));
|
||||
}
|
||||
|
||||
export function toInventoryJson(item: StoredExternalItem, accountId: string): InventoryItemJson {
|
||||
return {
|
||||
itemid: item.itemId,
|
||||
itemdef: item.itemDefId,
|
||||
accountid: accountId,
|
||||
quantity: item.quantity,
|
||||
state: 'none',
|
||||
timestamp: item.timestamp,
|
||||
};
|
||||
}
|
||||
|
||||
export function deltaToInventoryJson(deltas: readonly ExchangeItemDelta[], accountId: string): InventoryItemJson[] {
|
||||
return deltas.map((d) => ({
|
||||
itemid: d.itemId,
|
||||
itemdef: d.itemDefId,
|
||||
accountid: accountId,
|
||||
quantity: d.quantity,
|
||||
state: 'none',
|
||||
timestamp: d.timestamp,
|
||||
}));
|
||||
}
|
||||
|
||||
export function parseExchangeItemsRequest(rawText: string): ParsedExchangeRequest | undefined {
|
||||
let parsed: Record<string, unknown>;
|
||||
try {
|
||||
const raw = JSON.parse(rawText) as Record<string, unknown>;
|
||||
parsed = typeof raw.data === 'object' && raw.data !== null ? (raw.data as Record<string, unknown>) : raw;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
const outputItemDefId = Number(parsed.outputitemdefid ?? 0);
|
||||
const quantity = Number(parsed.quantity ?? 1);
|
||||
if (!Number.isSafeInteger(outputItemDefId) || !Number.isSafeInteger(quantity)) return undefined;
|
||||
const rawMaterials = Array.isArray(parsed.materials) ? parsed.materials : [];
|
||||
const materials: ExchangeMaterialInput[] = rawMaterials.flatMap((m) => {
|
||||
if (Array.isArray(m) && m.length === 2) {
|
||||
const [itemId, count] = m;
|
||||
return [{
|
||||
itemid: typeof itemId === 'string' ? itemId : '',
|
||||
quantity: typeof count === 'number' ? count : 0,
|
||||
}];
|
||||
}
|
||||
if (typeof m !== 'object' || m === null) return [];
|
||||
const rec = m as Record<string, unknown>;
|
||||
return [{
|
||||
itemid: String(rec.itemid ?? ''),
|
||||
itemdefid: Number(rec.itemdefid ?? 0),
|
||||
quantity: Number(rec.quantity ?? 0),
|
||||
}];
|
||||
});
|
||||
return { outputItemDefId, quantity, materials };
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
/**
|
||||
* Lookup catalogue assembling generated external inventory item definitions (`GetItemDefsClient`),
|
||||
* item shop prices (`GetItemPrices`), generator drop tables (`GetItemDefChances` & `ExchangeItems`),
|
||||
* and GJN marketplace listings from category-specific builders.
|
||||
*/
|
||||
import type { ExternalItemSources } from '../game-data/datasets/external-item-sources.ts';
|
||||
import type { ItemDefinition } from '../game-data/datasets/item-catalogue.ts';
|
||||
import type { LocalizedText } from '../game-data/datasets/unit-names.ts';
|
||||
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
|
||||
import { buildSupplyChests } from './chest-defs.ts';
|
||||
import type { MarketplaceTuning } from './marketplace-tuning.ts';
|
||||
import type { RecyclingTuning } from './recycling-tuning.ts';
|
||||
import type { SupplyChestTuning } from './supply-chest-tuning.ts';
|
||||
import { buildCosmeticCoupons } from './coupons/cosmetic-coupons.ts';
|
||||
import { buildVehicleCoupons } from './coupons/vehicle-coupons.ts';
|
||||
import {
|
||||
DEFAULT_ITEMDEF_TIMESTAMP,
|
||||
type CouponAction,
|
||||
type ExternalItemPrice,
|
||||
type GeneratorDefinition,
|
||||
type GeneratorRecipe,
|
||||
type ItemDefRecord,
|
||||
type LocalizedItemDef,
|
||||
type MarketplaceListing,
|
||||
} from './itemdef-types.ts';
|
||||
import { buildRecyclingDefs } from './recycling-defs.ts';
|
||||
|
||||
export type { ExternalItemPrice, GeneratorDefinition, GeneratorRecipe };
|
||||
|
||||
/** The tuning the external inventory is generated with. */
|
||||
export interface InventoryTuning {
|
||||
readonly marketplace: MarketplaceTuning;
|
||||
readonly supplyChests: SupplyChestTuning;
|
||||
readonly recycling: RecyclingTuning;
|
||||
}
|
||||
|
||||
export class InventoryCatalogue {
|
||||
readonly #defs = new Map<number, LocalizedItemDef>();
|
||||
readonly #coupons = new Map<number, CouponAction>();
|
||||
readonly #prices = new Map<number, ExternalItemPrice>();
|
||||
readonly #generators = new Map<number, GeneratorDefinition>();
|
||||
readonly #marketListings: MarketplaceListing[] = [];
|
||||
readonly #marketById = new Map<number, MarketplaceListing>();
|
||||
|
||||
constructor(
|
||||
vehicles: readonly CatalogueVehicle[],
|
||||
unitNames: Readonly<Record<string, LocalizedText>>,
|
||||
sources: ExternalItemSources,
|
||||
classicItems: readonly ItemDefinition[],
|
||||
tuning: InventoryTuning,
|
||||
) {
|
||||
const vehicleCoupons = buildVehicleCoupons(vehicles, unitNames, tuning.marketplace);
|
||||
const cosmeticCoupons = buildCosmeticCoupons(sources, tuning.marketplace);
|
||||
const recycling = buildRecyclingDefs(classicItems, tuning.recycling);
|
||||
const chests = buildSupplyChests({
|
||||
wrappersByPart: recycling.wrappersByPart,
|
||||
skinCouponIds: cosmeticCoupons.skinCouponIds,
|
||||
decalCouponIds: cosmeticCoupons.decalCouponIds,
|
||||
attachableCouponIds: cosmeticCoupons.attachableCouponIds,
|
||||
sortedMarketVehicles: vehicleCoupons.sortedVehicles,
|
||||
}, tuning.supplyChests);
|
||||
|
||||
for (const def of [...vehicleCoupons.defs, ...cosmeticCoupons.defs, ...recycling.defs, ...chests.defs]) {
|
||||
this.#defs.set(def.itemdefId, def);
|
||||
}
|
||||
for (const stub of cosmeticCoupons.workshopStubs) {
|
||||
if (!this.#defs.has(stub.itemdefId)) this.#defs.set(stub.itemdefId, stub);
|
||||
}
|
||||
for (const [id, action] of [...vehicleCoupons.coupons, ...cosmeticCoupons.coupons, ...recycling.coupons]) {
|
||||
this.#coupons.set(id, action);
|
||||
}
|
||||
for (const price of chests.prices) {
|
||||
this.#prices.set(price.itemdefId, price);
|
||||
}
|
||||
for (const gen of [...recycling.generators, ...chests.generators]) {
|
||||
this.#generators.set(gen.itemdefId, gen);
|
||||
}
|
||||
for (const listing of [...vehicleCoupons.listings, ...cosmeticCoupons.listings]) {
|
||||
this.#marketListings.push(listing);
|
||||
this.#marketById.set(listing.itemdefId, listing);
|
||||
}
|
||||
}
|
||||
|
||||
itemDef(itemdefId: number, language = 'english'): ItemDefRecord {
|
||||
const entry = this.#defs.get(itemdefId);
|
||||
if (!entry) return fallbackItemDef(itemdefId);
|
||||
const useZh = isChineseLanguage(language);
|
||||
return {
|
||||
...entry.base,
|
||||
name: useZh ? entry.name.zh : entry.name.en,
|
||||
description: useZh ? entry.description.zh : entry.description.en,
|
||||
};
|
||||
}
|
||||
|
||||
itemDefs(ids: readonly number[], language = 'english'): ItemDefRecord[] {
|
||||
const unique = [...new Set(ids.filter((id) => Number.isSafeInteger(id) && id > 0))];
|
||||
return unique.map((id) => this.itemDef(id, language));
|
||||
}
|
||||
|
||||
couponAction(itemdefId: number): CouponAction | undefined {
|
||||
return this.#coupons.get(itemdefId);
|
||||
}
|
||||
|
||||
priceOf(itemdefId: number): ExternalItemPrice | undefined {
|
||||
return this.#prices.get(itemdefId);
|
||||
}
|
||||
|
||||
pricesForCurrency(currency: 'WTE' | 'WTS'): Array<{ readonly itemdefid: number; readonly price: number }> {
|
||||
const out: Array<{ readonly itemdefid: number; readonly price: number }> = [];
|
||||
for (const entry of this.#prices.values()) {
|
||||
const price = currency === 'WTE' ? entry.goldenEagles : entry.silverLions;
|
||||
if (price > 0) out.push({ itemdefid: entry.itemdefId, price });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
generator(generatorId: number): GeneratorDefinition | undefined {
|
||||
return this.#generators.get(generatorId);
|
||||
}
|
||||
|
||||
chancesForGenerator(generatorId: number): Array<{ readonly drop: number; readonly prob: number }> | undefined {
|
||||
const gen = this.#generators.get(generatorId);
|
||||
if (!gen || gen.drops.length === 0) return undefined;
|
||||
const total = gen.drops.reduce((sum, d) => sum + d.weight, 0);
|
||||
if (total <= 0) return undefined;
|
||||
return gen.drops.map((d) => ({ drop: d.itemdefId, prob: Number((d.weight / total).toFixed(6)) }));
|
||||
}
|
||||
|
||||
marketplaceListings(): readonly MarketplaceListing[] {
|
||||
return this.#marketListings;
|
||||
}
|
||||
|
||||
marketplaceListing(itemdefId: number): MarketplaceListing | undefined {
|
||||
return this.#marketById.get(itemdefId);
|
||||
}
|
||||
|
||||
hasItemDef(itemdefId: number): boolean {
|
||||
return this.#defs.has(itemdefId);
|
||||
}
|
||||
}
|
||||
|
||||
function isChineseLanguage(lang: string): boolean {
|
||||
const lower = lang.toLowerCase();
|
||||
return lower.includes('chinese') || lower.includes('zh');
|
||||
}
|
||||
|
||||
function fallbackItemDef(itemdefid: number): ItemDefRecord {
|
||||
return {
|
||||
itemdefid,
|
||||
type: 'item',
|
||||
Timestamp: DEFAULT_ITEMDEF_TIMESTAMP,
|
||||
marketable: false,
|
||||
exchange: '',
|
||||
used_to_create: '',
|
||||
market_hash_name: '',
|
||||
background_color: '',
|
||||
name_color: '',
|
||||
item_quality: 1,
|
||||
meta: '',
|
||||
tags: 'type:craft_part;devItem:yes;hideDesc:yes',
|
||||
icon_url: '!#ui/gameuiskin#item_type_craftpart.svg',
|
||||
icon_url_large: '!#ui/gameuiskin#item_type_craftpart.svg',
|
||||
bundle: '',
|
||||
name: `Item #${itemdefid}`,
|
||||
name_english: `Item #${itemdefid}`,
|
||||
description: '',
|
||||
description_english: '',
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* Types and shared definition builder for the external inventory service (`inventory-proxy`),
|
||||
* generated itemdefs, and the local GJN marketplace.
|
||||
*/
|
||||
import type { DecorKind } from '../game-data/datasets/decor-catalogue.ts';
|
||||
import type { LocalizedText } from '../game-data/datasets/unit-names.ts';
|
||||
|
||||
export const DEFAULT_ITEMDEF_TIMESTAMP = '2026-01-01T00:00:00Z';
|
||||
|
||||
export const QUALITY_COLORS: Readonly<Record<number, string>> = {
|
||||
1: '',
|
||||
2: '45aacc',
|
||||
3: '5599ff',
|
||||
4: 'aa66ff',
|
||||
5: 'dd8833',
|
||||
};
|
||||
|
||||
/** Exact schema validated by scripts/inventory/inventoryClient.nut `validateResponseData.item_json`. */
|
||||
export interface InventoryItemJson {
|
||||
readonly itemid: string;
|
||||
readonly itemdef: number;
|
||||
readonly accountid: string;
|
||||
readonly quantity: number;
|
||||
readonly state: string;
|
||||
readonly timestamp: string;
|
||||
}
|
||||
|
||||
/** Exact schema validated by scripts/inventory/inventoryClient.nut `validateResponseData.itemdef_json`. */
|
||||
export interface ItemDefRecord {
|
||||
readonly itemdefid: number;
|
||||
readonly type: 'item' | 'generator' | 'bundle' | 'delayedexchange';
|
||||
readonly Timestamp: string;
|
||||
readonly marketable: boolean;
|
||||
readonly exchange: string;
|
||||
readonly used_to_create: string;
|
||||
readonly market_hash_name: string;
|
||||
readonly background_color: string;
|
||||
readonly name_color: string;
|
||||
readonly item_quality: number;
|
||||
readonly meta: string;
|
||||
readonly tags: string;
|
||||
readonly icon_url: string;
|
||||
readonly icon_url_large: string;
|
||||
readonly bundle: string;
|
||||
readonly name: string;
|
||||
readonly name_english: string;
|
||||
readonly description: string;
|
||||
readonly description_english: string;
|
||||
}
|
||||
|
||||
export interface LocalizedItemDef {
|
||||
readonly itemdefId: number;
|
||||
readonly base: Omit<ItemDefRecord, 'name' | 'description'>;
|
||||
readonly name: LocalizedText;
|
||||
readonly description: LocalizedText;
|
||||
}
|
||||
|
||||
export type CouponAction =
|
||||
| { readonly kind: 'vehicle'; readonly unitName: string; readonly parts: readonly string[] }
|
||||
| { readonly kind: 'decor'; readonly decorKind: DecorKind; readonly resourceKey: string }
|
||||
| { readonly kind: 'unlock'; readonly unlockId: string }
|
||||
| { readonly kind: 'classic-item'; readonly itemName: string; readonly count: number };
|
||||
|
||||
export type MarketplaceCategory = 'vehicle' | 'skin' | 'decal' | 'attachable' | 'unlock';
|
||||
|
||||
export interface MarketplaceListing {
|
||||
readonly itemdefId: number;
|
||||
readonly marketHashName: string;
|
||||
readonly category: MarketplaceCategory;
|
||||
readonly gjnCostCents: number;
|
||||
readonly quality: number;
|
||||
readonly nameColor: string;
|
||||
readonly title: LocalizedText;
|
||||
readonly subtitle: LocalizedText;
|
||||
readonly country?: string;
|
||||
readonly unitClass?: string;
|
||||
readonly rank?: number;
|
||||
readonly targetKey: string;
|
||||
}
|
||||
|
||||
export interface GeneratorDrop {
|
||||
readonly itemdefId: number;
|
||||
readonly weight: number;
|
||||
}
|
||||
|
||||
export interface ExternalItemPrice {
|
||||
readonly itemdefId: number;
|
||||
readonly silverLions: number;
|
||||
readonly goldenEagles: number;
|
||||
}
|
||||
|
||||
export interface GeneratorRecipe {
|
||||
readonly components: ReadonlyArray<{ readonly itemdefId: number; readonly quantity: number }>;
|
||||
}
|
||||
|
||||
export interface GeneratorDefinition {
|
||||
readonly itemdefId: number;
|
||||
readonly isChestGenerator: boolean;
|
||||
readonly chestItemdefId?: number;
|
||||
readonly recipes: readonly GeneratorRecipe[];
|
||||
readonly drops: readonly GeneratorDrop[];
|
||||
}
|
||||
|
||||
export type PartialItemDefFields = Partial<
|
||||
Omit<ItemDefRecord, 'itemdefid' | 'name' | 'name_english' | 'description' | 'description_english'>
|
||||
> & {
|
||||
readonly type: ItemDefRecord['type'];
|
||||
readonly tags: string;
|
||||
readonly icon_url: string;
|
||||
};
|
||||
|
||||
export function makeLocalizedItemDef(
|
||||
itemdefId: number,
|
||||
partial: PartialItemDefFields,
|
||||
name: LocalizedText,
|
||||
description: LocalizedText,
|
||||
): LocalizedItemDef {
|
||||
return {
|
||||
itemdefId,
|
||||
base: {
|
||||
itemdefid: itemdefId,
|
||||
type: partial.type,
|
||||
Timestamp: partial.Timestamp ?? DEFAULT_ITEMDEF_TIMESTAMP,
|
||||
marketable: partial.marketable ?? false,
|
||||
exchange: partial.exchange ?? '',
|
||||
used_to_create: partial.used_to_create ?? '',
|
||||
market_hash_name: partial.market_hash_name ?? '',
|
||||
background_color: partial.background_color ?? '',
|
||||
name_color: partial.name_color ?? '',
|
||||
item_quality: partial.item_quality ?? 1,
|
||||
meta: partial.meta ?? '',
|
||||
tags: partial.tags,
|
||||
icon_url: partial.icon_url,
|
||||
icon_url_large: partial.icon_url_large ?? partial.icon_url,
|
||||
bundle: partial.bundle ?? '',
|
||||
name_english: name.en,
|
||||
description_english: description.en,
|
||||
},
|
||||
name,
|
||||
description,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Selling a coupon back to the system removes it from `extInventory` and credits the listing
|
||||
* price less the configured `sellFeeRate` as GJN. See tuning/marketplace.jsonc.
|
||||
*/
|
||||
import type { BlkBlock } from '@wto/blk';
|
||||
import { addGjnCents } from '../profile/profile-currency.ts';
|
||||
import { consumeExternalItem, externalInventoryItems } from '../profile/profile-external-inventory.ts';
|
||||
import type { InventoryCatalogue } from './itemdef-catalogue.ts';
|
||||
|
||||
export type MarketSellOutcome =
|
||||
| { readonly ok: true; readonly creditedCents: number }
|
||||
| { readonly ok: false; readonly reason: 'NOT_FOUND' | 'NOT_ENOUGH_ITEMS' };
|
||||
|
||||
/** GJN hundredths the player receives for one coupon of this price. */
|
||||
export function sellProceedsCents(priceCents: number, feeRate: number): number {
|
||||
return Math.floor(priceCents * (1 - feeRate));
|
||||
}
|
||||
|
||||
export function sellMarketplaceCoupon(
|
||||
profile: BlkBlock,
|
||||
catalogue: InventoryCatalogue,
|
||||
itemdefId: number,
|
||||
quantity: number,
|
||||
feeRate: number,
|
||||
): MarketSellOutcome {
|
||||
const listing = catalogue.marketplaceListing(itemdefId);
|
||||
if (!listing || !Number.isSafeInteger(quantity) || quantity < 1) return { ok: false, reason: 'NOT_FOUND' };
|
||||
const stacks = externalInventoryItems(profile).filter((item) => item.itemDefId === itemdefId);
|
||||
if (stacks.reduce((sum, item) => sum + item.quantity, 0) < quantity) return { ok: false, reason: 'NOT_ENOUGH_ITEMS' };
|
||||
|
||||
let remaining = quantity;
|
||||
for (const stack of stacks) {
|
||||
if (remaining === 0) break;
|
||||
const take = Math.min(stack.quantity, remaining);
|
||||
if (!consumeExternalItem(profile, stack.itemId, take)) return { ok: false, reason: 'NOT_ENOUGH_ITEMS' };
|
||||
remaining -= take;
|
||||
}
|
||||
const credited = sellProceedsCents(listing.gjnCostCents, feeRate) * quantity;
|
||||
addGjnCents(profile, credited);
|
||||
return { ok: true, creditedCents: credited };
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
/**
|
||||
* Local GJN Marketplace web service (`/trade.gaijin.net` and `trade.gaijin.net` host;
|
||||
* implementation notes). Lets players browse and buy all 466 stock marketplace coupons
|
||||
* (vehicles, skins, decals, attachables, pilot/unlocks) with GJN, depositing coupons into
|
||||
* `extInventory` and pushing `mrpc.generic_notify` (`inventory.changed`) to active game clients.
|
||||
*/
|
||||
import { gjnText } from '../store/redeem-codes.ts';
|
||||
import type { BlkBlock } from '@wto/blk';
|
||||
import type { AccountStore } from '../accounts/account-store.ts';
|
||||
import type { PlayerProfiles } from '../profile/player-profiles.ts';
|
||||
import { balanceOf } from '../profile/profile-currency.ts';
|
||||
import { externalInventoryItems } from '../profile/profile-external-inventory.ts';
|
||||
import { ownsVehicle } from '../profile/profile-hangar.ts';
|
||||
import { ownsResource } from '../profile/profile-resources.ts';
|
||||
import { earnedUnlocks } from '../profile/profile-unlocks.ts';
|
||||
import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts';
|
||||
import {
|
||||
createStaticWebSite,
|
||||
jsonResponse,
|
||||
parseJsonBody,
|
||||
requireWebActionAccount,
|
||||
selectWebViewAccount,
|
||||
} from '../web-ui/web-helpers.ts';
|
||||
import { buyFreeMarketplaceCoupon, buyMarketplaceCoupon } from './inventory-rules.ts';
|
||||
import type { InventoryCatalogue } from './itemdef-catalogue.ts';
|
||||
import type { MarketplaceListing } from './itemdef-types.ts';
|
||||
import { sellMarketplaceCoupon, sellProceedsCents, type MarketSellOutcome } from './marketplace-sell.ts';
|
||||
import type { MarketplaceTuning } from './marketplace-tuning.ts';
|
||||
|
||||
const MARKET_WEB = createStaticWebSite(new URL('./web/', import.meta.url));
|
||||
|
||||
export class MarketplaceService implements Service {
|
||||
readonly name = 'marketplace';
|
||||
readonly #accounts: AccountStore;
|
||||
readonly #profiles: PlayerProfiles;
|
||||
readonly #catalogue: InventoryCatalogue;
|
||||
readonly #notifyInventoryChanged: () => void;
|
||||
readonly #maxPerPurchase: number;
|
||||
readonly #sellFeeRate: number;
|
||||
|
||||
constructor(
|
||||
accounts: AccountStore,
|
||||
profiles: PlayerProfiles,
|
||||
catalogue: InventoryCatalogue,
|
||||
notifyInventoryChanged: () => void,
|
||||
tuning: Pick<MarketplaceTuning, 'maxPerPurchase' | 'sellFeeRate'>,
|
||||
) {
|
||||
this.#accounts = accounts;
|
||||
this.#profiles = profiles;
|
||||
this.#catalogue = catalogue;
|
||||
this.#notifyInventoryChanged = notifyInventoryChanged;
|
||||
this.#maxPerPurchase = tuning.maxPerPurchase;
|
||||
this.#sellFeeRate = tuning.sellFeeRate;
|
||||
}
|
||||
|
||||
accepts(request: ServiceRequest): boolean {
|
||||
return request.originalHost === 'trade.gaijin.net'
|
||||
|| request.path === '/trade.gaijin.net'
|
||||
|| request.path.startsWith('/trade.gaijin.net/');
|
||||
}
|
||||
|
||||
handle(request: ServiceRequest): ServiceResponse {
|
||||
const subPath = request.path.startsWith('/trade.gaijin.net')
|
||||
? (request.path.slice('/trade.gaijin.net'.length) || '/')
|
||||
: request.path;
|
||||
|
||||
if (subPath === '/api/state' && request.method === 'GET') return this.#state(request);
|
||||
if (subPath === '/api/buy' && request.method === 'POST') return this.#buy(request);
|
||||
if (subPath === '/api/sell' && request.method === 'POST') return this.#sell(request);
|
||||
|
||||
return MARKET_WEB.serve(subPath, `marketplace web (${request.query.get('n') ?? 'index'})`)
|
||||
?? { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' }, body: 'Not found', logNotes: { summary: `marketplace 404: ${subPath}` } };
|
||||
}
|
||||
|
||||
#state(request: ServiceRequest): ServiceResponse {
|
||||
const account = selectWebViewAccount(this.#accounts, request.query.get('userId'));
|
||||
const profile = account ? this.#profiles.profileOf(account.userId) : undefined;
|
||||
const balance = profile ? balanceOf(profile) : { silverLions: 0, goldenEagles: 0, gjnCents: 0 };
|
||||
|
||||
const heldCounts = new Map<number, number>();
|
||||
if (profile) {
|
||||
for (const item of externalInventoryItems(profile)) {
|
||||
heldCounts.set(item.itemDefId, (heldCounts.get(item.itemDefId) ?? 0) + item.quantity);
|
||||
}
|
||||
}
|
||||
const unlockedSet = profile ? earnedUnlocks(profile) : new Set<string>();
|
||||
|
||||
const listings = this.#catalogue.marketplaceListings().map((listing) => ({
|
||||
...listing,
|
||||
sellCents: sellProceedsCents(listing.gjnCostCents, this.#sellFeeRate),
|
||||
couponCount: heldCounts.get(listing.itemdefId) ?? 0,
|
||||
alreadyActivated: profile ? isListingAlreadyActivated(profile, listing, unlockedSet) : false,
|
||||
}));
|
||||
|
||||
return jsonResponse({
|
||||
accounts: this.#accounts.all().map((a) => ({ userId: a.userId, login: a.login, nick: a.nick })),
|
||||
currentUserId: account?.userId ?? '',
|
||||
balance,
|
||||
sellFeeRate: this.#sellFeeRate,
|
||||
listings,
|
||||
}, `marketplace state (${account?.userId ?? 'no-account'})`);
|
||||
}
|
||||
|
||||
#sell(request: ServiceRequest): ServiceResponse {
|
||||
const body = parseJsonBody(request.body);
|
||||
const account = requireWebActionAccount(this.#accounts, body.userId);
|
||||
if (!account) {
|
||||
return jsonResponse({ ok: false, message: { zh: '没有找到这个账号,请先在右上角选择账号。', en: 'Account not found. Pick an account at the top right first.' } }, 'marketplace sell: unknown account');
|
||||
}
|
||||
const itemdefId = Number(body.itemdefId ?? 0);
|
||||
const quantity = body.quantity === undefined ? 1 : Number(body.quantity);
|
||||
let outcome: MarketSellOutcome = { ok: false, reason: 'NOT_FOUND' };
|
||||
this.#profiles.updateWhen(account.userId, (saved) => {
|
||||
outcome = sellMarketplaceCoupon(saved, this.#catalogue, itemdefId, quantity, this.#sellFeeRate);
|
||||
return outcome.ok;
|
||||
});
|
||||
const result = outcome as MarketSellOutcome;
|
||||
if (!result.ok) {
|
||||
return jsonResponse({ ok: false, message: { zh: '库存里没有足够的这张兑换券。', en: 'Not enough of this coupon in your inventory.' } }, `marketplace sell ${itemdefId}: ${result.reason}`);
|
||||
}
|
||||
this.#notifyInventoryChanged();
|
||||
const amount = gjnText(result.creditedCents);
|
||||
return jsonResponse({
|
||||
ok: true,
|
||||
message: { zh: `已卖给系统 ×${quantity},到账 ${amount} GJN(已扣 ${Math.round(this.#sellFeeRate * 100)}% 手续费)。`, en: `Sold ${quantity} to the system for ${amount} GJN (after the ${Math.round(this.#sellFeeRate * 100)}% fee).` },
|
||||
}, `marketplace sell ${itemdefId} x${quantity} (+${amount} GJN)`);
|
||||
}
|
||||
|
||||
#buy(request: ServiceRequest): ServiceResponse {
|
||||
const body = parseJsonBody(request.body);
|
||||
const account = requireWebActionAccount(this.#accounts, body.userId);
|
||||
if (!account) {
|
||||
return jsonResponse({ ok: false, message: { zh: '没有找到这个账号,请先在右上角选择账号。', en: 'Account not found. Pick an account at the top right first.' } }, 'marketplace buy: unknown account');
|
||||
}
|
||||
|
||||
const itemdefId = Number(body.itemdefId ?? 0);
|
||||
const rawQuantity = body.quantity === undefined ? 1 : Number(body.quantity);
|
||||
if (!Number.isSafeInteger(itemdefId) || itemdefId <= 0 || !Number.isSafeInteger(rawQuantity) || rawQuantity < 1 || rawQuantity > this.#maxPerPurchase) {
|
||||
return jsonResponse({ ok: false, message: { zh: `请求无效:每次购买 1~${this.#maxPerPurchase} 张。`, en: `Invalid request: buy 1 to ${this.#maxPerPurchase} coupons at a time.` } }, 'marketplace buy: bad params');
|
||||
}
|
||||
if (body.payMethod !== undefined && body.payMethod !== 'gjn' && body.payMethod !== 'free') {
|
||||
return jsonResponse({ ok: false, message: { zh: '不支持这种支付方式。', en: 'Unsupported payment method.' } }, 'marketplace buy: bad payMethod');
|
||||
}
|
||||
const isFree = body.payMethod === 'free';
|
||||
const quantity = rawQuantity;
|
||||
const listing = this.#catalogue.marketplaceListing(itemdefId);
|
||||
if (!listing) return jsonResponse({ ok: false, message: { zh: '没有找到这张兑换券。', en: 'Coupon not found.' } }, `marketplace buy: unknown ${itemdefId}`);
|
||||
|
||||
let errorReason: 'NOT_FOUND' | 'NOT_ENOUGH_GJN' | undefined;
|
||||
this.#profiles.updateWhen(account.userId, (saved) => {
|
||||
const res = isFree
|
||||
? buyFreeMarketplaceCoupon(saved, this.#catalogue, itemdefId, quantity, this.#maxPerPurchase)
|
||||
: buyMarketplaceCoupon(saved, this.#catalogue, itemdefId, quantity, this.#maxPerPurchase);
|
||||
if (!res.ok) {
|
||||
errorReason = res.reason;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
if (errorReason === 'NOT_ENOUGH_GJN') {
|
||||
return jsonResponse({ ok: false, message: { zh: 'GJN 不够。可直接点「老福爷付过了」,或在商店的"兑换码"页用 GJN 充值码补充。', en: 'Not enough GJN. Use "老福爷付过了" or a GJN code on the Redeem tab of the store.' } }, `marketplace buy ${itemdefId}: NOMONEY`);
|
||||
}
|
||||
if (errorReason) {
|
||||
return jsonResponse({ ok: false, message: { zh: '购买失败。', en: 'Purchase failed.' } }, `marketplace buy ${itemdefId}: ${errorReason}`);
|
||||
}
|
||||
|
||||
this.#notifyInventoryChanged();
|
||||
const costSummary = isFree ? 'free' : `${gjnText(listing.gjnCostCents * quantity)} GJN`;
|
||||
return jsonResponse({ ok: true, message: buySuccessMessage(listing, quantity, isFree) }, `marketplace buy ${itemdefId} x${quantity} (${costSummary})`);
|
||||
}
|
||||
}
|
||||
|
||||
function buySuccessMessage(listing: MarketplaceListing, quantity: number, isFree: boolean): { zh: string; en: string } {
|
||||
return isFree
|
||||
? {
|
||||
zh: `老福爷付过了!「${listing.title.zh}」兑换券 ×${quantity} 已放进游戏库存,可在机库的"道具 → 库存"里使用。`,
|
||||
en: `Paid by 老福爷! ${quantity} × "${listing.title.en}" coupon is in your inventory (Items → Inventory in the hangar).`,
|
||||
}
|
||||
: {
|
||||
zh: `已购买「${listing.title.zh}」兑换券 ×${quantity},已放进游戏库存,可在机库的"道具 → 库存"里使用。`,
|
||||
en: `Bought ${quantity} × "${listing.title.en}" coupon. It is in your inventory (Items → Inventory in the hangar).`,
|
||||
};
|
||||
}
|
||||
|
||||
function isListingAlreadyActivated(profile: BlkBlock, listing: MarketplaceListing, unlockedSet: ReadonlySet<string>): boolean {
|
||||
switch (listing.category) {
|
||||
case 'vehicle':
|
||||
return ownsVehicle(profile, listing.targetKey);
|
||||
case 'skin':
|
||||
case 'decal':
|
||||
case 'attachable':
|
||||
return ownsResource(profile, listing.targetKey);
|
||||
case 'unlock':
|
||||
return unlockedSet.has(listing.targetKey);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/** Typed content of tuning/marketplace.jsonc. */
|
||||
import { TuningError, type TuningReader } from '../tuning/tuning-reader.ts';
|
||||
|
||||
export type CosmeticCouponKind = 'skin' | 'decal' | 'attachable' | 'unlock';
|
||||
|
||||
export interface CouponPrice {
|
||||
readonly gjnCents: number;
|
||||
readonly quality: number;
|
||||
}
|
||||
|
||||
interface RankTier<T> {
|
||||
readonly upToRank: number;
|
||||
readonly value: T;
|
||||
}
|
||||
|
||||
export interface MarketplaceTuning {
|
||||
readonly maxPerPurchase: number;
|
||||
/** Fraction kept by the system when a player sells a coupon back (0.15 = 15 %). */
|
||||
readonly sellFeeRate: number;
|
||||
readonly vehiclePriceByVehicle: ReadonlyMap<string, number>;
|
||||
readonly vehiclePriceByRank: readonly RankTier<number>[];
|
||||
readonly vehicleQualityByRank: readonly RankTier<number>[];
|
||||
readonly cosmeticCoupons: Readonly<Record<CosmeticCouponKind, CouponPrice>>;
|
||||
/** Per-resource GJN-hundredths overrides for decor / unlock coupons (official market snapshot). */
|
||||
readonly cosmeticPriceByResource: ReadonlyMap<string, number>;
|
||||
}
|
||||
|
||||
const COSMETIC_KINDS: readonly CosmeticCouponKind[] = ['skin', 'decal', 'attachable', 'unlock'];
|
||||
|
||||
export function readMarketplaceTuning(file: TuningReader): MarketplaceTuning {
|
||||
const vehicles = file.object('vehicleCoupons');
|
||||
const prices = vehicles.object('byVehicle');
|
||||
const cosmetic = file.object('cosmeticCoupons');
|
||||
const byResource = cosmetic.object('byResource');
|
||||
return {
|
||||
maxPerPurchase: file.int('maxPerPurchase', { min: 1 }),
|
||||
sellFeeRate: file.number('sellFeeRate', { min: 0, max: 0.99 }),
|
||||
vehiclePriceByVehicle: new Map(prices.keys().map((name) => [name, prices.money(name, { min: 0.01 })])),
|
||||
vehiclePriceByRank: rankTiers(vehicles, 'byRank', (entry) => entry.money('gjn', { min: 0.01 })),
|
||||
vehicleQualityByRank: rankTiers(vehicles, 'qualityByRank', (entry) => entry.int('quality', { min: 1, max: 5 })),
|
||||
cosmeticCoupons: Object.fromEntries(COSMETIC_KINDS.map((kind) => {
|
||||
const entry = cosmetic.object(kind);
|
||||
return [kind, { gjnCents: entry.money('gjn', { min: 0.01 }), quality: entry.int('quality', { min: 1, max: 5 }) }];
|
||||
})) as Record<CosmeticCouponKind, CouponPrice>,
|
||||
cosmeticPriceByResource: new Map(byResource.keys().map((key) => [key, byResource.money(key, { min: 0.01 })])),
|
||||
};
|
||||
}
|
||||
|
||||
/** A decor / unlock coupon's price: the per-resource snapshot price, else the kind's default. */
|
||||
export function cosmeticCouponPrice(tuning: MarketplaceTuning, kind: CosmeticCouponKind, resource: string): CouponPrice {
|
||||
const base = tuning.cosmeticCoupons[kind];
|
||||
return { gjnCents: tuning.cosmeticPriceByResource.get(resource) ?? base.gjnCents, quality: base.quality };
|
||||
}
|
||||
|
||||
/** A vehicle coupon's price in GJN hundredths and its quality. */
|
||||
export function vehicleCouponPrice(tuning: MarketplaceTuning, vehicle: string, rank: number): CouponPrice {
|
||||
return {
|
||||
gjnCents: tuning.vehiclePriceByVehicle.get(vehicle) ?? forRank(tuning.vehiclePriceByRank, rank),
|
||||
quality: forRank(tuning.vehicleQualityByRank, rank),
|
||||
};
|
||||
}
|
||||
|
||||
function rankTiers<T>(file: TuningReader, key: string, read: (entry: TuningReader) => T): RankTier<T>[] {
|
||||
const tiers = file.list(key, (entry) => ({ upToRank: entry.int('upToRank', { min: 1 }), value: read(entry) })).sort((a, b) => a.upToRank - b.upToRank);
|
||||
if (tiers.length === 0) throw new TuningError(`tuning file marketplace.jsonc: vehicleCoupons.${key} must have at least one tier`);
|
||||
return tiers;
|
||||
}
|
||||
|
||||
/** The first tier whose upToRank covers the rank; the last tier above the highest. */
|
||||
function forRank<T>(tiers: readonly RankTier<T>[], rank: number): T {
|
||||
return (tiers.find((tier) => rank <= tier.upToRank) ?? tiers[tiers.length - 1]!).value;
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
/**
|
||||
* Classic-item `autoConsume` wrappers (`810001+`), recycled craft fragments and re-synthesis
|
||||
* generators. The fragments are the distinct recycleItemResult
|
||||
* values of config/items.blk; the recipes are tuning (tuning/recycling.jsonc).
|
||||
*/
|
||||
import type { ItemDefinition } from '../game-data/datasets/item-catalogue.ts';
|
||||
import {
|
||||
makeLocalizedItemDef,
|
||||
type CouponAction,
|
||||
type GeneratorDefinition,
|
||||
type GeneratorDrop,
|
||||
type GeneratorRecipe,
|
||||
type LocalizedItemDef,
|
||||
} from './itemdef-types.ts';
|
||||
import type { RecyclingTuning } from './recycling-tuning.ts';
|
||||
|
||||
const RECYCLE_SINGLE_OFFSET = 20;
|
||||
const RECYCLE_GENERIC_GENERATOR_ID = 299030;
|
||||
const FIRST_WRAPPER_ID = 810001;
|
||||
|
||||
export interface RecyclingBuildResult {
|
||||
readonly defs: readonly LocalizedItemDef[];
|
||||
readonly coupons: ReadonlyArray<readonly [number, CouponAction]>;
|
||||
readonly generators: readonly GeneratorDefinition[];
|
||||
readonly wrappersByPart: ReadonlyMap<number, readonly number[]>;
|
||||
}
|
||||
|
||||
export function buildRecyclingDefs(classicItems: readonly ItemDefinition[], tuning: RecyclingTuning): RecyclingBuildResult {
|
||||
const defs: LocalizedItemDef[] = [];
|
||||
const coupons: Array<readonly [number, CouponAction]> = [];
|
||||
const generators: GeneratorDefinition[] = [];
|
||||
|
||||
const partIds = [...new Set(classicItems.flatMap((item) => (item.recycleItemResult === undefined ? [] : [item.recycleItemResult])))].sort((a, b) => a - b);
|
||||
const wrappersByPart = buildClassicWrappers(classicItems, partIds, tuning, defs, coupons);
|
||||
const allWrappers = [...new Set([...wrappersByPart.values()].flat())];
|
||||
for (const partId of partIds) {
|
||||
registerSinglePartSynthesizer(partId, wrappersByPart.get(partId) ?? allWrappers, tuning, defs, generators);
|
||||
}
|
||||
registerMixedSynthesizer(partIds, allWrappers, defs, generators);
|
||||
return { defs, coupons, generators, wrappersByPart };
|
||||
}
|
||||
|
||||
function registerSinglePartSynthesizer(
|
||||
partId: number,
|
||||
pool: readonly number[],
|
||||
tuning: RecyclingTuning,
|
||||
defs: LocalizedItemDef[],
|
||||
generators: GeneratorDefinition[],
|
||||
): void {
|
||||
const singleGenId = partId + RECYCLE_SINGLE_OFFSET;
|
||||
const title = tuning.partNames.get(partId) ?? { en: `Recycled Part #${partId}`, zh: `回收组件 #${partId}` };
|
||||
const needed = tuning.partsPerItem;
|
||||
defs.push(makeLocalizedItemDef(partId, {
|
||||
type: 'item',
|
||||
marketable: false,
|
||||
item_quality: 1,
|
||||
used_to_create: `${singleGenId}x1;${RECYCLE_GENERIC_GENERATOR_ID}x1`,
|
||||
tags: 'type:craft_part;hideMarketablePropDesc:yes',
|
||||
icon_url: '!#ui/gameuiskin#item_type_craftpart.svg',
|
||||
}, title, {
|
||||
en: `Obtained by recycling classic items; ${needed} fragments craft a new random item.`,
|
||||
zh: `回收经典道具所得;每 ${needed} 个组件可重新合成 1 件随机道具。`,
|
||||
}));
|
||||
defs.push(makeLocalizedItemDef(singleGenId, {
|
||||
type: 'generator',
|
||||
marketable: false,
|
||||
item_quality: 1,
|
||||
exchange: `${partId}x${needed}`,
|
||||
bundle: pool.map((id) => `${id}x1`).join(';'),
|
||||
tags: 'devItem:yes',
|
||||
icon_url: '!#ui/gameuiskin#item_type_craftpart.svg',
|
||||
}, { en: 'Item Synthesizer', zh: '道具合成器' }, { en: '', zh: '' }));
|
||||
generators.push({
|
||||
itemdefId: singleGenId,
|
||||
isChestGenerator: false,
|
||||
recipes: [{ components: [{ itemdefId: partId, quantity: needed }] }],
|
||||
drops: pool.map((id): GeneratorDrop => ({ itemdefId: id, weight: 10 })),
|
||||
});
|
||||
}
|
||||
|
||||
function registerMixedSynthesizer(
|
||||
partIds: readonly number[],
|
||||
allWrappers: readonly number[],
|
||||
defs: LocalizedItemDef[],
|
||||
generators: GeneratorDefinition[],
|
||||
): void {
|
||||
const { pairRecipes, pairStrings } = buildPairRecipes(partIds);
|
||||
defs.push(makeLocalizedItemDef(RECYCLE_GENERIC_GENERATOR_ID, {
|
||||
type: 'generator',
|
||||
marketable: false,
|
||||
item_quality: 1,
|
||||
exchange: pairStrings.join(';'),
|
||||
bundle: allWrappers.map((id) => `${id}x1`).join(';'),
|
||||
tags: 'devItem:yes',
|
||||
icon_url: '!#ui/gameuiskin#item_type_craftpart.svg',
|
||||
}, { en: 'Mixed Item Synthesizer', zh: '混搭道具合成器' }, { en: '', zh: '' }));
|
||||
generators.push({
|
||||
itemdefId: RECYCLE_GENERIC_GENERATOR_ID,
|
||||
isChestGenerator: false,
|
||||
recipes: pairRecipes,
|
||||
drops: allWrappers.map((id): GeneratorDrop => ({ itemdefId: id, weight: 10 })),
|
||||
});
|
||||
}
|
||||
|
||||
function buildClassicWrappers(
|
||||
classicItems: readonly ItemDefinition[],
|
||||
partIds: readonly number[],
|
||||
tuning: RecyclingTuning,
|
||||
defs: LocalizedItemDef[],
|
||||
coupons: Array<readonly [number, CouponAction]>,
|
||||
): ReadonlyMap<number, readonly number[]> {
|
||||
const byRecyclePart = new Map<number, number[]>();
|
||||
for (const partId of partIds) byRecyclePart.set(partId, []);
|
||||
|
||||
// Sort deterministically by item id so wrapper IDs and drop pools do not depend on BLK order.
|
||||
const sortedPermanent = classicItems
|
||||
.filter((item) => item.expiresAt === undefined && item.type !== 'personalDiscounts')
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
|
||||
const preferredByPart = new Map<number, ItemDefinition[]>();
|
||||
for (const item of sortedPermanent) {
|
||||
const partId = item.recycleItemResult;
|
||||
if (partId === undefined) continue;
|
||||
let bucket = preferredByPart.get(partId);
|
||||
if (!bucket) preferredByPart.set(partId, bucket = []);
|
||||
if (bucket.length < tuning.itemsPerPart) bucket.push(item);
|
||||
}
|
||||
|
||||
let nextWrapperId = FIRST_WRAPPER_ID;
|
||||
for (const partId of partIds) {
|
||||
const targetList = byRecyclePart.get(partId) ?? [];
|
||||
for (const def of preferredByPart.get(partId) ?? []) {
|
||||
const wrapperId = nextWrapperId++;
|
||||
const count = tuning.piecesPerItem.get(def.name) ?? 1;
|
||||
defs.push(makeLocalizedItemDef(wrapperId, {
|
||||
type: 'item',
|
||||
marketable: false,
|
||||
item_quality: 1,
|
||||
tags: 'type:internal_item;autoConsume:yes;showAsContentItem:yes;hideMarketablePropDesc:yes',
|
||||
meta: `item:t="${def.name}"\ncount:i=${count}`,
|
||||
icon_url: '!#ui/gameuiskin#item_type_trophies.svg',
|
||||
}, { en: def.name, zh: def.name }, { en: '', zh: '' }));
|
||||
coupons.push([wrapperId, { kind: 'classic-item', itemName: def.name, count }]);
|
||||
targetList.push(wrapperId);
|
||||
}
|
||||
byRecyclePart.set(partId, targetList);
|
||||
}
|
||||
|
||||
const fallbackPool = tuning.fallbackParts.flatMap((partId) => byRecyclePart.get(partId) ?? []);
|
||||
for (const partId of partIds) {
|
||||
if ((byRecyclePart.get(partId)?.length ?? 0) === 0) byRecyclePart.set(partId, fallbackPool);
|
||||
}
|
||||
return byRecyclePart;
|
||||
}
|
||||
|
||||
function buildPairRecipes(partIds: readonly number[]): { readonly pairRecipes: readonly GeneratorRecipe[]; readonly pairStrings: readonly string[] } {
|
||||
const pairRecipes: GeneratorRecipe[] = [];
|
||||
const pairStrings: string[] = [];
|
||||
for (let i = 0; i < partIds.length; i += 1) {
|
||||
for (let j = i + 1; j < partIds.length; j += 1) {
|
||||
const a = partIds[i]!;
|
||||
const b = partIds[j]!;
|
||||
pairRecipes.push({ components: [{ itemdefId: a, quantity: 1 }, { itemdefId: b, quantity: 1 }] });
|
||||
pairStrings.push(`${a}x1,${b}x1`);
|
||||
}
|
||||
}
|
||||
return { pairRecipes, pairStrings };
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/** Typed content of tuning/recycling.jsonc. */
|
||||
import type { LocalizedText } from '../game-data/datasets/unit-names.ts';
|
||||
import { TuningError, type TuningReader } from '../tuning/tuning-reader.ts';
|
||||
|
||||
export interface RecyclingTuning {
|
||||
readonly partNames: ReadonlyMap<number, LocalizedText>;
|
||||
readonly partsPerItem: number;
|
||||
readonly itemsPerPart: number;
|
||||
readonly piecesPerItem: ReadonlyMap<string, number>;
|
||||
readonly fallbackParts: readonly number[];
|
||||
}
|
||||
|
||||
export function readRecyclingTuning(file: TuningReader): RecyclingTuning {
|
||||
const pieces = file.object('piecesPerItem');
|
||||
const names = file.table('partNames', (entry) => ({ zh: entry.string('zh'), en: entry.string('en') }));
|
||||
return {
|
||||
partNames: new Map([...names].map(([id, name]) => [partId(id), name])),
|
||||
partsPerItem: file.int('partsPerItem', { min: 1 }),
|
||||
itemsPerPart: file.int('itemsPerPart', { min: 1 }),
|
||||
piecesPerItem: new Map(pieces.keys().map((item) => [item, pieces.int(item, { min: 1 })])),
|
||||
fallbackParts: file.intList('fallbackParts', { min: 1 }),
|
||||
};
|
||||
}
|
||||
|
||||
function partId(text: string): number {
|
||||
const id = Number(text);
|
||||
if (!Number.isSafeInteger(id) || id <= 0) throw new TuningError(`tuning file recycling.jsonc: partNames key "${text}" must be a part number`);
|
||||
return id;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
/** Typed content of tuning/supply-chests.jsonc. */
|
||||
import type { LocalizedText } from '../game-data/datasets/unit-names.ts';
|
||||
import { TuningError, type TuningReader } from '../tuning/tuning-reader.ts';
|
||||
|
||||
export type ChestPrizeSpec =
|
||||
| { readonly kind: 'classicItems'; readonly recyclePart: number; readonly pick: number; readonly weightEach: number }
|
||||
| { readonly kind: 'coupons'; readonly couponKind: 'skin' | 'decal' | 'attachable'; readonly skip: number; readonly pick: number; readonly weightEach: number }
|
||||
| { readonly kind: 'marketVehicles'; readonly minRank: number; readonly maxRank: number; readonly pick: number; readonly weightEach: number };
|
||||
|
||||
export interface SupplyChestSpec {
|
||||
readonly id: number;
|
||||
readonly openerId: number;
|
||||
readonly silverLions: number;
|
||||
readonly quality: number;
|
||||
readonly icon: string;
|
||||
readonly title: LocalizedText;
|
||||
readonly description: LocalizedText;
|
||||
readonly prizes: readonly ChestPrizeSpec[];
|
||||
}
|
||||
|
||||
export interface SupplyChestTuning {
|
||||
readonly maxPerPurchase: number;
|
||||
readonly chests: readonly SupplyChestSpec[];
|
||||
}
|
||||
|
||||
const COUPON_KINDS = ['skin', 'decal', 'attachable'] as const;
|
||||
|
||||
export function readSupplyChestTuning(file: TuningReader): SupplyChestTuning {
|
||||
return {
|
||||
maxPerPurchase: file.int('maxPerPurchase', { min: 1 }),
|
||||
chests: file.list('chests', (entry) => ({
|
||||
id: entry.int('id', { min: 1 }),
|
||||
openerId: entry.int('openerId', { min: 1 }),
|
||||
silverLions: entry.int('silverLions', { min: 1 }),
|
||||
quality: entry.int('quality', { min: 1, max: 5 }),
|
||||
icon: entry.string('icon'),
|
||||
title: localized(entry.object('title')),
|
||||
description: localized(entry.object('description')),
|
||||
prizes: entry.list('prizes', readPrize),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function readPrize(entry: TuningReader): ChestPrizeSpec {
|
||||
const weightEach = entry.number('weightEach', { min: 0 });
|
||||
if (entry.has('classicItems')) {
|
||||
const group = entry.object('classicItems');
|
||||
return { kind: 'classicItems', recyclePart: group.int('recyclePart', { min: 1 }), pick: group.int('pick', { min: 1 }), weightEach };
|
||||
}
|
||||
if (entry.has('coupons')) {
|
||||
const group = entry.object('coupons');
|
||||
const couponKind = group.string('kind');
|
||||
if (!(COUPON_KINDS as readonly string[]).includes(couponKind)) throw new TuningError(`tuning file supply-chests.jsonc: coupons.kind must be one of ${COUPON_KINDS.join(', ')} (found "${couponKind}")`);
|
||||
return { kind: 'coupons', couponKind: couponKind as (typeof COUPON_KINDS)[number], skip: group.int('skip', { min: 0 }), pick: group.int('pick', { min: 1 }), weightEach };
|
||||
}
|
||||
if (entry.has('marketVehicles')) {
|
||||
const group = entry.object('marketVehicles');
|
||||
return { kind: 'marketVehicles', minRank: group.int('minRank', { min: 1 }), maxRank: group.int('maxRank', { min: 1 }), pick: group.int('pick', { min: 1 }), weightEach };
|
||||
}
|
||||
throw new TuningError(`tuning file supply-chests.jsonc: a prize needs one of classicItems, coupons, marketVehicles (found ${JSON.stringify(entry.keys())})`);
|
||||
}
|
||||
|
||||
function localized(entry: TuningReader): LocalizedText {
|
||||
return { zh: entry.string('zh'), en: entry.string('en') };
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
/**
|
||||
* Classic trophies (`cln_get_price_ex` top-level `trophy{}` + `Common/trophy/<id>` prices)
|
||||
* and `cln_buy_trophy` rules (implementation notes; scripts/items/itemsClasses/itemTrophy.nut):
|
||||
* 1. Silver-Lion supply chests with native drop-chance display (`showChances:b=yes`, calculated
|
||||
* by `calcTrophiesDropChance` at 0x1554dc0), using deterministic rank-and-country selection;
|
||||
* 2. Golden-Eagle direct-purchase prize-pool vehicles (`numTotal:i=1`, single `i{ unit:t }` prize,
|
||||
* disabled automatically by `isPrizeUnitBought()` once owned).
|
||||
*/
|
||||
import type { BlkBlock, BlkParam } from '@wto/blk';
|
||||
import type { ItemDefinition } from '../game-data/datasets/item-catalogue.ts';
|
||||
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
|
||||
import type { ItemCatalogue } from '../items/item-catalogue.ts';
|
||||
import { grantItem } from '../items/item-grants.ts';
|
||||
import { addGoldenEagles, addSilverLions, canAfford, pay } from '../profile/profile-currency.ts';
|
||||
import { addOwnedVehicle, ownsVehicle } from '../profile/profile-hangar.ts';
|
||||
import { appendUserLog, EULT_OPEN_TROPHY, incrementTrophyOpenCount, trophyOpenCount } from '../profile/profile-trophies-log.ts';
|
||||
import type { ServerTime } from '../profile/server-time.ts';
|
||||
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
|
||||
import { pickAcrossCountries } from './chest-defs.ts';
|
||||
import { pickWeighted } from './inventory-rules.ts';
|
||||
import type { GroupWeight, SupplyTrophySpec, TrophyPrizeSpec, TrophyTuning } from './trophy-tuning.ts';
|
||||
|
||||
export type TrophyPrize =
|
||||
| { readonly kind: 'warpoints'; readonly amount: number; readonly weight: number }
|
||||
| { readonly kind: 'gold'; readonly amount: number; readonly weight: number }
|
||||
| { readonly kind: 'item'; readonly itemName: string; readonly count: number; readonly weight: number }
|
||||
| { readonly kind: 'unit'; readonly unitName: string; readonly parts: readonly string[]; readonly weight: number };
|
||||
|
||||
export interface TrophyDefinition {
|
||||
readonly id: string;
|
||||
readonly iconStyle: string;
|
||||
readonly silverLions: number;
|
||||
readonly goldenEagles: number;
|
||||
readonly showChances: boolean;
|
||||
readonly repeatable: boolean;
|
||||
readonly instantOpening: boolean;
|
||||
readonly numTotal: number;
|
||||
readonly countryFlag?: string;
|
||||
readonly prizes: readonly TrophyPrize[];
|
||||
}
|
||||
|
||||
export class TrophyCatalogue {
|
||||
readonly #trophies: readonly TrophyDefinition[];
|
||||
readonly #byId = new Map<string, TrophyDefinition>();
|
||||
|
||||
constructor(vehicles: readonly CatalogueVehicle[], classicItems: readonly ItemDefinition[], tuning: TrophyTuning) {
|
||||
const eventVehicles = vehicles
|
||||
.filter((v) => v.event && !v.marketplaceItemdefId && !v.onlyShownWhenOwned && v.inTechTree)
|
||||
.sort((a, b) => (a.rank - b.rank) || a.country.localeCompare(b.country) || a.name.localeCompare(b.name));
|
||||
const pools: PrizePools = { eventVehicles, classicItems };
|
||||
this.#trophies = [
|
||||
...tuning.supplyTrophies.map((spec) => supplyTrophy(spec, pools)),
|
||||
...eventVehicles.map((vehicle) => directVehicleTrophy(vehicle, tuning.directVehicleGoldenEagles)),
|
||||
];
|
||||
for (const trophy of this.#trophies) this.#byId.set(trophy.id, trophy);
|
||||
}
|
||||
|
||||
all(): readonly TrophyDefinition[] {
|
||||
return this.#trophies;
|
||||
}
|
||||
|
||||
byId(id: string): TrophyDefinition | undefined {
|
||||
return this.#byId.get(id);
|
||||
}
|
||||
}
|
||||
|
||||
interface PrizePools {
|
||||
/** Event vehicles not sold on the marketplace, sorted by (rank, country, name). */
|
||||
readonly eventVehicles: readonly CatalogueVehicle[];
|
||||
readonly classicItems: readonly ItemDefinition[];
|
||||
}
|
||||
|
||||
function supplyTrophy(spec: SupplyTrophySpec, pools: PrizePools): TrophyDefinition {
|
||||
return {
|
||||
id: spec.id,
|
||||
iconStyle: spec.iconStyle,
|
||||
silverLions: spec.silverLions,
|
||||
goldenEagles: spec.goldenEagles,
|
||||
showChances: true,
|
||||
repeatable: true,
|
||||
instantOpening: false,
|
||||
numTotal: 0,
|
||||
prizes: spec.prizes.flatMap((prize) => resolvePrize(spec.id, prize, pools)),
|
||||
};
|
||||
}
|
||||
|
||||
/** Turn one prize entry of the tuning file into concrete prizes. */
|
||||
function resolvePrize(trophyId: string, spec: TrophyPrizeSpec, pools: PrizePools): TrophyPrize[] {
|
||||
switch (spec.kind) {
|
||||
case 'silverLions':
|
||||
return [{ kind: 'warpoints', amount: spec.amount, weight: spec.weight }];
|
||||
case 'goldenEagles':
|
||||
return [{ kind: 'gold', amount: spec.amount, weight: spec.weight }];
|
||||
case 'item':
|
||||
if (!pools.classicItems.some((item) => item.name === spec.item)) {
|
||||
throw new Error(`tuning file trophies.jsonc: ${trophyId} names item ${spec.item}, which config/items.blk of this game version does not have`);
|
||||
}
|
||||
return [{ kind: 'item', itemName: spec.item, count: spec.count, weight: spec.weight }];
|
||||
case 'itemsOfType': {
|
||||
const names = pools.classicItems
|
||||
.filter((item) => item.type === spec.itemType && item.expiresAt === undefined)
|
||||
.map((item) => item.name)
|
||||
.sort((a, b) => a.localeCompare(b))
|
||||
.slice(0, spec.pick);
|
||||
const weight = weightEach(spec.weight, names.length);
|
||||
return names.map((itemName): TrophyPrize => ({ kind: 'item', itemName, count: spec.count, weight }));
|
||||
}
|
||||
case 'eventVehicles': {
|
||||
const inRange = pools.eventVehicles.filter((v) => v.rank >= spec.minRank && v.rank <= spec.maxRank);
|
||||
const picked = pickAcrossCountries(inRange, spec.pick);
|
||||
const weight = weightEach(spec.weight, picked.length);
|
||||
return picked.map((v): TrophyPrize => ({ kind: 'unit', unitName: v.name, parts: v.parts, weight }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function weightEach(weight: GroupWeight, count: number): number {
|
||||
if ('each' in weight) return weight.each;
|
||||
return count > 0 ? weight.total / count : 0;
|
||||
}
|
||||
|
||||
function directVehicleTrophy(vehicle: CatalogueVehicle, goldenEagles: number): TrophyDefinition {
|
||||
return {
|
||||
id: `wto_prize_unit_${vehicle.name}`,
|
||||
iconStyle: 'ammo_box',
|
||||
silverLions: 0,
|
||||
goldenEagles,
|
||||
showChances: false,
|
||||
repeatable: false,
|
||||
instantOpening: true,
|
||||
numTotal: 1,
|
||||
countryFlag: vehicle.country,
|
||||
prizes: [{ kind: 'unit', unitName: vehicle.name, parts: vehicle.parts, weight: 100 }],
|
||||
};
|
||||
}
|
||||
|
||||
export function buyTrophy(
|
||||
profile: BlkBlock,
|
||||
trophies: TrophyCatalogue,
|
||||
classicItems: ItemCatalogue,
|
||||
trophyId: string,
|
||||
offeredWp: number,
|
||||
offeredGold: number,
|
||||
now: ServerTime,
|
||||
): RuleOutcome {
|
||||
const trophy = trophies.byId(trophyId);
|
||||
if (!trophy || trophy.prizes.length === 0) return refused('BAD_PARAMS');
|
||||
if (offeredWp !== trophy.silverLions || offeredGold !== trophy.goldenEagles) return refused('PRICE_CHANGED');
|
||||
if (trophy.numTotal > 0 && !trophy.repeatable && trophyOpenCount(profile, trophy.id) >= trophy.numTotal) {
|
||||
return refused('NOT_AVAILABLE');
|
||||
}
|
||||
if (trophy.prizes.length === 1 && trophy.prizes[0]!.kind === 'unit' && ownsVehicle(profile, trophy.prizes[0]!.unitName)) {
|
||||
return refused('NOT_AVAILABLE');
|
||||
}
|
||||
|
||||
const price = { silverLions: trophy.silverLions, goldenEagles: trophy.goldenEagles };
|
||||
if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY');
|
||||
|
||||
const eligible = trophy.prizes.filter((prize) => prize.kind !== 'unit' || !ownsVehicle(profile, prize.unitName));
|
||||
const chosen = pickWeighted(eligible.length > 0 ? eligible : trophy.prizes);
|
||||
|
||||
pay(profile, price);
|
||||
const openSeq = incrementTrophyOpenCount(profile, trophy.id, 1);
|
||||
const logBody = applyTrophyPrize(profile, classicItems, trophy.id, openSeq, chosen, now);
|
||||
appendUserLog(profile, { type: EULT_OPEN_TROPHY, timeSec: Math.floor(Date.now() / 1000), bodyParams: logBody });
|
||||
return ACCEPTED;
|
||||
}
|
||||
|
||||
function applyTrophyPrize(
|
||||
profile: BlkBlock,
|
||||
classicItems: ItemCatalogue,
|
||||
trophyId: string,
|
||||
openSeq: number,
|
||||
chosen: TrophyPrize,
|
||||
now: ServerTime,
|
||||
): BlkParam[] {
|
||||
const logBody: BlkParam[] = [
|
||||
{ name: 'id', value: { type: 'string', value: trophyId } },
|
||||
{ name: 'trophyItemId', value: { type: 'int', value: openSeq } },
|
||||
];
|
||||
switch (chosen.kind) {
|
||||
case 'warpoints':
|
||||
addSilverLions(profile, chosen.amount);
|
||||
logBody.push({ name: 'warpoints', value: { type: 'int', value: chosen.amount } });
|
||||
break;
|
||||
case 'gold':
|
||||
addGoldenEagles(profile, chosen.amount);
|
||||
logBody.push({ name: 'gold', value: { type: 'int', value: chosen.amount } });
|
||||
break;
|
||||
case 'item': {
|
||||
const def = classicItems.item(chosen.itemName);
|
||||
if (def) grantItem(profile, def, chosen.count, now);
|
||||
logBody.push(
|
||||
{ name: 'item', value: { type: 'string', value: chosen.itemName } },
|
||||
{ name: 'count', value: { type: 'int', value: chosen.count } },
|
||||
);
|
||||
break;
|
||||
}
|
||||
case 'unit':
|
||||
addOwnedVehicle(profile, chosen.unitName);
|
||||
for (const part of chosen.parts) addOwnedVehicle(profile, part);
|
||||
logBody.push(
|
||||
{ name: 'unit', value: { type: 'string', value: chosen.unitName } },
|
||||
{ name: 'count', value: { type: 'int', value: 1 } },
|
||||
);
|
||||
break;
|
||||
}
|
||||
return logBody;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
/** Typed content of tuning/trophies.jsonc. */
|
||||
import { TuningError, type TuningReader } from '../tuning/tuning-reader.ts';
|
||||
|
||||
/** How the weight of a prize group is given: each prize's own, or the group's, split evenly. */
|
||||
export type GroupWeight = { readonly each: number } | { readonly total: number };
|
||||
|
||||
export type TrophyPrizeSpec =
|
||||
| { readonly kind: 'silverLions'; readonly amount: number; readonly weight: number }
|
||||
| { readonly kind: 'goldenEagles'; readonly amount: number; readonly weight: number }
|
||||
| { readonly kind: 'item'; readonly item: string; readonly count: number; readonly weight: number }
|
||||
| { readonly kind: 'itemsOfType'; readonly itemType: string; readonly pick: number; readonly count: number; readonly weight: GroupWeight }
|
||||
| { readonly kind: 'eventVehicles'; readonly minRank: number; readonly maxRank: number; readonly pick: number; readonly weight: GroupWeight };
|
||||
|
||||
export interface SupplyTrophySpec {
|
||||
readonly id: string;
|
||||
readonly iconStyle: string;
|
||||
readonly silverLions: number;
|
||||
readonly goldenEagles: number;
|
||||
readonly prizes: readonly TrophyPrizeSpec[];
|
||||
}
|
||||
|
||||
export interface TrophyTuning {
|
||||
readonly supplyTrophies: readonly SupplyTrophySpec[];
|
||||
readonly directVehicleGoldenEagles: number;
|
||||
}
|
||||
|
||||
export function readTrophyTuning(file: TuningReader): TrophyTuning {
|
||||
return {
|
||||
supplyTrophies: file.list('supplyTrophies', (entry) => ({
|
||||
id: entry.string('id'),
|
||||
iconStyle: entry.string('iconStyle'),
|
||||
silverLions: entry.int('silverLions', { min: 0 }),
|
||||
goldenEagles: entry.int('goldenEagles', { min: 0 }),
|
||||
prizes: entry.list('prizes', readPrize),
|
||||
})),
|
||||
directVehicleGoldenEagles: file.object('directVehicles').int('goldenEagles', { min: 1 }),
|
||||
};
|
||||
}
|
||||
|
||||
function readPrize(entry: TuningReader): TrophyPrizeSpec {
|
||||
const weight = () => entry.number('weight', { min: 0 });
|
||||
if (entry.has('silverLions')) return { kind: 'silverLions', amount: entry.int('silverLions', { min: 1 }), weight: weight() };
|
||||
if (entry.has('goldenEagles')) return { kind: 'goldenEagles', amount: entry.int('goldenEagles', { min: 1 }), weight: weight() };
|
||||
if (entry.has('item')) return { kind: 'item', item: entry.string('item'), count: entry.int('count', { min: 1 }), weight: weight() };
|
||||
if (entry.has('itemsOfType')) {
|
||||
return { kind: 'itemsOfType', itemType: entry.string('itemsOfType'), pick: entry.int('pick', { min: 1 }), count: entry.int('count', { min: 1 }), weight: groupWeight(entry) };
|
||||
}
|
||||
if (entry.has('eventVehicles')) {
|
||||
const vehicles = entry.object('eventVehicles');
|
||||
return {
|
||||
kind: 'eventVehicles',
|
||||
minRank: vehicles.int('minRank', { min: 1 }),
|
||||
maxRank: vehicles.int('maxRank', { min: 1 }),
|
||||
pick: vehicles.int('pick', { min: 1 }),
|
||||
weight: groupWeight(entry),
|
||||
};
|
||||
}
|
||||
throw new TuningError(`tuning file trophies.jsonc: a prize needs one of silverLions, goldenEagles, item, itemsOfType, eventVehicles (found ${JSON.stringify(entry.keys())})`);
|
||||
}
|
||||
|
||||
function groupWeight(entry: TuningReader): GroupWeight {
|
||||
if (entry.has('weightEach')) return { each: entry.number('weightEach', { min: 0 }) };
|
||||
if (entry.has('weightTotal')) return { total: entry.number('weightTotal', { min: 0 }) };
|
||||
throw new TuningError(`tuning file trophies.jsonc: a prize group needs weightEach or weightTotal (found ${JSON.stringify(entry.keys())})`);
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
// Local marketplace page (implementation notes; layout after the official Gaijin Market,
|
||||
// implementation notes), shown in the game's built-in browser.
|
||||
// The game opens it as <marketplaceURL>?a=<app id>[&viewitem&n=<market_hash_name>] (inventoryClient.nut);
|
||||
// with `n` the page opens that item's card directly.
|
||||
'use strict';
|
||||
|
||||
const T = {
|
||||
zh: {
|
||||
toStore: '前往商城', eagles: '金鹰', filters: '筛选', itemType: '物品类型', country: '国家', vehicleClass: '适用于',
|
||||
heldOnly: '只看我的库存', search: '搜索', sortPopular: '人气', sortName: '名称(从 A 到 Z)', sortPriceAsc: '价格(从低到高)', sortPriceDesc: '价格(从高到低)',
|
||||
catVehicle: '载具', catSkin: '涂装', catAttachable: '装饰挂件', catDecal: '贴花', catUnlock: '头像',
|
||||
allCountries: '全部国家', allClasses: '全部', rank: '{rank} 级', from: '从', held: '库存 ×{n}', owned: '已拥有',
|
||||
buy: '购买', freeBuy: '老福爷付过了', sell: '出售', pickAccount: '请先在右上角选择账号', empty: '没有符合条件的物品',
|
||||
buyPrice: '系统售价:<b>{price}</b> GJN', sellPrice: '卖给系统:<b>{price}</b> GJN(扣 {fee}% 手续费)', youHave: '你拥有:<b>{n}</b>',
|
||||
tradeUnconfirmed: '无法确认交易结果,请先查看余额和库存。',
|
||||
tagType: '物品类型', tagRarity: '稀有度', tagCountry: '国家', ticker: '离线交易所:按固定价格与系统交易,价格取自官方交易所快照。',
|
||||
},
|
||||
en: {
|
||||
toStore: 'Store', eagles: 'Golden Eagles', filters: 'Filters', itemType: 'Item type', country: 'Country', vehicleClass: 'Vehicle type',
|
||||
heldOnly: 'Only my inventory', search: 'Search', sortPopular: 'Popular', sortName: 'Name (A to Z)', sortPriceAsc: 'Price (low to high)', sortPriceDesc: 'Price (high to low)',
|
||||
catVehicle: 'Vehicles', catSkin: 'Camouflages', catAttachable: 'Decorations', catDecal: 'Decals', catUnlock: 'Avatars',
|
||||
allCountries: 'All countries', allClasses: 'All', rank: 'Rank {rank}', from: 'from', held: 'Owned ×{n}', owned: 'Owned',
|
||||
buy: 'Buy', freeBuy: '老福爷付过了', sell: 'Sell', pickAccount: 'Pick an account at the top right', empty: 'Nothing matches the filters',
|
||||
buyPrice: 'System price: <b>{price}</b> GJN', sellPrice: 'Sell to system: <b>{price}</b> GJN ({fee}% fee)', youHave: 'You own: <b>{n}</b>',
|
||||
tradeUnconfirmed: 'Could not confirm the trade. Check your balance and inventory.',
|
||||
tagType: 'Item type', tagRarity: 'Rarity', tagCountry: 'Country', ticker: 'Offline market: fixed-price trades with the system, prices from an official market snapshot.',
|
||||
},
|
||||
};
|
||||
const CATEGORIES = [['vehicle', 'catVehicle', '#fd5f2c'], ['skin', 'catSkin', '#8f7ee7'], ['attachable', 'catAttachable', '#8f7ee7'], ['decal', 'catDecal', '#8f7ee7'], ['unlock', 'catUnlock', '#00ced1']];
|
||||
const CLASS_LABELS = { aircraft: 'mainmenu/type_aircraft', helicopter: 'mainmenu/type_helicopter', tank: 'mainmenu/type_tank', ship: 'mainmenu/type_ship_only', boat: 'mainmenu/type_boat_only' };
|
||||
const RARITY = { afafa1: ['常见', 'Common'], '14bd3a': ['罕见', 'Uncommon'], '2965ff': ['稀有', 'Rare'], c816c1: ['超稀有', 'Ultra rare'] };
|
||||
const ROMAN = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X'];
|
||||
const t = (key, params) => WtoUi.tr(T, key, params);
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const wantedItem = WtoUi.query.get('n') || '';
|
||||
|
||||
let state = { accounts: [], currentUserId: '', balance: { gjnCents: 0, goldenEagles: 0 }, listings: [] };
|
||||
const activeCats = new Set();
|
||||
let openedWanted = false;
|
||||
let tradeNoticeId = 0;
|
||||
|
||||
function applyStaticTexts() {
|
||||
for (const el of document.querySelectorAll('[data-t]')) el.textContent = t(el.dataset.t);
|
||||
$('searchInput').placeholder = t('search');
|
||||
$('storeLink').href = WtoUi.pageLink('/store');
|
||||
const types = $('typeFilters');
|
||||
for (const [cat, key, color] of CATEGORIES) {
|
||||
const row = document.createElement('label');
|
||||
row.className = 'check';
|
||||
row.innerHTML = '<input type="checkbox" /> <span></span>';
|
||||
row.querySelector('span').textContent = t(key);
|
||||
row.querySelector('span').style.color = color;
|
||||
row.querySelector('input').onchange = (e) => { if (e.target.checked) activeCats.add(cat); else activeCats.delete(cat); renderGrid(); };
|
||||
types.appendChild(row);
|
||||
}
|
||||
const classSelect = $('classFilter');
|
||||
classSelect.appendChild(new Option(t('allClasses'), ''));
|
||||
for (const [unitClass, key] of Object.entries(CLASS_LABELS)) classSelect.appendChild(new Option(WtoUi.label(key), unitClass));
|
||||
}
|
||||
|
||||
async function loadState(userId) {
|
||||
state = await WtoUi.getJson('/trade.gaijin.net/api/state' + (userId ? '?userId=' + encodeURIComponent(userId) : ''));
|
||||
if (userId && !state.currentUserId) { WtoUi.clearSavedAccount(); return loadState(''); }
|
||||
WtoUi.fillAccountSelect($('accountSelect'), state.accounts, state.currentUserId);
|
||||
$('gjnVal').textContent = WtoUi.gjn(state.balance.gjnCents);
|
||||
$('goldVal').textContent = WtoUi.num(state.balance.goldenEagles);
|
||||
renderCountries();
|
||||
renderGrid();
|
||||
if (wantedItem && !openedWanted) {
|
||||
openedWanted = true;
|
||||
const wanted = state.listings.find((l) => l.marketHashName === wantedItem);
|
||||
if (wanted) openDetail(wanted);
|
||||
}
|
||||
}
|
||||
|
||||
function renderCountries() {
|
||||
const select = $('countryFilter');
|
||||
const previous = select.value;
|
||||
select.innerHTML = '';
|
||||
select.appendChild(new Option(t('allCountries'), ''));
|
||||
for (const country of [...new Set(state.listings.map((l) => l.country).filter(Boolean))]) select.appendChild(new Option(WtoUi.label(country), country, false, country === previous));
|
||||
}
|
||||
|
||||
function matches(listing) {
|
||||
const query = $('searchInput').value.trim().toLowerCase();
|
||||
if (activeCats.size && !activeCats.has(listing.category)) return false;
|
||||
if ($('countryFilter').value && listing.country !== $('countryFilter').value) return false;
|
||||
if ($('classFilter').value && listing.unitClass !== $('classFilter').value) return false;
|
||||
if ($('heldOnly').checked && !listing.couponCount) return false;
|
||||
return !query || [listing.title.zh, listing.title.en, listing.marketHashName, String(listing.itemdefId)].some((s) => (s || '').toLowerCase().includes(query));
|
||||
}
|
||||
|
||||
function sorted(listings) {
|
||||
const mode = $('sortSelect').value;
|
||||
const copy = [...listings];
|
||||
if (mode === 'name') copy.sort((a, b) => WtoUi.text(a.title).localeCompare(WtoUi.text(b.title)));
|
||||
if (mode === 'priceAsc') copy.sort((a, b) => a.gjnCostCents - b.gjnCostCents);
|
||||
if (mode === 'priceDesc') copy.sort((a, b) => b.gjnCostCents - a.gjnCostCents);
|
||||
return copy;
|
||||
}
|
||||
|
||||
function listingImage(listing, className) {
|
||||
return listing.category === 'vehicle' ? WtoUi.vehicleImg(listing.targetKey, className) : WtoUi.itemImg(listing.category, listing.targetKey, className);
|
||||
}
|
||||
|
||||
function renderGrid() {
|
||||
const grid = $('grid');
|
||||
grid.innerHTML = '';
|
||||
const listings = sorted(state.listings.filter(matches));
|
||||
if (!listings.length) grid.innerHTML = '<div class="empty">' + WtoUi.escapeHtml(t('empty')) + '</div>';
|
||||
for (const listing of listings) grid.appendChild(lotCard(listing));
|
||||
}
|
||||
|
||||
function lotCard(listing) {
|
||||
const card = document.createElement('a');
|
||||
card.className = 'lot' + (listing.marketHashName === wantedItem ? ' highlight' : '');
|
||||
const color = '#' + (listing.nameColor || 'afafa1');
|
||||
card.innerHTML = '<div class="rarity"></div><div class="lot-image"></div><div class="lot-meta"><div class="project"></div><div class="lot-name"></div></div><div class="lot-stats"></div>';
|
||||
card.querySelector('.rarity').style.background = 'linear-gradient(180deg, ' + color + ', transparent)';
|
||||
card.querySelector('.lot-image').appendChild(listingImage(listing, ''));
|
||||
const project = card.querySelector('.project');
|
||||
if (listing.country) project.appendChild(WtoUi.iconImg('flag', listing.country, ''));
|
||||
project.appendChild(document.createTextNode(listing.rank ? 'War Thunder · ' + t('rank', { rank: ROMAN[listing.rank] || listing.rank }) : 'War Thunder'));
|
||||
card.querySelector('.lot-name').textContent = WtoUi.text(listing.title);
|
||||
const stats = card.querySelector('.lot-stats');
|
||||
if (listing.couponCount) stats.appendChild(Object.assign(document.createElement('div'), { className: 'lot-held', textContent: t('held', { n: listing.couponCount }) }));
|
||||
else if (listing.alreadyActivated) stats.appendChild(Object.assign(document.createElement('div'), { className: 'lot-held', textContent: t('owned') }));
|
||||
const price = document.createElement('div');
|
||||
price.className = 'lot-price';
|
||||
price.innerHTML = '<small></small><span></span> GJN';
|
||||
price.querySelector('small').textContent = t('from');
|
||||
price.querySelector('span').textContent = WtoUi.gjn(listing.gjnCostCents);
|
||||
stats.appendChild(price);
|
||||
card.onclick = () => openDetail(listing);
|
||||
return card;
|
||||
}
|
||||
|
||||
function tag(text, color, extraClass) {
|
||||
const el = Object.assign(document.createElement('span'), { className: 'tag' + (extraClass ? ' ' + extraClass : ''), textContent: text });
|
||||
if (color) el.style.background = color;
|
||||
return el;
|
||||
}
|
||||
|
||||
function openDetail(listing) {
|
||||
const color = '#' + (listing.nameColor || 'afafa1');
|
||||
const detail = $('detail');
|
||||
detail.style.setProperty('--glow', color);
|
||||
detail.innerHTML = '<div class="detail-glow"></div><button class="detail-close">×</button><h2 class="detail-title"></h2>'
|
||||
+ '<div class="detail-info"><div class="detail-image"></div><div class="detail-side"><div class="tags"></div><div class="detail-desc"></div></div></div>'
|
||||
+ '<div class="orders"><div class="sell-col"></div><div class="buy-col"></div></div><div class="ticker"></div>';
|
||||
detail.querySelector('.detail-title').textContent = WtoUi.text(listing.title);
|
||||
detail.querySelector('.detail-image').appendChild(listingImage(listing, ''));
|
||||
const tags = detail.querySelector('.tags');
|
||||
tags.appendChild(tag('War Thunder', '', 'game'));
|
||||
const cat = CATEGORIES.find((c) => c[0] === listing.category);
|
||||
if (cat) tags.appendChild(tag(t('tagType') + ': ' + t(cat[1]), cat[2]));
|
||||
const rarity = RARITY[(listing.nameColor || '').toLowerCase()];
|
||||
if (rarity) tags.appendChild(tag(t('tagRarity') + ': ' + (WtoUi.lang === 'zh' ? rarity[0] : rarity[1]), color));
|
||||
if (listing.country) tags.appendChild(tag(t('tagCountry') + ': ' + WtoUi.label(listing.country), '#68838c'));
|
||||
detail.querySelector('.detail-desc').textContent = WtoUi.text(listing.subtitle);
|
||||
fillOrderColumns(detail, listing);
|
||||
detail.querySelector('.ticker').textContent = t('ticker');
|
||||
detail.querySelector('.detail-close').onclick = closeDetail;
|
||||
$('modal').hidden = false;
|
||||
}
|
||||
|
||||
function fillOrderColumns(detail, listing) {
|
||||
const fee = Math.round(state.sellFeeRate * 100);
|
||||
const sellCol = detail.querySelector('.sell-col');
|
||||
const buyCol = detail.querySelector('.buy-col');
|
||||
const noAccount = !state.currentUserId;
|
||||
const sellBtn = Object.assign(document.createElement('button'), { className: 'big sell', textContent: t('sell'), disabled: noAccount || !listing.couponCount });
|
||||
sellBtn.onclick = () => trade('/trade.gaijin.net/api/sell', { itemdefId: listing.itemdefId, quantity: 1 }, listing);
|
||||
sellCol.append(sellBtn, html('totals', t('sellPrice', { price: WtoUi.gjn(listing.sellCents), fee })), html('totals', t('youHave', { n: listing.couponCount || 0 })));
|
||||
const buyBtn = Object.assign(document.createElement('button'), { className: 'big buy', textContent: noAccount ? t('pickAccount') : t('buy'), disabled: noAccount });
|
||||
buyBtn.onclick = () => trade('/trade.gaijin.net/api/buy', { itemdefId: listing.itemdefId, quantity: 1, payMethod: 'gjn' }, listing);
|
||||
const freeBtn = Object.assign(document.createElement('button'), { className: 'big free', textContent: t('freeBuy'), disabled: noAccount });
|
||||
freeBtn.onclick = () => trade('/trade.gaijin.net/api/buy', { itemdefId: listing.itemdefId, quantity: 1, payMethod: 'free' }, listing);
|
||||
buyCol.append(buyBtn, freeBtn, html('totals', t('buyPrice', { price: WtoUi.gjn(listing.gjnCostCents) })));
|
||||
}
|
||||
|
||||
function html(className, markup) {
|
||||
const el = document.createElement('div');
|
||||
el.className = className;
|
||||
el.innerHTML = markup;
|
||||
return el;
|
||||
}
|
||||
|
||||
function closeDetail() { $('modal').hidden = true; }
|
||||
|
||||
async function trade(url, body, listing) {
|
||||
const notice = $('notice');
|
||||
const noticeId = ++tradeNoticeId;
|
||||
notice.textContent = '';
|
||||
notice.className = 'notice';
|
||||
|
||||
const showResult = (message, ok) => {
|
||||
if (noticeId === tradeNoticeId) WtoUi.showNotice(notice, message, ok);
|
||||
};
|
||||
|
||||
let result;
|
||||
try {
|
||||
result = await WtoUi.postJson(url, { userId: state.currentUserId, ...body });
|
||||
} catch {
|
||||
showResult(t('tradeUnconfirmed'), false);
|
||||
return;
|
||||
}
|
||||
const message = WtoUi.text(result?.message);
|
||||
if (typeof result?.ok !== 'boolean' || typeof message !== 'string' || !message) {
|
||||
showResult(t('tradeUnconfirmed'), false);
|
||||
return;
|
||||
}
|
||||
showResult(message, result.ok);
|
||||
await loadState(state.currentUserId);
|
||||
const fresh = state.listings.find((l) => l.itemdefId === listing.itemdefId);
|
||||
if (fresh && !$('modal').hidden) openDetail(fresh);
|
||||
}
|
||||
|
||||
$('modal').onclick = (event) => { if (event.target === $('modal')) closeDetail(); };
|
||||
$('accountSelect').onchange = (event) => { WtoUi.saveAccount(event.target.value); loadState(event.target.value); };
|
||||
for (const id of ['countryFilter', 'classFilter', 'sortSelect', 'heldOnly']) $(id).onchange = renderGrid;
|
||||
$('searchInput').oninput = renderGrid;
|
||||
|
||||
Promise.all([WtoUi.loadLabels(), WtoUi.loadImageSources()]).then(() => {
|
||||
applyStaticTexts();
|
||||
return loadState(WtoUi.savedAccount());
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Gaijin Market · WTOffline</title>
|
||||
<link rel="stylesheet" href="/trade.gaijin.net/styles.css" />
|
||||
</head>
|
||||
<body>
|
||||
<header class="head">
|
||||
<div class="logo"><span class="logo-top">Gaijin.Net</span><span class="logo-main">MARKET</span></div>
|
||||
<nav class="nav">
|
||||
<a class="nav-item" id="storeLink" data-t="toStore"></a>
|
||||
<span class="nav-item wallet"><span class="coin"></span><b id="gjnVal">0</b></span>
|
||||
<span class="nav-item muted"><span data-t="eagles"></span> <b id="goldVal">0</b></span>
|
||||
<select id="accountSelect" class="nav-select"></select>
|
||||
</nav>
|
||||
</header>
|
||||
<div class="layout">
|
||||
<aside class="filters">
|
||||
<div class="filters-caption" data-t="filters"></div>
|
||||
<div class="filter-group">
|
||||
<h3 data-t="itemType"></h3>
|
||||
<div id="typeFilters"></div>
|
||||
</div>
|
||||
<div class="filter-group">
|
||||
<h3 data-t="country"></h3>
|
||||
<select id="countryFilter"></select>
|
||||
</div>
|
||||
<div class="filter-group">
|
||||
<h3 data-t="vehicleClass"></h3>
|
||||
<select id="classFilter"></select>
|
||||
</div>
|
||||
<div class="filter-group">
|
||||
<label class="check"><input type="checkbox" id="heldOnly" /> <span data-t="heldOnly"></span></label>
|
||||
</div>
|
||||
</aside>
|
||||
<main class="screen">
|
||||
<div class="controls">
|
||||
<div class="search"><input id="searchInput" type="search" /></div>
|
||||
<select id="sortSelect" class="control">
|
||||
<option value="popular" data-t="sortPopular"></option>
|
||||
<option value="name" data-t="sortName"></option>
|
||||
<option value="priceAsc" data-t="sortPriceAsc"></option>
|
||||
<option value="priceDesc" data-t="sortPriceDesc"></option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="grid" id="grid"></div>
|
||||
</main>
|
||||
</div>
|
||||
<div class="modal" id="modal" hidden>
|
||||
<div class="card-detail" id="detail"></div>
|
||||
</div>
|
||||
<div id="notice" class="notice" role="status"></div>
|
||||
<script src="/_wto/ui/common.js"></script>
|
||||
<script src="/trade.gaijin.net/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,94 @@
|
||||
/* Local marketplace page, laid out like the official Gaijin Market (implementation notes
|
||||
section 4; Chromium 100: no :has(), container queries or CSS nesting). Fonts fall back to system fonts. */
|
||||
:root {
|
||||
--bg: #1c1f23; --surface: #272a2e; --lift: #2e3238; --cyan: #31e3ee; --red: #bf2d36; --green: #2a826d;
|
||||
--text: #cbd7dc; --muted: #ffffff80; --hair: #ffffff0d; --disabled: #ffffff24;
|
||||
--font: Inter, "Source Sans Pro", "Segoe UI", "Microsoft YaHei", sans-serif;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
[hidden] { display: none !important; }
|
||||
html, body { margin: 0; min-height: 100%; }
|
||||
body { background: var(--bg); color: var(--text); font: 14px/18px var(--font); min-width: 1024px; }
|
||||
::-webkit-scrollbar { width: 8px; } ::-webkit-scrollbar-thumb { background: var(--disabled); border-radius: 4px; }
|
||||
|
||||
.head { position: sticky; top: 0; z-index: 100; height: 72px; display: flex; align-items: center; padding: 8px 16px 4px; background: var(--surface); }
|
||||
.logo { display: flex; flex-direction: column; color: #fff; }
|
||||
.logo-top { font-size: 16px; font-weight: 500; opacity: 0.8; line-height: 18px; }
|
||||
.logo-main { font-size: 22px; font-weight: 700; line-height: 24px; letter-spacing: 0.02em; }
|
||||
.nav { margin-left: auto; display: flex; align-items: center; gap: 16px; }
|
||||
.nav-item { display: flex; align-items: center; gap: 6px; height: 40px; padding: 10px 8px; border-radius: 8px; color: var(--text); text-decoration: none; }
|
||||
.nav-item:hover { background: var(--hair); }
|
||||
.nav-item.muted { color: var(--muted); }
|
||||
.wallet b { color: #ffda7c; font-size: 16px; }
|
||||
.coin { width: 18px; height: 18px; border-radius: 50%; background: radial-gradient(circle at 35% 35%, #ffe9a8, #d9a43a 70%); }
|
||||
.nav-select { height: 40px; padding: 0 10px; border: none; border-radius: 8px; background: var(--lift); color: #fff; font: inherit; }
|
||||
|
||||
.layout { display: flex; gap: 24px; padding: 24px; align-items: flex-start; }
|
||||
.filters { flex: none; width: 250px; padding: 16px; border-radius: 5px; background: var(--surface); font-family: "Golos UI", var(--font); position: sticky; top: 96px; }
|
||||
.filters-caption { color: #fff; font-size: 16px; font-weight: 700; text-transform: uppercase; margin-bottom: 12px; }
|
||||
.filter-group { padding: 10px 0; border-top: 1px solid var(--hair); }
|
||||
.filter-group h3 { margin: 0 0 8px; color: #fff; font-size: 14px; font-weight: 600; }
|
||||
.filter-group select { width: 100%; height: 34px; border: none; border-radius: 5px; background: var(--lift); color: #fff; font: inherit; padding: 0 8px; }
|
||||
.check { display: flex; align-items: center; gap: 8px; height: 24px; font-size: 15px; cursor: pointer; }
|
||||
.check input { accent-color: var(--cyan); }
|
||||
|
||||
.screen { flex: 1; min-width: 0; }
|
||||
.controls { display: flex; gap: 16px; align-items: center; height: 48px; }
|
||||
.search { flex: 1; max-width: 420px; }
|
||||
.search input { width: 100%; height: 48px; padding: 8px 16px; border: none; border-radius: 8px; background: #06090d4f; color: #fff; font: 16px var(--font); box-shadow: inset 0 -1px #ffffff1a; outline: none; }
|
||||
.search input:focus { background: #06090d9e; box-shadow: inset 0 -1px #ffffff4d; }
|
||||
.control { margin-left: auto; min-width: 180px; height: 40px; border: none; border-radius: 5px; background: var(--surface); color: #fff; font: inherit; padding: 0 10px; }
|
||||
|
||||
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 18px; margin: 24px 0; }
|
||||
.lot { position: relative; display: flex; flex-direction: column; height: 352px; max-width: 260px; border-radius: 5px; background: var(--surface); overflow: hidden; cursor: pointer; transition: transform 0.15s; }
|
||||
.lot:hover { transform: translateY(-2px); }
|
||||
.lot.highlight { outline: 2px solid var(--cyan); }
|
||||
.rarity { position: absolute; left: 0; right: 0; top: 0; height: 45%; opacity: 0.35; }
|
||||
.rarity::before { content: ""; position: absolute; left: 0; right: 0; top: 0; height: 2px; background: inherit; opacity: 1; }
|
||||
.lot-image { position: relative; height: 180px; display: flex; align-items: center; justify-content: center; padding: 12px; }
|
||||
.lot-image img { width: 100%; height: 100%; object-fit: contain; }
|
||||
.lot-meta { position: relative; padding: 0 14px; }
|
||||
.project { display: flex; align-items: center; gap: 6px; color: var(--muted); font-size: 12px; }
|
||||
.project img { width: 16px; height: 11px; }
|
||||
.lot-name { height: 53px; margin: 8px 0; color: #fff; font-size: 16px; line-height: 20px; overflow: hidden; word-break: break-word; }
|
||||
.lot-stats { margin-top: auto; padding: 0 14px 14px; display: flex; flex-direction: column; align-items: flex-end; gap: 4px; }
|
||||
.lot-held { color: var(--cyan); font-size: 13px; }
|
||||
.lot-price { color: #fff; font-size: 17px; font-weight: 600; }
|
||||
.lot-price small { color: #2dd4aa; font-size: 12px; font-weight: 400; margin-right: 4px; }
|
||||
.empty { color: var(--muted); padding: 40px 0; }
|
||||
|
||||
.notice {
|
||||
position: fixed;
|
||||
z-index: 1001;
|
||||
top: 16px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
max-width: calc(100% - 32px);
|
||||
pointer-events: none;
|
||||
}
|
||||
.notice.ok, .notice.err { padding: 10px 14px; border-radius: 8px; background: var(--surface); }
|
||||
.notice.ok { color: #2dd4aa; }
|
||||
.notice.err { color: #ff6b73; }
|
||||
|
||||
.modal { position: fixed; inset: 0; z-index: 1000; display: flex; justify-content: center; align-items: flex-start; overflow-y: auto; background: #0b0f16db; }
|
||||
.card-detail { position: relative; width: 960px; margin: 45px auto; border-radius: 5px; background: var(--surface); box-shadow: 0 24px 32px #00000061; overflow: hidden; }
|
||||
.detail-glow { height: 2px; box-shadow: 0 6px 16px var(--glow); background: var(--glow); }
|
||||
.detail-title { margin: 29px 64px 16px 24px; color: #fff; font-size: 24px; font-weight: 400; }
|
||||
.detail-close { position: absolute; top: 2px; right: 0; width: 40px; height: 40px; border: none; background: #0000002b; color: #fff; font-size: 22px; cursor: pointer; }
|
||||
.detail-info { display: flex; gap: 24px; padding: 0 24px; }
|
||||
.detail-image { flex: none; width: 440px; height: 260px; display: flex; align-items: center; justify-content: center; border-radius: 5px; background: radial-gradient(50% 50% at 50% 50%, #272a2e99 0%, #272a2ef0 85%, #272a2e 100%), var(--glow); }
|
||||
.detail-image img { width: 92%; height: 92%; object-fit: contain; }
|
||||
.tags { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.tag { padding: 4px 10px; border-radius: 2px; color: #000; font-size: 12px; font-weight: 600; }
|
||||
.tag.game { background: #12151a9e; color: #fff; }
|
||||
.detail-desc { margin-top: 12px; color: var(--text); }
|
||||
.orders { display: flex; padding: 32px 24px; gap: 24px; }
|
||||
.orders > div { flex: 1; display: flex; flex-direction: column; align-items: center; gap: 12px; }
|
||||
.big { width: 280px; height: 56px; border: none; border-radius: 5px; color: #fff; font: 700 16px var(--font); cursor: pointer; }
|
||||
.big.sell { background: var(--green); box-shadow: 0 4px 8px #00392c80; }
|
||||
.big.buy { background: var(--red); box-shadow: 0 4px 8px #7b000080; }
|
||||
.big.free { background: transparent; border: 1px solid #ffda7c; color: #ffda7c; box-shadow: none; height: 44px; }
|
||||
.big:disabled { background: var(--disabled); color: #ffffff66; border-color: transparent; box-shadow: none; cursor: default; }
|
||||
.totals { color: var(--muted); font-size: 15px; text-align: center; }
|
||||
.totals b { color: #fff; }
|
||||
.ticker { padding: 16px 64px; background: #0000001a; color: var(--text); font-weight: 600; }
|
||||
Reference in new issue
Block a user