@idosgames/mcp 0.1.19 → 0.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/cli.js +2 -2
  2. package/package.json +1 -1
  3. package/registry/host.json +13 -13
  4. package/registry/index.json +474 -147
  5. package/registry/modules/ai.json +65 -0
  6. package/registry/modules/board-game.json +4 -4
  7. package/registry/modules/boosts.json +66 -0
  8. package/registry/modules/character.json +7 -8
  9. package/registry/modules/chat.json +7 -8
  10. package/registry/modules/collections.json +69 -0
  11. package/registry/modules/coop-events.json +67 -0
  12. package/registry/modules/craft.json +7 -8
  13. package/registry/modules/deals.json +7 -8
  14. package/registry/modules/events.json +10 -15
  15. package/registry/modules/friends.json +8 -8
  16. package/registry/modules/idle-rpg.json +4 -4
  17. package/registry/modules/inventory.json +16 -19
  18. package/registry/modules/invite.json +9 -9
  19. package/registry/modules/leaderboard.json +7 -8
  20. package/registry/modules/lootboxes.json +67 -0
  21. package/registry/modules/mailbox.json +71 -0
  22. package/registry/modules/marketplace.json +7 -8
  23. package/registry/modules/mini-game.json +7 -7
  24. package/registry/modules/multiplayer.json +74 -0
  25. package/registry/modules/premium.json +67 -0
  26. package/registry/modules/profile.json +11 -12
  27. package/registry/modules/pvp.json +5 -6
  28. package/registry/modules/quests.json +69 -0
  29. package/registry/modules/rewards.json +17 -23
  30. package/registry/modules/season.json +10 -15
  31. package/registry/modules/store.json +7 -8
  32. package/registry/modules/tutorials.json +7 -8
  33. package/registry/modules/voxelcraft.json +16 -12
  34. package/registry/modules/workshop.json +7 -8
  35. package/registry/skills/blockchain-system.json +1 -1
  36. package/registry/skills/idosgames-compose-modules.json +2 -2
  37. package/registry/skills/idosgames-getting-started.json +1 -1
  38. package/registry/skills/idosgames-module-contract.json +2 -2
  39. package/registry/skills/idosgames-project-structure.json +1 -1
  40. package/registry/skills/idosgames-ui-kit.json +2 -2
  41. package/registry/skills/mailbox-system.json +6 -0
  42. package/registry/skills/multiplayer-realtime.json +2 -2
  43. package/registry/skills/workshop-system.json +1 -1
@@ -7,7 +7,6 @@
7
7
  },
8
8
  "catalog": {
9
9
  "type": "feature",
10
- "inBase": true,
11
10
  "summary": "Workshop: players and the publisher share content (maps, levels, skins, models) — free, for in-game resources, or unlocked by holding items.",
12
11
  "description": "A ready catalog of user-generated content for ANY game. Players publish what they made (a world, a level, a skin, any file the title allows), set how others get it — free, a price in in-game resources (several options at once, the author receives it minus commission), or 'hold N of this item / currency to unlock' (nothing is charged; while held or once) — and others browse, filter, acquire, open, like, favorite, follow authors and report. The publisher configures content types, formats, limits, commission and moderation in the Workshop section of the title config, curates featured collections and publishes official content from the dashboard. A game plugs its own content in by registering a handler with ctx.content.registerType({ type, label, listLocal, capture, open, modeId }) — the Workshop never imports the game. VoxelCraft registers 'voxelcraft.world'.",
13
12
  "provides": [
@@ -37,15 +36,15 @@
37
36
  "name": "iDos Games",
38
37
  "url": "https://idosgames.com"
39
38
  },
40
- "version": "0.1.0"
39
+ "version": "0.1.2"
41
40
  },
42
41
  "dependencies": {
43
- "@idosgames/core": "0.19.0",
44
- "@idosgames/module-sdk": "0.6.0",
45
- "@idosgames/react": "0.3.0",
42
+ "@idosgames/core": "0.19.1",
43
+ "@idosgames/module-sdk": "0.8.0",
44
+ "@idosgames/react": "0.4.0",
46
45
  "react": "19.2.7"
47
46
  },
48
- "contentHash": "8708fd1f761188580603bd1e2cca47209c2d618a9c82a5530cca9c083bca19e6",
47
+ "contentHash": "25a1e02d58fb773f2c26574d6985ffca501001350497cac8f8a067774914e490",
49
48
  "files": [
50
49
  {
51
50
  "path": "i18n.ts",
@@ -61,11 +60,11 @@
61
60
  },
62
61
  {
63
62
  "path": "WorkshopApp.tsx",
64
- "content": "import {\n useCallback,\n useEffect,\n useState,\n type ComponentType,\n type CSSProperties,\n type ReactNode,\n} from \"react\";\nimport type {\n WorkshopAccessOption,\n WorkshopAccessOptionInput,\n WorkshopBrowseQuery,\n WorkshopContentResponse,\n WorkshopContentView,\n WorkshopDefinitionsResponse,\n SocialReportReason,\n WorkshopVisibility,\n} from \"@idosgames/core\";\nimport type {\n ContentRegistry,\n ContentTypeHandler,\n FeatureScreenProps,\n IDosGamesClient,\n} from \"@idosgames/module-sdk\";\n\n// The Workshop screen: catalog, content card, publish wizard, \"mine / licenses / favorites\".\n//\n// It is the same for every game. Everything game-specific comes from two places: the title's Workshop\n// config (which types exist, formats, access modes — read via client.workshop.getDefinitions()) and the\n// handlers games register in ctx.content (how to list, capture and open their content). This file is\n// plain editable React with inline styles — restyle or replace it like any other module source.\n\n/** What the panel needs from the host — the module passes it in at setup(). */\nexport interface WorkshopHost {\n client: IDosGamesClient;\n content: ContentRegistry;\n navigate(modeId: string): void;\n}\n\n/** The Workshop as a tab of the lobby (a feature screen); `navigate` hands the screen to a game. */\nexport function makeWorkshopScreen(\n host: WorkshopHost,\n): ComponentType<FeatureScreenProps> {\n return function WorkshopScreen(): ReactNode {\n return <WorkshopApp host={host} />;\n };\n}\n\ntype Tab = \"catalog\" | \"publish\" | \"mine\" | \"licenses\" | \"favorites\";\n\nconst TABS: Array<[Tab, string]> = [\n [\"catalog\", \"Catalog\"],\n [\"publish\", \"Publish\"],\n [\"mine\", \"My content\"],\n [\"licenses\", \"My library\"],\n [\"favorites\", \"Favorites\"],\n];\n\n/** Server error codes → words. Anything else is shown as is (it is already a sentence). */\nconst ERRORS: Record<string, string> = {\n WORKSHOP_DISABLED: \"The Workshop is turned off.\",\n WORKSHOP_NOT_CONFIGURED: \"The Workshop is not set up in this game yet.\",\n WORKSHOP_NOT_AVAILABLE: \"The Workshop is not available to you.\",\n WORKSHOP_CLOSED: \"The Workshop is closed right now.\",\n PRICE_CHANGED: \"The author changed the price — look at it again.\",\n HOLDING_REQUIREMENTS_NOT_MET: \"You don't hold what this option requires.\",\n ACCESS_DENIED: \"You don't have access to this yet.\",\n CONTENT_NOT_FOUND: \"Not found (or not shared with you).\",\n CONTENT_NOT_AVAILABLE: \"This publication is not available now.\",\n CONTENT_TEXT_REJECTED:\n \"The title or description contains words that are not allowed.\",\n PUBLISH_LIMIT_REACHED:\n \"You have reached the limit of publications of this type.\",\n DAILY_PUBLISH_LIMIT_REACHED: \"You have reached today's publishing limit.\",\n PUBLISH_NOT_ALLOWED: \"You can't publish this type of content yet.\",\n CANNOT_LIKE_OWN_CONTENT: \"You can't like your own publication.\",\n WORKSHOP_STORAGE_NOT_CONFIGURED:\n \"File storage is not configured for this game.\",\n TOO_MANY_PENDING_UPLOADS:\n \"You have too many unfinished uploads — try again a bit later.\",\n ACCESS_REQUIRED: \"Add at least one way for others to get it.\",\n OPTION_REQUIRED: \"Choose how you want to get it.\",\n PRICE_NO_LONGER_ALLOWED: \"This price is no longer allowed in this game.\",\n TITLE_REQUIRED: \"Give it a title.\",\n TITLE_TOO_LONG: \"The title is too long.\",\n THUMBNAIL_REQUIRED: \"This type of content needs a preview image.\",\n FILE_TOO_LARGE: \"The file is too large for this type of content.\",\n FILE_TYPE_MISMATCH: \"The file does not match its declared format.\",\n CONTENT_TYPE_NOT_ALLOWED:\n \"This type of content can't be published in this game.\",\n CANNOT_REPORT_OWN_CONTENT: \"You can't report your own publication.\",\n CANNOT_FOLLOW_SELF: \"You can't follow yourself.\",\n};\nconst errorText = (e: string): string => ERRORS[e] ?? e;\n\nexport function WorkshopApp({ host }: { host: WorkshopHost }): ReactNode {\n const [defs, setDefs] = useState<WorkshopDefinitionsResponse | null>(null);\n const [error, setError] = useState<string | null>(null);\n const [tab, setTab] = useState<Tab>(\"catalog\");\n const [openID, setOpenID] = useState<string | null>(null);\n\n useEffect(() => {\n let alive = true;\n void host.client.workshop.getDefinitions().then((r) => {\n if (!alive) return;\n if (r.ok) setDefs(r.data);\n else setError(errorText(r.error));\n });\n return () => {\n alive = false;\n };\n }, [host]);\n\n if (!defs) return <Frame>{error ?? \"Loading the Workshop…\"}</Frame>;\n if (!defs.Definitions?.Enabled || !defs.GatePassed)\n return <Frame>The Workshop is not available in this game right now.</Frame>;\n\n return (\n <Frame>\n <div style={tabsRow}>\n {TABS.map(([id, label]) => (\n <button\n key={id}\n style={id === tab ? tabActive : tabBtn}\n onClick={() => setTab(id)}\n >\n {label}\n </button>\n ))}\n </div>\n {tab === \"catalog\" && (\n <Catalog host={host} defs={defs} onOpen={setOpenID} />\n )}\n {tab === \"publish\" && (\n <PublishWizard\n host={host}\n defs={defs}\n onDone={(id) => {\n setTab(\"mine\");\n setOpenID(id);\n }}\n />\n )}\n {tab === \"mine\" && <MyList host={host} kind=\"mine\" onOpen={setOpenID} />}\n {tab === \"licenses\" && (\n <MyList host={host} kind=\"licenses\" onOpen={setOpenID} />\n )}\n {tab === \"favorites\" && (\n <MyList host={host} kind=\"favorites\" onOpen={setOpenID} />\n )}\n {openID && (\n <ContentDetails\n host={host}\n contentID={openID}\n onClose={() => setOpenID(null)}\n />\n )}\n </Frame>\n );\n}\n\n// ────────────────────────────── Catalog ──────────────────────────────\n\nfunction Catalog({\n host,\n defs,\n onOpen,\n}: {\n host: WorkshopHost;\n defs: WorkshopDefinitionsResponse;\n onOpen(id: string): void;\n}): ReactNode {\n const handlers = useContentTypes(host.content);\n const [query, setQuery] = useState<WorkshopBrowseQuery>({ sort: \"New\" });\n const [collection, setCollection] = useState<string | null>(null);\n const [items, setItems] = useState<WorkshopContentView[]>([]);\n const [cursor, setCursor] = useState<string | null>(null);\n const [busy, setBusy] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const load = useCallback(\n async (more: boolean) => {\n setBusy(true);\n setError(null);\n if (collection) {\n const r = await host.client.workshop.getCollection(collection);\n if (r.ok) {\n setItems(r.data.Items ?? []);\n setCursor(null);\n } else setError(errorText(r.error));\n } else {\n const r = await host.client.workshop.browse({\n ...query,\n pageSize: 24,\n continuationToken: more ? (cursor ?? undefined) : undefined,\n });\n if (r.ok) {\n setItems((prev) =>\n more ? [...prev, ...(r.data.Items ?? [])] : (r.data.Items ?? []),\n );\n setCursor(r.data.ContinuationToken ?? null);\n } else setError(errorText(r.error));\n }\n setBusy(false);\n },\n [host, query, collection, cursor],\n );\n\n // Reload from the first page whenever the filter changes (not when the cursor does).\n useEffect(() => {\n void load(false);\n }, [query, collection]);\n\n const types = Object.entries(defs.Definitions?.ContentTypes ?? {}).filter(\n ([, t]) => t.Enabled !== false,\n );\n\n return (\n <div>\n {(defs.Collections?.length ?? 0) > 0 && (\n <div style={chipsRow}>\n <button\n style={collection === null ? chipActive : chip}\n onClick={() => setCollection(null)}\n >\n All\n </button>\n {defs.Collections?.map((c) => (\n <button\n key={c.CollectionID ?? \"\"}\n style={collection === c.CollectionID ? chipActive : chip}\n onClick={() => setCollection(c.CollectionID ?? null)}\n >\n ★ {c.Name ?? c.CollectionID}\n </button>\n ))}\n </div>\n )}\n {!collection && (\n <div style={filtersRow}>\n <select\n style={input}\n value={query.contentType ?? \"\"}\n onChange={(e) =>\n setQuery({ ...query, contentType: e.target.value || undefined })\n }\n >\n <option value=\"\">All types</option>\n {types.map(([id, t]) => (\n <option key={id} value={id}>\n {handlers.find((h) => h.type === id)?.label ??\n t.DisplayName ??\n id}\n </option>\n ))}\n </select>\n <select\n style={input}\n value={query.sort ?? \"New\"}\n onChange={(e) =>\n setQuery({\n ...query,\n sort: e.target.value as WorkshopBrowseQuery[\"sort\"],\n })\n }\n >\n <option value=\"New\">Newest</option>\n <option value=\"Popular\">Most acquired</option>\n <option value=\"MostLiked\">Most liked</option>\n </select>\n <input\n style={input}\n placeholder=\"Tag\"\n defaultValue={query.tag ?? \"\"}\n onKeyDown={(e) => {\n if (e.key === \"Enter\")\n setQuery({\n ...query,\n tag: (e.target as HTMLInputElement).value.trim() || undefined,\n });\n }}\n />\n <label style={checkLabel}>\n <input\n type=\"checkbox\"\n checked={query.fromFollowing === true}\n onChange={(e) =>\n setQuery({\n ...query,\n fromFollowing: e.target.checked || undefined,\n })\n }\n />\n From authors I follow\n </label>\n </div>\n )}\n {error && <div style={errorBox}>{error}</div>}\n {items.length === 0 && !busy && (\n <div style={muted}>Nothing here yet.</div>\n )}\n <div style={grid}>\n {items.map((item) => (\n <ContentCard\n key={item.ContentID ?? \"\"}\n item={item}\n handlers={handlers}\n onClick={() => item.ContentID && onOpen(item.ContentID)}\n />\n ))}\n </div>\n {cursor && (\n <button\n style={secondaryBtn}\n disabled={busy}\n onClick={() => void load(true)}\n >\n {busy ? \"Loading…\" : \"Show more\"}\n </button>\n )}\n </div>\n );\n}\n\nfunction ContentCard({\n item,\n handlers,\n onClick,\n}: {\n item: WorkshopContentView;\n handlers: ContentTypeHandler[];\n onClick(): void;\n}): ReactNode {\n const handler = handlers.find((h) => h.type === item.ContentType);\n return (\n <button style={card} onClick={onClick}>\n <div style={thumbBox}>\n {item.ThumbnailUrl ? (\n <img src={item.ThumbnailUrl} alt=\"\" style={thumbImg} />\n ) : (\n <span style={{ fontSize: 34 }}>{handler?.icon ?? \"📦\"}</span>\n )}\n </div>\n <div style={cardTitle}>\n {item.Title ||\n (item.Status === \"Uploading\" ? \"Unfinished upload\" : \"Untitled\")}\n </div>\n <div style={cardMeta}>\n {item.IsOfficial\n ? \"Official\"\n : (item.CreatorPublicData?.Username ?? \"Player\")}{\" \"}\n · ♥ {item.Stats?.Likes ?? 0}\n </div>\n <div style={badgesRow}>\n {item.IsMine ? (\n <span style={badgeOwned}>Yours</span>\n ) : item.Owned ? (\n <span style={badgeOwned}>In library</span>\n ) : (\n (item.Access ?? []).map((o) => (\n <span key={o.OptionID ?? \"\"} style={badge}>\n {accessLabel(o)}\n </span>\n ))\n )}\n {item.Status && item.Status !== \"Published\" && (\n <span style={badgeWarn}>{item.Status}</span>\n )}\n </div>\n </button>\n );\n}\n\n// ────────────────────────────── Details ──────────────────────────────\n\nconst REPORT_REASONS: SocialReportReason[] = [\n \"Inappropriate\",\n \"Spam\",\n \"Stolen\",\n \"Broken\",\n \"Harassment\",\n \"Other\",\n];\n\nfunction ContentDetails({\n host,\n contentID,\n onClose,\n}: {\n host: WorkshopHost;\n contentID: string;\n onClose(): void;\n}): ReactNode {\n const [data, setData] = useState<WorkshopContentResponse | null>(null);\n const [busy, setBusy] = useState<string | null>(null);\n const [message, setMessage] = useState<string | null>(null);\n const [following, setFollowing] = useState<boolean | null>(null);\n const [reportReason, setReportReason] =\n useState<SocialReportReason>(\"Inappropriate\");\n\n const reload = useCallback(async () => {\n const r = await host.client.workshop.getContent(contentID);\n if (!r.ok) {\n setMessage(errorText(r.error));\n return;\n }\n setData(r.data);\n // Following the author is a social-layer edge on the PLAYER, not part of the card.\n const creator = r.data.Content?.CreatorUserID;\n if (creator && !r.data.Content?.IsMine) {\n const s = await host.client.social.getEntityStates(\"User\", [creator]);\n if (s.ok) setFollowing(s.data.Items?.[0]?.Following === true);\n }\n }, [host, contentID]);\n\n useEffect(() => {\n void reload();\n }, [reload]);\n\n const view = data?.Content;\n const handler = view?.ContentType\n ? host.content.getType(view.ContentType)\n : undefined;\n\n const run = async (\n label: string,\n work: () => Promise<string | null>,\n ): Promise<void> => {\n setBusy(label);\n setMessage(null);\n try {\n setMessage(await work());\n } catch (e) {\n setMessage(e instanceof Error ? e.message : String(e));\n } finally {\n setBusy(null);\n }\n };\n\n const open = (): Promise<void> =>\n run(\"open\", async () => {\n if (!view?.ContentID) return null;\n if (!handler?.open)\n return \"This game can't open this type of content here.\";\n const r = await host.client.workshop.downloadFiles(view.ContentID);\n if (!r.ok) return errorText(r.error);\n await handler.open({\n contentID: view.ContentID,\n title: view.Title,\n revision: view.Revision,\n files: r.data.files,\n });\n if (handler.modeId) host.navigate(handler.modeId);\n return null;\n });\n\n const acquire = (option: WorkshopAccessOption): Promise<void> =>\n run(`get:${option.OptionID}`, async () => {\n const r = await host.client.workshop.acquire(contentID, option);\n if (!r.ok) return errorText(r.error);\n await reload();\n return r.data.AlreadyOwned\n ? \"Already in your library.\"\n : \"Added to your library.\";\n });\n\n if (!view) return <Modal onClose={onClose}>{message ?? \"Loading…\"}</Modal>;\n\n const states = new Map(\n (data?.AccessState ?? []).map((s) => [\n s.OptionID ?? \"\",\n s.Available !== false,\n ]),\n );\n const canOpen = Boolean(data?.CanDownload);\n\n return (\n <Modal onClose={onClose}>\n <div style={detailsHead}>\n <div style={detailsThumb}>\n {view.ThumbnailUrl ? (\n <img src={view.ThumbnailUrl} alt=\"\" style={thumbImg} />\n ) : (\n <span style={{ fontSize: 48 }}>{handler?.icon ?? \"📦\"}</span>\n )}\n </div>\n <div style={{ minWidth: 0 }}>\n <h2 style={{ margin: \"0 0 6px\" }}>{view.Title}</h2>\n <div style={muted}>\n {view.IsOfficial\n ? \"Official content\"\n : `by ${view.CreatorPublicData?.Username ?? \"a player\"}`}{\" \"}\n · {handler?.label ?? view.ContentType} · rev. {view.Revision}\n </div>\n <div style={muted}>\n ♥ {view.Stats?.Likes ?? 0} · ★ {view.Stats?.Favorites ?? 0} · ⬇{\" \"}\n {view.Stats?.Acquisitions ?? 0}\n {view.TotalBytes ? ` · ${formatBytes(view.TotalBytes)}` : \"\"}\n </div>\n {(view.Tags?.length ?? 0) > 0 && (\n <div style={badgesRow}>\n {view.Tags?.map((t) => (\n <span key={t} style={badge}>\n #{t}\n </span>\n ))}\n </div>\n )}\n </div>\n </div>\n\n {view.Description && (\n <p style={{ whiteSpace: \"pre-wrap\" }}>{view.Description}</p>\n )}\n {view.IsMine && view.ModerationNote && (\n <div style={errorBox}>Moderation: {view.ModerationNote}</div>\n )}\n {view.IsMine && (view.Access?.length ?? 0) > 0 && (\n <div style={muted}>\n Others get it: {(view.Access ?? []).map(accessLabel).join(\" · \")}\n </div>\n )}\n\n <div style={actionsCol}>\n {canOpen ? (\n <button\n style={primaryBtn}\n disabled={busy !== null || !handler?.open}\n onClick={() => void open()}\n >\n {busy === \"open\"\n ? \"Opening…\"\n : handler?.open\n ? \"Open\"\n : \"Owned (open it in the game)\"}\n </button>\n ) : (\n (view.Access ?? []).map((o) => {\n const available = states.get(o.OptionID ?? \"\") ?? true;\n return (\n <button\n key={o.OptionID ?? \"\"}\n style={available ? primaryBtn : disabledBtn}\n disabled={!available || busy !== null}\n title={\n available\n ? undefined\n : \"You don't meet this option's requirements\"\n }\n onClick={() => void acquire(o)}\n >\n {busy === `get:${o.OptionID}` ? \"…\" : `Get — ${accessLabel(o)}`}\n </button>\n );\n })\n )}\n </div>\n\n <div style={filtersRow}>\n {!view.IsMine && (\n <button\n style={secondaryBtn}\n disabled={busy !== null}\n onClick={() =>\n void run(\"like\", async () => {\n const r = view.Liked\n ? await host.client.social.unlike(\"WorkshopItem\", contentID)\n : await host.client.social.like(\"WorkshopItem\", contentID);\n if (!r.ok) return errorText(r.error);\n await reload();\n return null;\n })\n }\n >\n {view.Liked ? \"♥ Liked\" : \"♡ Like\"}\n </button>\n )}\n <button\n style={secondaryBtn}\n disabled={busy !== null}\n onClick={() =>\n void run(\"fav\", async () => {\n const r = view.Favorited\n ? await host.client.social.unfavorite(\"WorkshopItem\", contentID)\n : await host.client.social.favorite(\"WorkshopItem\", contentID);\n if (!r.ok) return errorText(r.error);\n await reload();\n return null;\n })\n }\n >\n {view.Favorited ? \"★ In favorites\" : \"☆ Favorite\"}\n </button>\n {!view.IsMine && view.CreatorUserID && (\n <button\n style={secondaryBtn}\n disabled={busy !== null}\n onClick={() =>\n void run(\"follow\", async () => {\n const creator = view.CreatorUserID ?? \"\";\n const r = following\n ? await host.client.social.unfollow(\"User\", creator)\n : await host.client.social.follow(\"User\", creator);\n if (!r.ok) return errorText(r.error);\n setFollowing(r.data.Following === true);\n return r.data.Following ? \"You follow this author.\" : null;\n })\n }\n >\n {following ? \"Following ✓\" : \"Follow author\"}\n </button>\n )}\n {view.IsMine && view.Status !== \"Removed\" && (\n <button\n style={dangerBtn}\n disabled={busy !== null}\n onClick={() => {\n if (\n !confirm(\n \"Unpublish for good? Players who already have it keep it.\",\n )\n )\n return;\n void run(\"unpublish\", async () => {\n const r = await host.client.workshop.unpublish(contentID);\n if (!r.ok) return errorText(r.error);\n await reload();\n return \"Unpublished.\";\n });\n }}\n >\n Unpublish\n </button>\n )}\n </div>\n\n {!view.IsMine && (\n <div style={filtersRow}>\n <select\n style={input}\n value={reportReason}\n onChange={(e) =>\n setReportReason(e.target.value as SocialReportReason)\n }\n >\n {REPORT_REASONS.map((r) => (\n <option key={r} value={r}>\n {r}\n </option>\n ))}\n </select>\n <button\n style={secondaryBtn}\n disabled={busy !== null}\n onClick={() =>\n void run(\"report\", async () => {\n const r = await host.client.social.report(\n \"WorkshopItem\",\n contentID,\n reportReason,\n );\n if (!r.ok) return errorText(r.error);\n return r.data.AlreadyReported\n ? \"You already reported this.\"\n : \"Thanks — the publisher will review it.\";\n })\n }\n >\n Report\n </button>\n </div>\n )}\n\n {message && <div style={noticeBox}>{message}</div>}\n </Modal>\n );\n}\n\n// ────────────────────────────── Publish ──────────────────────────────\n\ninterface AccessDraft {\n mode: \"Free\" | \"Price\" | \"Holding\";\n resource: string; // \"vc:GOLD\" | \"item:<catalog>/<item>\"\n amount: number;\n holdMode: \"WhileHeld\" | \"UnlockOnce\";\n}\n\nfunction PublishWizard({\n host,\n defs,\n onDone,\n}: {\n host: WorkshopHost;\n defs: WorkshopDefinitionsResponse;\n onDone(contentID: string): void;\n}): ReactNode {\n const handlers = useContentTypes(host.content).filter(\n (h) => h.listLocal && h.capture && defs.CanPublish?.[h.type] === true,\n );\n const [type, setType] = useState<string | null>(null);\n const [locals, setLocals] = useState<Array<{\n id: string;\n name: string;\n subtitle?: string;\n }> | null>(null);\n const [localId, setLocalId] = useState<string | null>(null);\n const [title, setTitle] = useState(\"\");\n const [description, setDescription] = useState(\"\");\n const [tags, setTags] = useState(\"\");\n const [visibility, setVisibility] = useState<WorkshopVisibility>(\"Public\");\n const [access, setAccess] = useState<AccessDraft[]>([\n { mode: \"Free\", resource: \"\", amount: 1, holdMode: \"UnlockOnce\" },\n ]);\n const [busy, setBusy] = useState(false);\n const [message, setMessage] = useState<string | null>(null);\n\n const handler = handlers.find((h) => h.type === type);\n const typeDef = type ? defs.Definitions?.ContentTypes?.[type] : undefined;\n const allowedModes = typeDef?.AllowedAccessModes?.length\n ? typeDef.AllowedAccessModes\n : [\"Free\", \"Price\", \"Holding\"];\n const resources = useResourceOptions(host.client);\n // Плата за публикацию берётся только ресурсами: вариант с оплатой в сторе сервер отвергнет.\n const fee = Object.entries(typeDef?.PublishFeeOptions ?? {}).find(\n ([, option]) =>\n !(option?.Cost?.Standard?.Entries ?? []).some(\n (e) => e?.Type === \"Purchase\",\n ),\n );\n\n useEffect(() => {\n setLocals(null);\n setLocalId(null);\n if (!handler?.listLocal) return;\n void handler\n .listLocal()\n .then(setLocals, (e: unknown) =>\n setMessage(e instanceof Error ? e.message : String(e)),\n );\n }, [handler]);\n\n if (handlers.length === 0)\n return (\n <div style={muted}>\n Nothing to publish from here: the games in this project either do not\n register their content, or you can't publish it yet.\n </div>\n );\n\n const publish = async (): Promise<void> => {\n if (!handler?.capture || !type || !localId) return;\n // Опция без ресурса молча выпала бы из списка, и публикация ушла бы не с теми способами получить.\n if (access.some((a) => a.mode !== \"Free\" && !a.resource)) {\n setMessage(\"Pick a resource for every paid or hold-to-unlock option.\");\n return;\n }\n setBusy(true);\n setMessage(null);\n try {\n const captured = await handler.capture(localId);\n const r = await host.client.workshop.publish({\n contentType: type,\n files: captured.files,\n thumbnail: captured.thumbnail,\n title: title.trim() || captured.suggestedTitle || \"Untitled\",\n description: description.trim() || captured.suggestedDescription,\n tags: tags\n .split(\",\")\n .map((t) => t.trim())\n .filter(Boolean)\n .concat(captured.tags ?? []),\n metadata: captured.metadata,\n visibility,\n access: access\n .map(toAccessInput)\n .filter((a): a is WorkshopAccessOptionInput => a !== null),\n selectedFeeOptionID: fee?.[0],\n });\n if (!r.ok) setMessage(errorText(r.error));\n else if (r.data.Content?.ContentID) onDone(r.data.Content.ContentID);\n } catch (e) {\n setMessage(e instanceof Error ? e.message : String(e));\n } finally {\n setBusy(false);\n }\n };\n\n return (\n <div style={formCol}>\n <label style={fieldLabel}>What</label>\n <div style={chipsRow}>\n {handlers.map((h) => (\n <button\n key={h.type}\n style={type === h.type ? chipActive : chip}\n onClick={() => setType(h.type)}\n >\n {h.icon} {h.label}\n </button>\n ))}\n </div>\n\n {handler && (\n <>\n <label style={fieldLabel}>Which one</label>\n {!locals ? (\n <div style={muted}>Loading…</div>\n ) : locals.length === 0 ? (\n <div style={muted}>You have nothing of this type yet.</div>\n ) : (\n <div style={formCol}>\n {locals.map((l) => (\n <label key={l.id} style={checkLabel}>\n <input\n type=\"radio\"\n name=\"wsLocal\"\n checked={localId === l.id}\n onChange={() => {\n setLocalId(l.id);\n if (!title) setTitle(l.name);\n }}\n />\n {l.name}{\" \"}\n {l.subtitle && <span style={muted}>· {l.subtitle}</span>}\n </label>\n ))}\n </div>\n )}\n </>\n )}\n\n {localId && (\n <>\n <label style={fieldLabel}>Title</label>\n <input\n style={input}\n value={title}\n maxLength={defs.Definitions?.Limits?.MaxTitleLength ?? 60}\n onChange={(e) => setTitle(e.target.value)}\n />\n <label style={fieldLabel}>Description</label>\n <textarea\n style={{ ...input, minHeight: 70 }}\n value={description}\n onChange={(e) => setDescription(e.target.value)}\n />\n <label style={fieldLabel}>\n Tags (comma separated\n {typeDef?.TagVocabulary?.length\n ? `: ${typeDef.TagVocabulary.join(\", \")}`\n : \"\"}\n )\n </label>\n <input\n style={input}\n value={tags}\n onChange={(e) => setTags(e.target.value)}\n />\n <label style={fieldLabel}>Who can see it</label>\n <select\n style={input}\n value={visibility}\n onChange={(e) =>\n setVisibility(e.target.value as WorkshopVisibility)\n }\n >\n <option value=\"Public\">Everyone (in the catalog)</option>\n <option value=\"Unlisted\">Anyone with the link</option>\n <option value=\"Friends\">Only my friends</option>\n </select>\n\n <label style={fieldLabel}>How others get it — any option works</label>\n {access.map((a, i) => (\n <div key={i} style={filtersRow}>\n <select\n style={input}\n value={a.mode}\n onChange={(e) =>\n setAccess(\n patch(access, i, {\n mode: e.target.value as AccessDraft[\"mode\"],\n }),\n )\n }\n >\n {allowedModes.map((m) => (\n <option key={m} value={m}>\n {m === \"Free\"\n ? \"Free\"\n : m === \"Price\"\n ? \"For resources\"\n : \"Hold to unlock\"}\n </option>\n ))}\n </select>\n {a.mode !== \"Free\" && (\n <>\n <select\n style={input}\n value={a.resource}\n onChange={(e) =>\n setAccess(patch(access, i, { resource: e.target.value }))\n }\n >\n <option value=\"\">— resource —</option>\n {resources\n .filter(\n (r) => a.mode === \"Holding\" || r.startsWith(\"vc:\"),\n )\n .map((r) => (\n <option key={r} value={r}>\n {r.replace(/^vc:/, \"\").replace(/^item:/, \"item \")}\n </option>\n ))}\n </select>\n <input\n style={{ ...input, width: 90 }}\n type=\"number\"\n min={1}\n value={a.amount}\n onChange={(e) =>\n setAccess(\n patch(access, i, {\n amount: Math.max(1, Number(e.target.value) || 1),\n }),\n )\n }\n />\n </>\n )}\n {a.mode === \"Holding\" && (\n <select\n style={input}\n value={a.holdMode}\n onChange={(e) =>\n setAccess(\n patch(access, i, {\n holdMode: e.target.value as AccessDraft[\"holdMode\"],\n }),\n )\n }\n >\n <option value=\"UnlockOnce\">Checked once, then forever</option>\n <option value=\"WhileHeld\">Only while they hold it</option>\n </select>\n )}\n {access.length > 1 && (\n <button\n style={secondaryBtn}\n onClick={() => setAccess(access.filter((_, j) => j !== i))}\n >\n ✕\n </button>\n )}\n </div>\n ))}\n <button\n style={secondaryBtn}\n onClick={() =>\n setAccess([\n ...access,\n {\n mode: allowedModes.includes(\"Price\") ? \"Price\" : \"Free\",\n resource: \"\",\n amount: 10,\n holdMode: \"UnlockOnce\",\n },\n ])\n }\n >\n + Add an option\n </button>\n\n {fee && (\n <div style={muted}>\n Publishing costs {bundleLabel(fee[1].Cost?.Standard)} (charged\n once).\n </div>\n )}\n <button\n style={primaryBtn}\n disabled={busy}\n onClick={() => void publish()}\n >\n {busy ? \"Publishing…\" : \"Publish\"}\n </button>\n </>\n )}\n {message && <div style={errorBox}>{message}</div>}\n </div>\n );\n}\n\nfunction patch<T>(list: T[], index: number, change: Partial<T>): T[] {\n return list.map((item, i) => (i === index ? { ...item, ...change } : item));\n}\n\nfunction toAccessInput(a: AccessDraft): WorkshopAccessOptionInput | null {\n if (a.mode === \"Free\") return { Mode: \"Free\" };\n if (!a.resource) return null;\n const [kind, id = \"\"] = a.resource.split(\":\", 2);\n if (a.mode === \"Price\") {\n return {\n Mode: \"Price\",\n Price: {\n Entries: [\n { Type: \"VirtualCurrency\", CurrencyID: id, Amount: a.amount },\n ],\n },\n };\n }\n const [catalogID, itemID] = id.split(\"/\", 2);\n return {\n Mode: \"Holding\",\n Holding: {\n Mode: a.holdMode,\n Match: \"All\",\n Requirements: [\n kind === \"vc\"\n ? { Type: \"VirtualCurrency\", CurrencyID: id, Amount: a.amount }\n : {\n Type: \"Item\",\n CatalogID: catalogID,\n ItemID: itemID ?? \"\",\n Amount: a.amount,\n },\n ],\n },\n };\n}\n\n// ────────────────────────────── Lists ──────────────────────────────\n\nfunction MyList({\n host,\n kind,\n onOpen,\n}: {\n host: WorkshopHost;\n kind: \"mine\" | \"licenses\" | \"favorites\";\n onOpen(id: string): void;\n}): ReactNode {\n const handlers = useContentTypes(host.content);\n const [items, setItems] = useState<WorkshopContentView[] | null>(null);\n const [error, setError] = useState<string | null>(null);\n\n useEffect(() => {\n let alive = true;\n const load = async (): Promise<void> => {\n const w = host.client.workshop;\n if (kind === \"licenses\") {\n const r = await w.getMyLicenses();\n if (!alive) return;\n if (r.ok)\n setItems(\n (r.data.Licenses ?? [])\n .map((l) => l.Content)\n .filter((c): c is WorkshopContentView => Boolean(c)),\n );\n else setError(errorText(r.error));\n return;\n }\n const r =\n kind === \"mine\" ? await w.getMyContent() : await w.getMyFavorites();\n if (!alive) return;\n if (r.ok) setItems(r.data.Items ?? []);\n else setError(errorText(r.error));\n };\n void load();\n return () => {\n alive = false;\n };\n }, [host, kind]);\n\n if (error) return <div style={errorBox}>{error}</div>;\n if (!items) return <div style={muted}>Loading…</div>;\n if (items.length === 0) return <div style={muted}>Empty.</div>;\n return (\n <div style={grid}>\n {items.map((item) => (\n <ContentCard\n key={item.ContentID ?? \"\"}\n item={item}\n handlers={handlers}\n onClick={() => item.ContentID && onOpen(item.ContentID)}\n />\n ))}\n </div>\n );\n}\n\n// ────────────────────────────── helpers ──────────────────────────────\n\n/**\n * Registered content types, re-read on every registry change. ⚠ Not keyed by the NUMBER of types: a game\n * re-installed after re-login registers the same type again with a new handler, the count stays the\n * same, and a count-based snapshot kept the handler of the destroyed game.\n */\nfunction useContentTypes(content: ContentRegistry): ContentTypeHandler[] {\n const [types, setTypes] = useState(() => content.listTypes());\n useEffect(() => {\n setTypes(content.listTypes());\n return content.subscribe(() => setTypes(content.listTypes()));\n }, [content]);\n return types;\n}\n\n/** \"vc:GOLD\" and \"item:<catalog>/<item>\" for every currency and item the title defines. */\nfunction useResourceOptions(client: IDosGamesClient): string[] {\n const [list] = useState(() => {\n const out: string[] = [];\n for (const id of Object.keys(\n client.data.config.currencyDefinitions?.VirtualCurrencies ?? {},\n ))\n out.push(`vc:${id}`);\n for (const [catalogID, catalog] of Object.entries(\n client.data.config.itemDefinitions?.Catalogs ?? {},\n ))\n for (const itemID of Object.keys(catalog?.Items ?? {}))\n out.push(`item:${catalogID}/${itemID}`);\n return out;\n });\n return list;\n}\n\ntype BundleLike =\n | {\n Entries?: Array<{\n CurrencyID?: string | null;\n ItemID?: string | null;\n Amount?: number | null;\n } | null> | null;\n }\n | null\n | undefined;\n\nfunction bundleLabel(bundle: BundleLike): string {\n const parts = (bundle?.Entries ?? [])\n .filter((e): e is NonNullable<typeof e> => Boolean(e))\n .map((e) => `${e.Amount ?? 0} ${e.CurrencyID ?? e.ItemID ?? \"\"}`.trim());\n return parts.length ? parts.join(\" + \") : \"free\";\n}\n\nfunction accessLabel(o: WorkshopAccessOption): string {\n if (o.Mode === \"Free\") return \"Free\";\n if (o.Mode === \"Price\") return bundleLabel(o.Price);\n const reqs = (o.Holding?.Requirements ?? []).map(\n (r) =>\n `${r.Amount ?? 0} ${r.CurrencyID ?? r.ItemID ?? \"\"}${r.MinLevel ? ` (lvl ${r.MinLevel}+)` : \"\"}`,\n );\n const joined = reqs.join(o.Holding?.Match === \"Any\" ? \" or \" : \" + \");\n return `🔑 hold ${joined}${o.Holding?.Mode === \"WhileHeld\" ? \" (while held)\" : \"\"}`;\n}\n\nfunction formatBytes(n: number): string {\n if (n < 1024) return `${n} B`;\n if (n < 1024 * 1024) return `${(n / 1024).toFixed(0)} KB`;\n return `${(n / 1024 / 1024).toFixed(1)} MB`;\n}\n\nfunction Frame({ children }: { children: ReactNode }): ReactNode {\n return <div style={frame}>{children}</div>;\n}\n\nfunction Modal({\n children,\n onClose,\n}: {\n children: ReactNode;\n onClose(): void;\n}): ReactNode {\n return (\n <div style={backdrop} onClick={onClose}>\n <div style={modal} onClick={(e) => e.stopPropagation()}>\n <button style={closeBtn} onClick={onClose} aria-label=\"Close\">\n ✕\n </button>\n {children}\n </div>\n </div>\n );\n}\n\n// ────────────────────────────── styles ──────────────────────────────\n\nconst frame: CSSProperties = {\n // A tab of the lobby: the lobby scrolls it and gives it the width.\n minHeight: 360,\n borderRadius: 16,\n padding: \"16px 20px 40px\",\n background: \"#12151c\",\n color: \"#e8e8ea\",\n fontFamily: \"system-ui, sans-serif\",\n pointerEvents: \"auto\",\n};\nconst tabsRow: CSSProperties = {\n display: \"flex\",\n gap: 6,\n flexWrap: \"wrap\",\n marginBottom: 14,\n};\nconst tabBtn: CSSProperties = {\n background: \"transparent\",\n color: \"#aab\",\n border: \"1px solid #2a2f3a\",\n borderRadius: 8,\n padding: \"6px 12px\",\n cursor: \"pointer\",\n};\nconst tabActive: CSSProperties = {\n ...tabBtn,\n background: \"#2d6cdf\",\n color: \"#fff\",\n border: \"1px solid #2d6cdf\",\n};\nconst chipsRow: CSSProperties = {\n display: \"flex\",\n gap: 6,\n flexWrap: \"wrap\",\n margin: \"8px 0\",\n};\nconst chip: CSSProperties = {\n ...tabBtn,\n borderRadius: 999,\n padding: \"4px 10px\",\n fontSize: 13,\n};\nconst chipActive: CSSProperties = {\n ...chip,\n background: \"#394a6b\",\n color: \"#fff\",\n};\nconst filtersRow: CSSProperties = {\n display: \"flex\",\n gap: 8,\n flexWrap: \"wrap\",\n alignItems: \"center\",\n margin: \"8px 0\",\n};\nconst input: CSSProperties = {\n background: \"#1b2029\",\n color: \"#e8e8ea\",\n border: \"1px solid #2a2f3a\",\n borderRadius: 6,\n padding: \"6px 8px\",\n font: \"inherit\",\n};\nconst checkLabel: CSSProperties = {\n display: \"flex\",\n gap: 6,\n alignItems: \"center\",\n fontSize: 14,\n};\nconst grid: CSSProperties = {\n display: \"grid\",\n gridTemplateColumns: \"repeat(auto-fill, minmax(170px, 1fr))\",\n gap: 12,\n};\nconst card: CSSProperties = {\n textAlign: \"left\",\n background: \"#1b2029\",\n border: \"1px solid #2a2f3a\",\n borderRadius: 10,\n padding: 8,\n color: \"inherit\",\n cursor: \"pointer\",\n font: \"inherit\",\n};\nconst thumbBox: CSSProperties = {\n aspectRatio: \"1 / 1\",\n borderRadius: 8,\n background: \"#0d1016\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n overflow: \"hidden\",\n};\nconst thumbImg: CSSProperties = {\n width: \"100%\",\n height: \"100%\",\n objectFit: \"cover\",\n imageRendering: \"pixelated\",\n};\nconst cardTitle: CSSProperties = {\n fontWeight: 600,\n margin: \"6px 0 2px\",\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n whiteSpace: \"nowrap\",\n};\nconst cardMeta: CSSProperties = { fontSize: 12, color: \"#8a90a0\" };\nconst badgesRow: CSSProperties = {\n display: \"flex\",\n gap: 4,\n flexWrap: \"wrap\",\n marginTop: 6,\n};\nconst badge: CSSProperties = {\n fontSize: 11,\n background: \"#263043\",\n borderRadius: 4,\n padding: \"2px 6px\",\n};\nconst badgeOwned: CSSProperties = { ...badge, background: \"#1f5134\" };\nconst badgeWarn: CSSProperties = { ...badge, background: \"#6b4a1f\" };\nconst muted: CSSProperties = { color: \"#8a90a0\", fontSize: 13 };\nconst errorBox: CSSProperties = {\n background: \"#3a1d22\",\n color: \"#ffb4b4\",\n borderRadius: 6,\n padding: \"8px 10px\",\n margin: \"8px 0\",\n};\nconst noticeBox: CSSProperties = {\n background: \"#1d2c3a\",\n borderRadius: 6,\n padding: \"8px 10px\",\n marginTop: 10,\n};\nconst primaryBtn: CSSProperties = {\n background: \"#2d6cdf\",\n color: \"#fff\",\n border: 0,\n borderRadius: 8,\n padding: \"9px 14px\",\n cursor: \"pointer\",\n font: \"inherit\",\n fontWeight: 600,\n};\nconst disabledBtn: CSSProperties = {\n ...primaryBtn,\n background: \"#3a3f4a\",\n color: \"#99a\",\n cursor: \"not-allowed\",\n};\nconst secondaryBtn: CSSProperties = { ...tabBtn, color: \"#dde\" };\nconst dangerBtn: CSSProperties = {\n ...tabBtn,\n color: \"#ff9d9d\",\n border: \"1px solid #5a2a30\",\n};\nconst actionsCol: CSSProperties = {\n display: \"flex\",\n flexDirection: \"column\",\n gap: 8,\n margin: \"12px 0\",\n};\nconst formCol: CSSProperties = {\n display: \"flex\",\n flexDirection: \"column\",\n gap: 6,\n maxWidth: 640,\n};\nconst fieldLabel: CSSProperties = { fontSize: 13, color: \"#aab\", marginTop: 8 };\nconst backdrop: CSSProperties = {\n position: \"fixed\",\n inset: 0,\n background: \"rgba(0,0,0,.6)\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n zIndex: 50,\n};\nconst modal: CSSProperties = {\n position: \"relative\",\n background: \"#171b23\",\n borderRadius: 12,\n padding: 20,\n width: \"min(640px, 94vw)\",\n maxHeight: \"90vh\",\n overflow: \"auto\",\n};\nconst closeBtn: CSSProperties = {\n position: \"absolute\",\n top: 10,\n right: 10,\n background: \"transparent\",\n color: \"#aab\",\n border: 0,\n fontSize: 18,\n cursor: \"pointer\",\n};\nconst detailsHead: CSSProperties = {\n display: \"flex\",\n gap: 14,\n alignItems: \"flex-start\",\n marginRight: 24,\n};\nconst detailsThumb: CSSProperties = {\n ...thumbBox,\n width: 120,\n flex: \"0 0 120px\",\n};\n"
63
+ "content": "import {\n useCallback,\n useEffect,\n useState,\n type ComponentType,\n type CSSProperties,\n type ReactNode,\n} from \"react\";\nimport type {\n WorkshopAccessOption,\n WorkshopAccessOptionInput,\n WorkshopBrowseQuery,\n WorkshopContentResponse,\n WorkshopContentView,\n WorkshopDefinitionsResponse,\n SocialReportReason,\n WorkshopVisibility,\n} from \"@idosgames/core\";\nimport type {\n ContentRegistry,\n ContentTypeHandler,\n FeatureScreenProps,\n IDosGamesClient,\n} from \"@idosgames/module-sdk\";\nimport { buttonStyle, panel, v } from \"@idosgames/react/ui\";\n\n// The Workshop screen: catalog, content card, publish wizard, \"mine / licenses / favorites\".\n//\n// It is the same for every game. Everything game-specific comes from two places: the title's Workshop\n// config (which types exist, formats, access modes — read via client.workshop.getDefinitions()) and the\n// handlers games register in ctx.content (how to list, capture and open their content). This file is\n// plain editable React with inline styles — restyle or replace it like any other module source.\n\n/** What the panel needs from the host — the module passes it in at setup(). */\nexport interface WorkshopHost {\n client: IDosGamesClient;\n content: ContentRegistry;\n navigate(modeId: string): void;\n}\n\n/** The Workshop as a tab of the lobby (a feature screen); `navigate` hands the screen to a game. */\nexport function makeWorkshopScreen(\n host: WorkshopHost,\n): ComponentType<FeatureScreenProps> {\n return function WorkshopScreen(): ReactNode {\n return <WorkshopApp host={host} />;\n };\n}\n\ntype Tab = \"catalog\" | \"publish\" | \"mine\" | \"licenses\" | \"favorites\";\n\nconst TABS: Array<[Tab, string]> = [\n [\"catalog\", \"Catalog\"],\n [\"publish\", \"Publish\"],\n [\"mine\", \"My content\"],\n [\"licenses\", \"My library\"],\n [\"favorites\", \"Favorites\"],\n];\n\n/** Server error codes → words. Anything else is shown as is (it is already a sentence). */\nconst ERRORS: Record<string, string> = {\n WORKSHOP_DISABLED: \"The Workshop is turned off.\",\n WORKSHOP_NOT_CONFIGURED: \"The Workshop is not set up in this game yet.\",\n WORKSHOP_NOT_AVAILABLE: \"The Workshop is not available to you.\",\n WORKSHOP_CLOSED: \"The Workshop is closed right now.\",\n PRICE_CHANGED: \"The author changed the price — look at it again.\",\n HOLDING_REQUIREMENTS_NOT_MET: \"You don't hold what this option requires.\",\n ACCESS_DENIED: \"You don't have access to this yet.\",\n CONTENT_NOT_FOUND: \"Not found (or not shared with you).\",\n CONTENT_NOT_AVAILABLE: \"This publication is not available now.\",\n CONTENT_TEXT_REJECTED:\n \"The title or description contains words that are not allowed.\",\n PUBLISH_LIMIT_REACHED:\n \"You have reached the limit of publications of this type.\",\n DAILY_PUBLISH_LIMIT_REACHED: \"You have reached today's publishing limit.\",\n PUBLISH_NOT_ALLOWED: \"You can't publish this type of content yet.\",\n CANNOT_LIKE_OWN_CONTENT: \"You can't like your own publication.\",\n WORKSHOP_STORAGE_NOT_CONFIGURED:\n \"File storage is not configured for this game.\",\n TOO_MANY_PENDING_UPLOADS:\n \"You have too many unfinished uploads — try again a bit later.\",\n ACCESS_REQUIRED: \"Add at least one way for others to get it.\",\n OPTION_REQUIRED: \"Choose how you want to get it.\",\n PRICE_NO_LONGER_ALLOWED: \"This price is no longer allowed in this game.\",\n TITLE_REQUIRED: \"Give it a title.\",\n TITLE_TOO_LONG: \"The title is too long.\",\n THUMBNAIL_REQUIRED: \"This type of content needs a preview image.\",\n FILE_TOO_LARGE: \"The file is too large for this type of content.\",\n FILE_TYPE_MISMATCH: \"The file does not match its declared format.\",\n CONTENT_TYPE_NOT_ALLOWED:\n \"This type of content can't be published in this game.\",\n CANNOT_REPORT_OWN_CONTENT: \"You can't report your own publication.\",\n CANNOT_FOLLOW_SELF: \"You can't follow yourself.\",\n};\nconst errorText = (e: string): string => ERRORS[e] ?? e;\n\nexport function WorkshopApp({ host }: { host: WorkshopHost }): ReactNode {\n const [defs, setDefs] = useState<WorkshopDefinitionsResponse | null>(null);\n const [error, setError] = useState<string | null>(null);\n const [tab, setTab] = useState<Tab>(\"catalog\");\n const [openID, setOpenID] = useState<string | null>(null);\n\n useEffect(() => {\n let alive = true;\n void host.client.workshop.getDefinitions().then((r) => {\n if (!alive) return;\n if (r.ok) setDefs(r.data);\n else setError(errorText(r.error));\n });\n return () => {\n alive = false;\n };\n }, [host]);\n\n if (!defs) return <Frame>{error ?? \"Loading the Workshop…\"}</Frame>;\n if (!defs.Definitions?.Enabled || !defs.GatePassed)\n return <Frame>The Workshop is not available in this game right now.</Frame>;\n\n return (\n <Frame>\n <div style={tabsRow}>\n {TABS.map(([id, label]) => (\n <button\n key={id}\n style={id === tab ? tabActive : tabBtn}\n onClick={() => setTab(id)}\n >\n {label}\n </button>\n ))}\n </div>\n {tab === \"catalog\" && (\n <Catalog host={host} defs={defs} onOpen={setOpenID} />\n )}\n {tab === \"publish\" && (\n <PublishWizard\n host={host}\n defs={defs}\n onDone={(id) => {\n setTab(\"mine\");\n setOpenID(id);\n }}\n />\n )}\n {tab === \"mine\" && <MyList host={host} kind=\"mine\" onOpen={setOpenID} />}\n {tab === \"licenses\" && (\n <MyList host={host} kind=\"licenses\" onOpen={setOpenID} />\n )}\n {tab === \"favorites\" && (\n <MyList host={host} kind=\"favorites\" onOpen={setOpenID} />\n )}\n {openID && (\n <ContentDetails\n host={host}\n contentID={openID}\n onClose={() => setOpenID(null)}\n />\n )}\n </Frame>\n );\n}\n\n// ────────────────────────────── Catalog ──────────────────────────────\n\nfunction Catalog({\n host,\n defs,\n onOpen,\n}: {\n host: WorkshopHost;\n defs: WorkshopDefinitionsResponse;\n onOpen(id: string): void;\n}): ReactNode {\n const handlers = useContentTypes(host.content);\n const [query, setQuery] = useState<WorkshopBrowseQuery>({ sort: \"New\" });\n const [collection, setCollection] = useState<string | null>(null);\n const [items, setItems] = useState<WorkshopContentView[]>([]);\n const [cursor, setCursor] = useState<string | null>(null);\n const [busy, setBusy] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const load = useCallback(\n async (more: boolean) => {\n setBusy(true);\n setError(null);\n if (collection) {\n const r = await host.client.workshop.getCollection(collection);\n if (r.ok) {\n setItems(r.data.Items ?? []);\n setCursor(null);\n } else setError(errorText(r.error));\n } else {\n const r = await host.client.workshop.browse({\n ...query,\n pageSize: 24,\n continuationToken: more ? (cursor ?? undefined) : undefined,\n });\n if (r.ok) {\n setItems((prev) =>\n more ? [...prev, ...(r.data.Items ?? [])] : (r.data.Items ?? []),\n );\n setCursor(r.data.ContinuationToken ?? null);\n } else setError(errorText(r.error));\n }\n setBusy(false);\n },\n [host, query, collection, cursor],\n );\n\n // Reload from the first page whenever the filter changes (not when the cursor does).\n useEffect(() => {\n void load(false);\n }, [query, collection]);\n\n const types = Object.entries(defs.Definitions?.ContentTypes ?? {}).filter(\n ([, t]) => t.Enabled !== false,\n );\n\n return (\n <div>\n {(defs.Collections?.length ?? 0) > 0 && (\n <div style={chipsRow}>\n <button\n style={collection === null ? chipActive : chip}\n onClick={() => setCollection(null)}\n >\n All\n </button>\n {defs.Collections?.map((c) => (\n <button\n key={c.CollectionID ?? \"\"}\n style={collection === c.CollectionID ? chipActive : chip}\n onClick={() => setCollection(c.CollectionID ?? null)}\n >\n ★ {c.Name ?? c.CollectionID}\n </button>\n ))}\n </div>\n )}\n {!collection && (\n <div style={filtersRow}>\n <select\n style={input}\n value={query.contentType ?? \"\"}\n onChange={(e) =>\n setQuery({ ...query, contentType: e.target.value || undefined })\n }\n >\n <option value=\"\">All types</option>\n {types.map(([id, t]) => (\n <option key={id} value={id}>\n {handlers.find((h) => h.type === id)?.label ??\n t.DisplayName ??\n id}\n </option>\n ))}\n </select>\n <select\n style={input}\n value={query.sort ?? \"New\"}\n onChange={(e) =>\n setQuery({\n ...query,\n sort: e.target.value as WorkshopBrowseQuery[\"sort\"],\n })\n }\n >\n <option value=\"New\">Newest</option>\n <option value=\"Popular\">Most acquired</option>\n <option value=\"MostLiked\">Most liked</option>\n </select>\n <input\n style={input}\n placeholder=\"Tag\"\n defaultValue={query.tag ?? \"\"}\n onKeyDown={(e) => {\n if (e.key === \"Enter\")\n setQuery({\n ...query,\n tag: (e.target as HTMLInputElement).value.trim() || undefined,\n });\n }}\n />\n <label style={checkLabel}>\n <input\n type=\"checkbox\"\n checked={query.fromFollowing === true}\n onChange={(e) =>\n setQuery({\n ...query,\n fromFollowing: e.target.checked || undefined,\n })\n }\n />\n From authors I follow\n </label>\n </div>\n )}\n {error && <div style={errorBox}>{error}</div>}\n {items.length === 0 && !busy && (\n <div style={muted}>Nothing here yet.</div>\n )}\n <div style={grid}>\n {items.map((item) => (\n <ContentCard\n key={item.ContentID ?? \"\"}\n item={item}\n handlers={handlers}\n onClick={() => item.ContentID && onOpen(item.ContentID)}\n />\n ))}\n </div>\n {cursor && (\n <button\n style={secondaryBtn}\n disabled={busy}\n onClick={() => void load(true)}\n >\n {busy ? \"Loading…\" : \"Show more\"}\n </button>\n )}\n </div>\n );\n}\n\nfunction ContentCard({\n item,\n handlers,\n onClick,\n}: {\n item: WorkshopContentView;\n handlers: ContentTypeHandler[];\n onClick(): void;\n}): ReactNode {\n const handler = handlers.find((h) => h.type === item.ContentType);\n return (\n <button style={card} onClick={onClick}>\n <div style={thumbBox}>\n {item.ThumbnailUrl ? (\n <img src={item.ThumbnailUrl} alt=\"\" style={thumbImg} />\n ) : (\n <span style={{ fontSize: 34 }}>{handler?.icon ?? \"📦\"}</span>\n )}\n </div>\n <div style={cardTitle}>\n {item.Title ||\n (item.Status === \"Uploading\" ? \"Unfinished upload\" : \"Untitled\")}\n </div>\n <div style={cardMeta}>\n {item.IsOfficial\n ? \"Official\"\n : (item.CreatorPublicData?.Username ?? \"Player\")}{\" \"}\n · ♥ {item.Stats?.Likes ?? 0}\n </div>\n <div style={badgesRow}>\n {item.IsMine ? (\n <span style={badgeOwned}>Yours</span>\n ) : item.Owned ? (\n <span style={badgeOwned}>In library</span>\n ) : (\n (item.Access ?? []).map((o) => (\n <span key={o.OptionID ?? \"\"} style={badge}>\n {accessLabel(o)}\n </span>\n ))\n )}\n {item.Status && item.Status !== \"Published\" && (\n <span style={badgeWarn}>{item.Status}</span>\n )}\n </div>\n </button>\n );\n}\n\n// ────────────────────────────── Details ──────────────────────────────\n\nconst REPORT_REASONS: SocialReportReason[] = [\n \"Inappropriate\",\n \"Spam\",\n \"Stolen\",\n \"Broken\",\n \"Harassment\",\n \"Other\",\n];\n\nfunction ContentDetails({\n host,\n contentID,\n onClose,\n}: {\n host: WorkshopHost;\n contentID: string;\n onClose(): void;\n}): ReactNode {\n const [data, setData] = useState<WorkshopContentResponse | null>(null);\n const [busy, setBusy] = useState<string | null>(null);\n const [message, setMessage] = useState<string | null>(null);\n const [following, setFollowing] = useState<boolean | null>(null);\n const [reportReason, setReportReason] =\n useState<SocialReportReason>(\"Inappropriate\");\n\n const reload = useCallback(async () => {\n const r = await host.client.workshop.getContent(contentID);\n if (!r.ok) {\n setMessage(errorText(r.error));\n return;\n }\n setData(r.data);\n // Following the author is a social-layer edge on the PLAYER, not part of the card.\n const creator = r.data.Content?.CreatorUserID;\n if (creator && !r.data.Content?.IsMine) {\n const s = await host.client.social.getEntityStates(\"User\", [creator]);\n if (s.ok) setFollowing(s.data.Items?.[0]?.Following === true);\n }\n }, [host, contentID]);\n\n useEffect(() => {\n void reload();\n }, [reload]);\n\n const view = data?.Content;\n const handler = view?.ContentType\n ? host.content.getType(view.ContentType)\n : undefined;\n\n const run = async (\n label: string,\n work: () => Promise<string | null>,\n ): Promise<void> => {\n setBusy(label);\n setMessage(null);\n try {\n setMessage(await work());\n } catch (e) {\n setMessage(e instanceof Error ? e.message : String(e));\n } finally {\n setBusy(null);\n }\n };\n\n const open = (): Promise<void> =>\n run(\"open\", async () => {\n if (!view?.ContentID) return null;\n if (!handler?.open)\n return \"This game can't open this type of content here.\";\n const r = await host.client.workshop.downloadFiles(view.ContentID);\n if (!r.ok) return errorText(r.error);\n await handler.open({\n contentID: view.ContentID,\n title: view.Title,\n revision: view.Revision,\n files: r.data.files,\n });\n if (handler.modeId) host.navigate(handler.modeId);\n return null;\n });\n\n const acquire = (option: WorkshopAccessOption): Promise<void> =>\n run(`get:${option.OptionID}`, async () => {\n const r = await host.client.workshop.acquire(contentID, option);\n if (!r.ok) return errorText(r.error);\n await reload();\n return r.data.AlreadyOwned\n ? \"Already in your library.\"\n : \"Added to your library.\";\n });\n\n if (!view) return <Modal onClose={onClose}>{message ?? \"Loading…\"}</Modal>;\n\n const states = new Map(\n (data?.AccessState ?? []).map((s) => [\n s.OptionID ?? \"\",\n s.Available !== false,\n ]),\n );\n const canOpen = Boolean(data?.CanDownload);\n\n return (\n <Modal onClose={onClose}>\n <div style={detailsHead}>\n <div style={detailsThumb}>\n {view.ThumbnailUrl ? (\n <img src={view.ThumbnailUrl} alt=\"\" style={thumbImg} />\n ) : (\n <span style={{ fontSize: 48 }}>{handler?.icon ?? \"📦\"}</span>\n )}\n </div>\n <div style={{ minWidth: 0 }}>\n <h2 style={{ margin: \"0 0 6px\" }}>{view.Title}</h2>\n <div style={muted}>\n {view.IsOfficial\n ? \"Official content\"\n : `by ${view.CreatorPublicData?.Username ?? \"a player\"}`}{\" \"}\n · {handler?.label ?? view.ContentType} · rev. {view.Revision}\n </div>\n <div style={muted}>\n ♥ {view.Stats?.Likes ?? 0} · ★ {view.Stats?.Favorites ?? 0} · ⬇{\" \"}\n {view.Stats?.Acquisitions ?? 0}\n {view.TotalBytes ? ` · ${formatBytes(view.TotalBytes)}` : \"\"}\n </div>\n {(view.Tags?.length ?? 0) > 0 && (\n <div style={badgesRow}>\n {view.Tags?.map((t) => (\n <span key={t} style={badge}>\n #{t}\n </span>\n ))}\n </div>\n )}\n </div>\n </div>\n\n {view.Description && (\n <p style={{ whiteSpace: \"pre-wrap\" }}>{view.Description}</p>\n )}\n {view.IsMine && view.ModerationNote && (\n <div style={errorBox}>Moderation: {view.ModerationNote}</div>\n )}\n {view.IsMine && (view.Access?.length ?? 0) > 0 && (\n <div style={muted}>\n Others get it: {(view.Access ?? []).map(accessLabel).join(\" · \")}\n </div>\n )}\n\n <div style={actionsCol}>\n {canOpen ? (\n <button\n style={primaryBtn}\n disabled={busy !== null || !handler?.open}\n onClick={() => void open()}\n >\n {busy === \"open\"\n ? \"Opening…\"\n : handler?.open\n ? \"Open\"\n : \"Owned (open it in the game)\"}\n </button>\n ) : (\n (view.Access ?? []).map((o) => {\n const available = states.get(o.OptionID ?? \"\") ?? true;\n return (\n <button\n key={o.OptionID ?? \"\"}\n style={available ? primaryBtn : disabledBtn}\n disabled={!available || busy !== null}\n title={\n available\n ? undefined\n : \"You don't meet this option's requirements\"\n }\n onClick={() => void acquire(o)}\n >\n {busy === `get:${o.OptionID}` ? \"…\" : `Get — ${accessLabel(o)}`}\n </button>\n );\n })\n )}\n </div>\n\n <div style={filtersRow}>\n {!view.IsMine && (\n <button\n style={secondaryBtn}\n disabled={busy !== null}\n onClick={() =>\n void run(\"like\", async () => {\n const r = view.Liked\n ? await host.client.social.unlike(\"WorkshopItem\", contentID)\n : await host.client.social.like(\"WorkshopItem\", contentID);\n if (!r.ok) return errorText(r.error);\n await reload();\n return null;\n })\n }\n >\n {view.Liked ? \"♥ Liked\" : \"♡ Like\"}\n </button>\n )}\n <button\n style={secondaryBtn}\n disabled={busy !== null}\n onClick={() =>\n void run(\"fav\", async () => {\n const r = view.Favorited\n ? await host.client.social.unfavorite(\"WorkshopItem\", contentID)\n : await host.client.social.favorite(\"WorkshopItem\", contentID);\n if (!r.ok) return errorText(r.error);\n await reload();\n return null;\n })\n }\n >\n {view.Favorited ? \"★ In favorites\" : \"☆ Favorite\"}\n </button>\n {!view.IsMine && view.CreatorUserID && (\n <button\n style={secondaryBtn}\n disabled={busy !== null}\n onClick={() =>\n void run(\"follow\", async () => {\n const creator = view.CreatorUserID ?? \"\";\n const r = following\n ? await host.client.social.unfollow(\"User\", creator)\n : await host.client.social.follow(\"User\", creator);\n if (!r.ok) return errorText(r.error);\n setFollowing(r.data.Following === true);\n return r.data.Following ? \"You follow this author.\" : null;\n })\n }\n >\n {following ? \"Following ✓\" : \"Follow author\"}\n </button>\n )}\n {view.IsMine && view.Status !== \"Removed\" && (\n <button\n style={dangerBtn}\n disabled={busy !== null}\n onClick={() => {\n if (\n !confirm(\n \"Unpublish for good? Players who already have it keep it.\",\n )\n )\n return;\n void run(\"unpublish\", async () => {\n const r = await host.client.workshop.unpublish(contentID);\n if (!r.ok) return errorText(r.error);\n await reload();\n return \"Unpublished.\";\n });\n }}\n >\n Unpublish\n </button>\n )}\n </div>\n\n {!view.IsMine && (\n <div style={filtersRow}>\n <select\n style={input}\n value={reportReason}\n onChange={(e) =>\n setReportReason(e.target.value as SocialReportReason)\n }\n >\n {REPORT_REASONS.map((r) => (\n <option key={r} value={r}>\n {r}\n </option>\n ))}\n </select>\n <button\n style={secondaryBtn}\n disabled={busy !== null}\n onClick={() =>\n void run(\"report\", async () => {\n const r = await host.client.social.report(\n \"WorkshopItem\",\n contentID,\n reportReason,\n );\n if (!r.ok) return errorText(r.error);\n return r.data.AlreadyReported\n ? \"You already reported this.\"\n : \"Thanks — the publisher will review it.\";\n })\n }\n >\n Report\n </button>\n </div>\n )}\n\n {message && <div style={noticeBox}>{message}</div>}\n </Modal>\n );\n}\n\n// ────────────────────────────── Publish ──────────────────────────────\n\ninterface AccessDraft {\n mode: \"Free\" | \"Price\" | \"Holding\";\n resource: string; // \"vc:GOLD\" | \"item:<catalog>/<item>\"\n amount: number;\n holdMode: \"WhileHeld\" | \"UnlockOnce\";\n}\n\nfunction PublishWizard({\n host,\n defs,\n onDone,\n}: {\n host: WorkshopHost;\n defs: WorkshopDefinitionsResponse;\n onDone(contentID: string): void;\n}): ReactNode {\n const handlers = useContentTypes(host.content).filter(\n (h) => h.listLocal && h.capture && defs.CanPublish?.[h.type] === true,\n );\n const [type, setType] = useState<string | null>(null);\n const [locals, setLocals] = useState<Array<{\n id: string;\n name: string;\n subtitle?: string;\n }> | null>(null);\n const [localId, setLocalId] = useState<string | null>(null);\n const [title, setTitle] = useState(\"\");\n const [description, setDescription] = useState(\"\");\n const [tags, setTags] = useState(\"\");\n const [visibility, setVisibility] = useState<WorkshopVisibility>(\"Public\");\n const [access, setAccess] = useState<AccessDraft[]>([\n { mode: \"Free\", resource: \"\", amount: 1, holdMode: \"UnlockOnce\" },\n ]);\n const [busy, setBusy] = useState(false);\n const [message, setMessage] = useState<string | null>(null);\n\n const handler = handlers.find((h) => h.type === type);\n const typeDef = type ? defs.Definitions?.ContentTypes?.[type] : undefined;\n const allowedModes = typeDef?.AllowedAccessModes?.length\n ? typeDef.AllowedAccessModes\n : [\"Free\", \"Price\", \"Holding\"];\n const resources = useResourceOptions(host.client);\n // Плата за публикацию берётся только ресурсами: вариант с оплатой в сторе сервер отвергнет.\n const fee = Object.entries(typeDef?.PublishFeeOptions ?? {}).find(\n ([, option]) =>\n !(option?.Cost?.Standard?.Entries ?? []).some(\n (e) => e?.Type === \"Purchase\",\n ),\n );\n\n useEffect(() => {\n setLocals(null);\n setLocalId(null);\n if (!handler?.listLocal) return;\n void handler\n .listLocal()\n .then(setLocals, (e: unknown) =>\n setMessage(e instanceof Error ? e.message : String(e)),\n );\n }, [handler]);\n\n if (handlers.length === 0)\n return (\n <div style={muted}>\n Nothing to publish from here: the games in this project either do not\n register their content, or you can't publish it yet.\n </div>\n );\n\n const publish = async (): Promise<void> => {\n if (!handler?.capture || !type || !localId) return;\n // Опция без ресурса молча выпала бы из списка, и публикация ушла бы не с теми способами получить.\n if (access.some((a) => a.mode !== \"Free\" && !a.resource)) {\n setMessage(\"Pick a resource for every paid or hold-to-unlock option.\");\n return;\n }\n setBusy(true);\n setMessage(null);\n try {\n const captured = await handler.capture(localId);\n const r = await host.client.workshop.publish({\n contentType: type,\n files: captured.files,\n thumbnail: captured.thumbnail,\n title: title.trim() || captured.suggestedTitle || \"Untitled\",\n description: description.trim() || captured.suggestedDescription,\n tags: tags\n .split(\",\")\n .map((t) => t.trim())\n .filter(Boolean)\n .concat(captured.tags ?? []),\n metadata: captured.metadata,\n visibility,\n access: access\n .map(toAccessInput)\n .filter((a): a is WorkshopAccessOptionInput => a !== null),\n selectedFeeOptionID: fee?.[0],\n });\n if (!r.ok) setMessage(errorText(r.error));\n else if (r.data.Content?.ContentID) onDone(r.data.Content.ContentID);\n } catch (e) {\n setMessage(e instanceof Error ? e.message : String(e));\n } finally {\n setBusy(false);\n }\n };\n\n return (\n <div style={formCol}>\n <label style={fieldLabel}>What</label>\n <div style={chipsRow}>\n {handlers.map((h) => (\n <button\n key={h.type}\n style={type === h.type ? chipActive : chip}\n onClick={() => setType(h.type)}\n >\n {h.icon} {h.label}\n </button>\n ))}\n </div>\n\n {handler && (\n <>\n <label style={fieldLabel}>Which one</label>\n {!locals ? (\n <div style={muted}>Loading…</div>\n ) : locals.length === 0 ? (\n <div style={muted}>You have nothing of this type yet.</div>\n ) : (\n <div style={formCol}>\n {locals.map((l) => (\n <label key={l.id} style={checkLabel}>\n <input\n type=\"radio\"\n name=\"wsLocal\"\n checked={localId === l.id}\n onChange={() => {\n setLocalId(l.id);\n if (!title) setTitle(l.name);\n }}\n />\n {l.name}{\" \"}\n {l.subtitle && <span style={muted}>· {l.subtitle}</span>}\n </label>\n ))}\n </div>\n )}\n </>\n )}\n\n {localId && (\n <>\n <label style={fieldLabel}>Title</label>\n <input\n style={input}\n value={title}\n maxLength={defs.Definitions?.Limits?.MaxTitleLength ?? 60}\n onChange={(e) => setTitle(e.target.value)}\n />\n <label style={fieldLabel}>Description</label>\n <textarea\n style={{ ...input, minHeight: 70 }}\n value={description}\n onChange={(e) => setDescription(e.target.value)}\n />\n <label style={fieldLabel}>\n Tags (comma separated\n {typeDef?.TagVocabulary?.length\n ? `: ${typeDef.TagVocabulary.join(\", \")}`\n : \"\"}\n )\n </label>\n <input\n style={input}\n value={tags}\n onChange={(e) => setTags(e.target.value)}\n />\n <label style={fieldLabel}>Who can see it</label>\n <select\n style={input}\n value={visibility}\n onChange={(e) =>\n setVisibility(e.target.value as WorkshopVisibility)\n }\n >\n <option value=\"Public\">Everyone (in the catalog)</option>\n <option value=\"Unlisted\">Anyone with the link</option>\n <option value=\"Friends\">Only my friends</option>\n </select>\n\n <label style={fieldLabel}>How others get it — any option works</label>\n {access.map((a, i) => (\n <div key={i} style={filtersRow}>\n <select\n style={input}\n value={a.mode}\n onChange={(e) =>\n setAccess(\n patch(access, i, {\n mode: e.target.value as AccessDraft[\"mode\"],\n }),\n )\n }\n >\n {allowedModes.map((m) => (\n <option key={m} value={m}>\n {m === \"Free\"\n ? \"Free\"\n : m === \"Price\"\n ? \"For resources\"\n : \"Hold to unlock\"}\n </option>\n ))}\n </select>\n {a.mode !== \"Free\" && (\n <>\n <select\n style={input}\n value={a.resource}\n onChange={(e) =>\n setAccess(patch(access, i, { resource: e.target.value }))\n }\n >\n <option value=\"\">— resource —</option>\n {resources\n .filter(\n (r) => a.mode === \"Holding\" || r.startsWith(\"vc:\"),\n )\n .map((r) => (\n <option key={r} value={r}>\n {r.replace(/^vc:/, \"\").replace(/^item:/, \"item \")}\n </option>\n ))}\n </select>\n <input\n style={{ ...input, width: 90 }}\n type=\"number\"\n min={1}\n value={a.amount}\n onChange={(e) =>\n setAccess(\n patch(access, i, {\n amount: Math.max(1, Number(e.target.value) || 1),\n }),\n )\n }\n />\n </>\n )}\n {a.mode === \"Holding\" && (\n <select\n style={input}\n value={a.holdMode}\n onChange={(e) =>\n setAccess(\n patch(access, i, {\n holdMode: e.target.value as AccessDraft[\"holdMode\"],\n }),\n )\n }\n >\n <option value=\"UnlockOnce\">Checked once, then forever</option>\n <option value=\"WhileHeld\">Only while they hold it</option>\n </select>\n )}\n {access.length > 1 && (\n <button\n style={secondaryBtn}\n onClick={() => setAccess(access.filter((_, j) => j !== i))}\n >\n ✕\n </button>\n )}\n </div>\n ))}\n <button\n style={secondaryBtn}\n onClick={() =>\n setAccess([\n ...access,\n {\n mode: allowedModes.includes(\"Price\") ? \"Price\" : \"Free\",\n resource: \"\",\n amount: 10,\n holdMode: \"UnlockOnce\",\n },\n ])\n }\n >\n + Add an option\n </button>\n\n {fee && (\n <div style={muted}>\n Publishing costs {bundleLabel(fee[1].Cost?.Standard)} (charged\n once).\n </div>\n )}\n <button\n style={primaryBtn}\n disabled={busy}\n onClick={() => void publish()}\n >\n {busy ? \"Publishing…\" : \"Publish\"}\n </button>\n </>\n )}\n {message && <div style={errorBox}>{message}</div>}\n </div>\n );\n}\n\nfunction patch<T>(list: T[], index: number, change: Partial<T>): T[] {\n return list.map((item, i) => (i === index ? { ...item, ...change } : item));\n}\n\nfunction toAccessInput(a: AccessDraft): WorkshopAccessOptionInput | null {\n if (a.mode === \"Free\") return { Mode: \"Free\" };\n if (!a.resource) return null;\n const [kind, id = \"\"] = a.resource.split(\":\", 2);\n if (a.mode === \"Price\") {\n return {\n Mode: \"Price\",\n Price: {\n Entries: [\n { Type: \"VirtualCurrency\", CurrencyID: id, Amount: a.amount },\n ],\n },\n };\n }\n const [catalogID, itemID] = id.split(\"/\", 2);\n return {\n Mode: \"Holding\",\n Holding: {\n Mode: a.holdMode,\n Match: \"All\",\n Requirements: [\n kind === \"vc\"\n ? { Type: \"VirtualCurrency\", CurrencyID: id, Amount: a.amount }\n : {\n Type: \"Item\",\n CatalogID: catalogID,\n ItemID: itemID ?? \"\",\n Amount: a.amount,\n },\n ],\n },\n };\n}\n\n// ────────────────────────────── Lists ──────────────────────────────\n\nfunction MyList({\n host,\n kind,\n onOpen,\n}: {\n host: WorkshopHost;\n kind: \"mine\" | \"licenses\" | \"favorites\";\n onOpen(id: string): void;\n}): ReactNode {\n const handlers = useContentTypes(host.content);\n const [items, setItems] = useState<WorkshopContentView[] | null>(null);\n const [error, setError] = useState<string | null>(null);\n\n useEffect(() => {\n let alive = true;\n const load = async (): Promise<void> => {\n const w = host.client.workshop;\n if (kind === \"licenses\") {\n const r = await w.getMyLicenses();\n if (!alive) return;\n if (r.ok)\n setItems(\n (r.data.Licenses ?? [])\n .map((l) => l.Content)\n .filter((c): c is WorkshopContentView => Boolean(c)),\n );\n else setError(errorText(r.error));\n return;\n }\n const r =\n kind === \"mine\" ? await w.getMyContent() : await w.getMyFavorites();\n if (!alive) return;\n if (r.ok) setItems(r.data.Items ?? []);\n else setError(errorText(r.error));\n };\n void load();\n return () => {\n alive = false;\n };\n }, [host, kind]);\n\n if (error) return <div style={errorBox}>{error}</div>;\n if (!items) return <div style={muted}>Loading…</div>;\n if (items.length === 0) return <div style={muted}>Empty.</div>;\n return (\n <div style={grid}>\n {items.map((item) => (\n <ContentCard\n key={item.ContentID ?? \"\"}\n item={item}\n handlers={handlers}\n onClick={() => item.ContentID && onOpen(item.ContentID)}\n />\n ))}\n </div>\n );\n}\n\n// ────────────────────────────── helpers ──────────────────────────────\n\n/**\n * Registered content types, re-read on every registry change. ⚠ Not keyed by the NUMBER of types: a game\n * re-installed after re-login registers the same type again with a new handler, the count stays the\n * same, and a count-based snapshot kept the handler of the destroyed game.\n */\nfunction useContentTypes(content: ContentRegistry): ContentTypeHandler[] {\n const [types, setTypes] = useState(() => content.listTypes());\n useEffect(() => {\n setTypes(content.listTypes());\n return content.subscribe(() => setTypes(content.listTypes()));\n }, [content]);\n return types;\n}\n\n/** \"vc:GOLD\" and \"item:<catalog>/<item>\" for every currency and item the title defines. */\nfunction useResourceOptions(client: IDosGamesClient): string[] {\n const [list] = useState(() => {\n const out: string[] = [];\n for (const id of Object.keys(\n client.data.config.currencyDefinitions?.VirtualCurrencies ?? {},\n ))\n out.push(`vc:${id}`);\n for (const [catalogID, catalog] of Object.entries(\n client.data.config.itemDefinitions?.Catalogs ?? {},\n ))\n for (const itemID of Object.keys(catalog?.Items ?? {}))\n out.push(`item:${catalogID}/${itemID}`);\n return out;\n });\n return list;\n}\n\ntype BundleLike =\n | {\n Entries?: Array<{\n CurrencyID?: string | null;\n ItemID?: string | null;\n Amount?: number | null;\n } | null> | null;\n }\n | null\n | undefined;\n\nfunction bundleLabel(bundle: BundleLike): string {\n const parts = (bundle?.Entries ?? [])\n .filter((e): e is NonNullable<typeof e> => Boolean(e))\n .map((e) => `${e.Amount ?? 0} ${e.CurrencyID ?? e.ItemID ?? \"\"}`.trim());\n return parts.length ? parts.join(\" + \") : \"free\";\n}\n\nfunction accessLabel(o: WorkshopAccessOption): string {\n if (o.Mode === \"Free\") return \"Free\";\n if (o.Mode === \"Price\") return bundleLabel(o.Price);\n const reqs = (o.Holding?.Requirements ?? []).map(\n (r) =>\n `${r.Amount ?? 0} ${r.CurrencyID ?? r.ItemID ?? \"\"}${r.MinLevel ? ` (lvl ${r.MinLevel}+)` : \"\"}`,\n );\n const joined = reqs.join(o.Holding?.Match === \"Any\" ? \" or \" : \" + \");\n return `🔑 hold ${joined}${o.Holding?.Mode === \"WhileHeld\" ? \" (while held)\" : \"\"}`;\n}\n\nfunction formatBytes(n: number): string {\n if (n < 1024) return `${n} B`;\n if (n < 1024 * 1024) return `${(n / 1024).toFixed(0)} KB`;\n return `${(n / 1024 / 1024).toFixed(1)} MB`;\n}\n\nfunction Frame({ children }: { children: ReactNode }): ReactNode {\n return <div style={frame}>{children}</div>;\n}\n\nfunction Modal({\n children,\n onClose,\n}: {\n children: ReactNode;\n onClose(): void;\n}): ReactNode {\n return (\n <div style={backdrop} onClick={onClose}>\n <div style={modal} onClick={(e) => e.stopPropagation()}>\n <button style={closeBtn} onClick={onClose} aria-label=\"Close\">\n ✕\n </button>\n {children}\n </div>\n </div>\n );\n}\n\n// ────────────────────────────── styles ──────────────────────────────\n// Every colour is a theme token of the UI kit (the project's src/ui.config.ts), like every other\n// system — the workshop must not be a dark island in a light app. Change the theme, not these.\n\nconst frame: CSSProperties = {\n // A tab of the lobby: the lobby scrolls it and gives it the width.\n minHeight: 360,\n borderRadius: 16,\n padding: \"16px 20px 40px\",\n ...panel,\n color: v.text,\n fontFamily: v.font,\n pointerEvents: \"auto\",\n};\nconst tabsRow: CSSProperties = {\n display: \"flex\",\n gap: 6,\n flexWrap: \"wrap\",\n marginBottom: 14,\n};\nconst tabBtn: CSSProperties = {\n background: \"transparent\",\n color: v.textDim,\n border: `1px solid ${v.line}`,\n borderRadius: 8,\n padding: \"6px 12px\",\n cursor: \"pointer\",\n};\nconst tabActive: CSSProperties = {\n ...tabBtn,\n background: `linear-gradient(180deg, ${v.blue}, ${v.blueDeep})`,\n color: v.onBlue,\n border: \"1px solid transparent\",\n};\nconst chipsRow: CSSProperties = {\n display: \"flex\",\n gap: 6,\n flexWrap: \"wrap\",\n margin: \"8px 0\",\n};\nconst chip: CSSProperties = {\n ...tabBtn,\n borderRadius: 999,\n padding: \"4px 10px\",\n fontSize: 13,\n};\nconst chipActive: CSSProperties = {\n ...chip,\n background: `color-mix(in srgb, ${v.blue} 30%, transparent)`,\n color: v.text,\n};\nconst filtersRow: CSSProperties = {\n display: \"flex\",\n gap: 8,\n flexWrap: \"wrap\",\n alignItems: \"center\",\n margin: \"8px 0\",\n};\nconst input: CSSProperties = {\n background: v.well,\n color: v.text,\n border: `1px solid ${v.line}`,\n boxShadow: v.wellShadow,\n borderRadius: 6,\n padding: \"6px 8px\",\n font: \"inherit\",\n};\nconst checkLabel: CSSProperties = {\n display: \"flex\",\n gap: 6,\n alignItems: \"center\",\n fontSize: 14,\n};\nconst grid: CSSProperties = {\n display: \"grid\",\n gridTemplateColumns: \"repeat(auto-fill, minmax(170px, 1fr))\",\n gap: 12,\n};\nconst card: CSSProperties = {\n textAlign: \"left\",\n background: v.panelDeep,\n border: `1px solid ${v.panelEdge}`,\n borderRadius: 10,\n padding: 8,\n color: \"inherit\",\n cursor: \"pointer\",\n font: \"inherit\",\n};\nconst thumbBox: CSSProperties = {\n aspectRatio: \"1 / 1\",\n borderRadius: 8,\n background: v.wellSoft,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n overflow: \"hidden\",\n};\nconst thumbImg: CSSProperties = {\n width: \"100%\",\n height: \"100%\",\n objectFit: \"cover\",\n imageRendering: \"pixelated\",\n};\nconst cardTitle: CSSProperties = {\n fontWeight: 600,\n margin: \"6px 0 2px\",\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n whiteSpace: \"nowrap\",\n};\nconst cardMeta: CSSProperties = { fontSize: 12, color: v.textDim };\nconst badgesRow: CSSProperties = {\n display: \"flex\",\n gap: 4,\n flexWrap: \"wrap\",\n marginTop: 6,\n};\nconst badge: CSSProperties = {\n fontSize: 11,\n background: v.wellSoft,\n color: v.text,\n borderRadius: 4,\n padding: \"2px 6px\",\n};\nconst badgeOwned: CSSProperties = {\n ...badge,\n background: `color-mix(in srgb, ${v.green} 35%, transparent)`,\n};\nconst badgeWarn: CSSProperties = {\n ...badge,\n background: `color-mix(in srgb, ${v.gold} 35%, transparent)`,\n};\nconst muted: CSSProperties = { color: v.textDim, fontSize: 13 };\nconst errorBox: CSSProperties = {\n background: `color-mix(in srgb, ${v.red} 18%, transparent)`,\n border: `1px solid color-mix(in srgb, ${v.red} 45%, transparent)`,\n color: v.text,\n borderRadius: 6,\n padding: \"8px 10px\",\n margin: \"8px 0\",\n};\nconst noticeBox: CSSProperties = {\n background: `color-mix(in srgb, ${v.blue} 16%, transparent)`,\n borderRadius: 6,\n padding: \"8px 10px\",\n marginTop: 10,\n};\nconst primaryBtn: CSSProperties = {\n ...buttonStyle(\"blue\", false, \"sm\"),\n font: \"inherit\",\n fontWeight: 800,\n};\nconst disabledBtn: CSSProperties = {\n ...buttonStyle(\"blue\", true, \"sm\"),\n font: \"inherit\",\n fontWeight: 800,\n cursor: \"not-allowed\",\n};\nconst secondaryBtn: CSSProperties = { ...tabBtn, color: v.text };\nconst dangerBtn: CSSProperties = {\n ...tabBtn,\n color: v.red,\n border: `1px solid color-mix(in srgb, ${v.red} 50%, transparent)`,\n};\nconst actionsCol: CSSProperties = {\n display: \"flex\",\n flexDirection: \"column\",\n gap: 8,\n margin: \"12px 0\",\n};\nconst formCol: CSSProperties = {\n display: \"flex\",\n flexDirection: \"column\",\n gap: 6,\n maxWidth: 640,\n};\nconst fieldLabel: CSSProperties = {\n fontSize: 13,\n color: v.textDim,\n marginTop: 8,\n};\nconst backdrop: CSSProperties = {\n position: \"fixed\",\n inset: 0,\n background: v.backdrop,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n zIndex: 50,\n};\nconst modal: CSSProperties = {\n position: \"relative\",\n ...panel,\n color: v.text,\n padding: 20,\n width: \"min(640px, 94vw)\",\n maxHeight: \"90vh\",\n overflow: \"auto\",\n};\nconst closeBtn: CSSProperties = {\n position: \"absolute\",\n top: 10,\n right: 10,\n background: \"transparent\",\n color: v.textDim,\n border: 0,\n fontSize: 18,\n cursor: \"pointer\",\n};\nconst detailsHead: CSSProperties = {\n display: \"flex\",\n gap: 14,\n alignItems: \"flex-start\",\n marginRight: 24,\n};\nconst detailsThumb: CSSProperties = {\n ...thumbBox,\n width: 120,\n flex: \"0 0 120px\",\n};\n"
65
64
  },
66
65
  {
67
66
  "path": "module.meta.json",
68
- "content": "{\n \"id\": \"workshop\",\n \"type\": \"feature\",\n \"inBase\": true,\n \"summary\": \"Workshop: players and the publisher share content (maps, levels, skins, models) — free, for in-game resources, or unlocked by holding items.\",\n \"description\": \"A ready catalog of user-generated content for ANY game. Players publish what they made (a world, a level, a skin, any file the title allows), set how others get it — free, a price in in-game resources (several options at once, the author receives it minus commission), or 'hold N of this item / currency to unlock' (nothing is charged; while held or once) — and others browse, filter, acquire, open, like, favorite, follow authors and report. The publisher configures content types, formats, limits, commission and moderation in the Workshop section of the title config, curates featured collections and publishes official content from the dashboard. A game plugs its own content in by registering a handler with ctx.content.registerType({ type, label, listLocal, capture, open, modeId }) — the Workshop never imports the game. VoxelCraft registers 'voxelcraft.world'.\",\n \"provides\": [\n \"player-made content catalog (maps, levels, skins, models, any file type the title allows)\",\n \"publish a map or level made in the game\",\n \"sell content for in-game resources with author royalties minus commission\",\n \"free content sharing\",\n \"unlock content by holding an item or currency without spending it\",\n \"likes, favorites and following content creators\",\n \"report content and auto-hide after reports\",\n \"publisher featured collections and official content\",\n \"download and open shared content in the game\"\n ],\n \"tags\": [\n \"workshop\",\n \"ugc\",\n \"user-generated-content\",\n \"maps\",\n \"levels\",\n \"mods\",\n \"sharing\",\n \"marketplace\",\n \"creators\",\n \"social\"\n ],\n \"author\": { \"name\": \"iDos Games\", \"url\": \"https://idosgames.com\" },\n \"version\": \"0.1.0\"\n}\n"
67
+ "content": "{\n \"id\": \"workshop\",\n \"type\": \"feature\",\n \"summary\": \"Workshop: players and the publisher share content (maps, levels, skins, models) — free, for in-game resources, or unlocked by holding items.\",\n \"description\": \"A ready catalog of user-generated content for ANY game. Players publish what they made (a world, a level, a skin, any file the title allows), set how others get it — free, a price in in-game resources (several options at once, the author receives it minus commission), or 'hold N of this item / currency to unlock' (nothing is charged; while held or once) — and others browse, filter, acquire, open, like, favorite, follow authors and report. The publisher configures content types, formats, limits, commission and moderation in the Workshop section of the title config, curates featured collections and publishes official content from the dashboard. A game plugs its own content in by registering a handler with ctx.content.registerType({ type, label, listLocal, capture, open, modeId }) — the Workshop never imports the game. VoxelCraft registers 'voxelcraft.world'.\",\n \"provides\": [\n \"player-made content catalog (maps, levels, skins, models, any file type the title allows)\",\n \"publish a map or level made in the game\",\n \"sell content for in-game resources with author royalties minus commission\",\n \"free content sharing\",\n \"unlock content by holding an item or currency without spending it\",\n \"likes, favorites and following content creators\",\n \"report content and auto-hide after reports\",\n \"publisher featured collections and official content\",\n \"download and open shared content in the game\"\n ],\n \"tags\": [\n \"workshop\",\n \"ugc\",\n \"user-generated-content\",\n \"maps\",\n \"levels\",\n \"mods\",\n \"sharing\",\n \"marketplace\",\n \"creators\",\n \"social\"\n ],\n \"author\": { \"name\": \"iDos Games\", \"url\": \"https://idosgames.com\" },\n \"version\": \"0.1.2\"\n}\n"
69
68
  }
70
69
  ]
71
70
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "blockchain-system",
3
3
  "description": "Bridge in-game assets on-chain in a game on the iDosGames TypeScript SDK (@idosgames/core) via client.blockchain (BlockchainService): load blockchain network/config definitions, load the player's on-chain state (linked wallets, pending withdrawals, KYC, stats), deposit a token or NFT from a wallet into the game, request a token or NFT withdrawal out to a wallet, read on-chain transaction history, retry a still-pending withdrawal's signature, confirm a withdrawal's on-chain tx hash, and donate crypto to the developer or a users' pool. Use this whenever the user is working in the iDosGames TS SDK or its game templates (board-game, idle-rpg) and wants crypto wallets, NFT deposits/withdrawals, token bridging, on-chain asset transfers, KYC status, or otherwise touches client.blockchain, BlockchainService, BlockchainDefinitions, UserBlockchainState, DepositTokenResponse, TokenWithdrawalResponse, or NFTWithdrawalResponse — even if they don't name the module explicitly.",
4
- "content": "---\nname: blockchain-system\ndescription: >-\n Bridge in-game assets on-chain in a game on the iDosGames TypeScript SDK\n (@idosgames/core) via client.blockchain (BlockchainService): load blockchain\n network/config definitions, load the player's on-chain state (linked\n wallets, pending withdrawals, KYC, stats), deposit a token or NFT from a\n wallet into the game, request a token or NFT withdrawal out to a wallet,\n read on-chain transaction history, retry a still-pending withdrawal's\n signature, confirm a withdrawal's on-chain tx hash, and donate crypto to\n the developer or a users' pool. Use this whenever the user is working in\n the iDosGames TS SDK or its game templates (board-game, idle-rpg) and wants crypto wallets, NFT\n deposits/withdrawals, token bridging, on-chain asset transfers, KYC status,\n or otherwise touches client.blockchain, BlockchainService,\n BlockchainDefinitions, UserBlockchainState, DepositTokenResponse,\n TokenWithdrawalResponse, or NFTWithdrawalResponse — even if they don't name\n the module explicitly.\n---\n\n# Blockchain system (iDosGames TS SDK)\n\nThe Blockchain module bridges in-game assets to and from real wallets on\nsupported chains (EVM and Solana networks). A player can deposit a token or\nNFT they already sent on-chain (crediting their in-game balance/inventory),\nor request a withdrawal that pays an in-game token/NFT out to their wallet\n(debiting their in-game balance/inventory and producing a signature the\nplayer submits on-chain themselves). Everything is **server-authoritative**:\nthe client reports/requests, the backend validates the transaction against\nthe chain, applies rules (network enabled, KYC, account-safety policy), and\nthe SDK mirrors the confirmed result into a local cache your UI reads. You\nnever credit/debit balances yourself.\n\nThis skill is for **using** the production `BlockchainService`, not for\nporting or extending it, and not for signing/broadcasting transactions\nyourself — this SDK reports deposits and requests withdrawals; actually\nsending the on-chain transaction (the deposit transfer, or broadcasting a\nwithdrawal signature) happens with a wallet SDK outside this client.\n\n> **The on-chain half is the `@idosgames/wallet` companion package.** It\n> connects browser & mobile wallets (EVM via wagmi/viem/WalletConnect, Solana\n> via wallet-adapter) and runs the exact RewardPool contract calls, threading\n> them through this service's request → submit → confirm / approve → deposit →\n> report lifecycle. If the user wants to actually connect a wallet and move\n> tokens/NFTs (not just call `client.blockchain.*`), reach for that package —\n> see its README. Everything below documents the server-authoritative\n> `client.blockchain` surface that `@idosgames/wallet` builds on. The wallet\n> package's EVM surface covers both NFT standards: `submitEvmNftWithdrawal` /\n> `depositNftEvm` (+ `erc1155Abi`) for ERC-1155 collections, and\n> `submitEvmNftWithdrawal721` / `depositNftEvm721` (+ `erc721Abi`) for\n> ERC-721 unique-item collections (4-arg `safeTransferFrom`, no `id`/`amount`\n> — the token is always qty 1). `submitEvmTokenWithdrawal`'s `withdrawERC20`\n> call now also threads `sig.BurnAmount` through (see\n> [Burn on withdrawal](#gotchas) below) — the ABI/contract call order changed,\n> so an app pinned to an older `@idosgames/wallet` build will revert on-chain\n> against an updated RewardPool contract.\n\n> **Never import `@idosgames/wallet/react` (or `/react/solana`) from a file\n> that loads on startup.** Those subpaths pull in Reown AppKit, and AppKit is\n> deliberately _not_ a dependency of a generated project — the live preview\n> resolves every declared dependency up front and times out on AppKit's tree.\n> A static import therefore blanks the preview before any game code runs\n> (`Could not find dependency: '@reown/appkit-adapter-wagmi'`), while the real\n> build stays green — that mismatch is the signature of this mistake.\n> Two rules keep both working:\n>\n> - **Sign-in button:** import `LazyWalletLogin` / `LazySolanaWalletLogin` from\n> `@idosgames/wallet/react/lazy` (that entry has no AppKit in its graph; it\n> also re-exports the chains as plain objects — never import chains from\n> `wagmi/chains` or `viem/chains`, that barrel breaks the preview too).\n> - **In-game deposit/withdraw panel:** import `LazyWalletPanel` from\n> `@idosgames/wallet/react/lazy` and pass it the authenticated `client` (a\n> prop, like the login button — never a module context). Same lazy contract:\n> AppKit stays out of the startup graph. Don't hand-roll your own\n> `await import(\"./PanelImpl\")` wrapper — `LazyWalletPanel` is that wrapper.\n> Because the wallet config is memoised per WalletConnect project id, the\n> panel reuses the wallet the player connected at sign-in: same store, so it\n> opens already-connected, no second tap and no second modal. This is exactly\n> how the board-game and idle-rpg modules wire their `WalletPanel.tsx`.\n\n> **The game cannot reach the wallet while it is embedded in an idosgames.com iframe** (owner's\n> decision, 2026-09-17 — deposit/withdraw goes through the buttons in the site's own wallet card).\n> You don't need to special-case this: `LazyWalletPanel` renders nothing there, and\n> `LazyWalletLogin` / `LazySolanaWalletLogin` stay a working \"Sign in with wallet\" button — inside\n> the frame the SITE's connected wallet signs the engine's login message for the game\n> (`loginWithWalletViaPlatform` from `@idosgames/wallet`, used by the buttons automatically). Never\n> show a \"use idosgames.com\" notice inside the game. Every flow function that talks to the wallet\n> directly (`depositTokenEvm`, `withdrawTokenEvm`, `loginWithWalletEvm`, their Solana equivalents,\n> `payWithWalletEvm`) refuses with `WALLET_USE_SITE_PANEL` inside a frame. A game opened by its own\n> direct link (not embedded) is unaffected — every one of these works exactly as before there.\n\n### Login mode and play access by token balance (`cfg.Blockchain.PlayAccess`)\n\nA title can require players to HOLD tokens to play. The publisher picks one of three login modes:\n\n| `Mode` | Who can sign in | Balance check |\n| --------------------- | ----------------------------- | -------------------------------------------- |\n| `Open` (default) | every method, guests included | none |\n| `AnyWithLinkedWallet` | every method except guest | the wallet the player linked by signature |\n| `WalletOnly` | wallet login only | the wallet they signed in with — and only it |\n\nIn `WalletOnly` the account must BE the wallet's account: an account created another way before the\nmode was switched on gets `PLAY_ACCESS_WALLET_LOGIN_ONLY` on every check, and `linkWallet` refuses\nany wallet but the account's own with the same code — don't offer \"link wallet\" there, offer\n\"log out and sign in with your wallet\".\n\nRequirements are `TokenGates` (`CurrencyID`, `MinBalance`, `BalanceSource`: `OnChain` wallet /\n`InGame` game balance — no wallet needed / `Combined`; `NetworkID` for wallet ones). The SERVER\nchecks the balance on every login and session refresh — silently, no signature — and on\n`client.blockchain.confirmPlayAccess()`. Gameplay calls without a valid pass fail with HTTP 403\n`PLAY_ACCESS_REQUIRED`; `Blockchain` itself, account linking and the login-time `User` reads stay open.\n\n**The host template already handles all of it — don't rebuild it.** `mountHost` shows the\nplay-access screen (`renderPlayAccess`, the template's `src/PlayAccessScreen.tsx` over\n`DefaultPlayAccessScreen`) instead of the game whenever `client.auth.playAccess?.Granted === false`\nor `playAccess:required` fires, and the template's login screen hides the methods the mode refuses\n(`client.auth.getAuthOptions()` → `PlayAccessMode`). \"Link wallet\" on that screen is\n`LazyWalletLogin mode=\"link\"` (`renderWalletLink` in `src/walletLogin.tsx`); inside the\nidosgames.com frame the site's wallet signs the link (`linkWalletViaPlatform`).\n\nClient surface, if you roll your own screen: `client.auth.playAccess` (+ `playAccess:changed`),\n`client.blockchain.getPlayAccess()` (mode, requirements, the player's signature-linked wallets, last\ncheck), `client.blockchain.confirmPlayAccess(networkID?)` (choose a linked wallet and check now),\n`client.auth.linkWallet(address, networkID, signature?)` (two steps; the second returns the pass\nchecked against that wallet), `linkWalletEvm` / `linkWalletSolana` / `linkWalletViaPlatform` in\n`@idosgames/wallet`. Refusal codes: `PLAY_ACCESS_WALLET_REQUIRED`,\n`PLAY_ACCESS_WALLET_NETWORK_NOT_GATED`, `PLAY_ACCESS_GUEST_DISABLED`, `PLAY_ACCESS_WALLET_LOGIN_ONLY`,\n`PLAY_ACCESS_CHECK_FAILED` (the RPC could not be read — NOT an empty wallet; check again), or the\nrequirement's own `DenyMessage`. A login or refresh never fails for lack of balance — in every mode\nthe session is issued and the game stays closed until the pass is granted.\n\n### Operation category (`game_topup` by default)\n\nThe updated RewardPool contract tags every deposit/withdrawal with a string\n**category** (default `\"game_topup\"`; `\"community_reward\"` is the other known\nvalue, and arbitrary strings are allowed). On a **withdrawal** the server signs\nthe category into the on-chain hash and returns it on the signature payload\n(`EvmSignature.Category` / `.TitleID`); whoever submits the transaction **must\npass the same value on-chain verbatim** or the contract rejects the signature —\n`@idosgames/wallet` does this for you. Pass it as the optional last arg to\n`requestTokenWithdrawal`/`requestNFTWithdrawal` (omit → `\"game_topup\"`). On a\n**deposit** the category is read back from the on-chain transaction, so you\ndon't pass it to `depositToken`/`depositNFT`. It also appears on transaction\ndocuments as `Category`. Import the constants from `@idosgames/core`:\n`BlockchainOperationCategory.GameTopUp` / `.CommunityReward`.\n\n## Mental model: deposits vs. withdrawals\n\n- **Deposit** = the player already sent tokens/an NFT to the platform's pool\n or vault address on-chain. The client then calls `depositToken`/`depositNFT`\n with that transaction's hash so the backend can verify it and credit the\n player in-game. One-shot: the credit happens directly on a successful call.\n- **Withdrawal** = the player wants an in-game token/NFT sent out to their\n wallet. The client calls `requestTokenWithdrawal`/`requestNFTWithdrawal`,\n which **debits in-game immediately** and returns a signed payload\n (`EvmSignature` or `SolanaSignature`) the player's wallet must submit\n on-chain to actually receive the asset. This is a **multi-step, async\n flow** — see [Recipes](#recipes) for the full lifecycle, including what to\n do when the on-chain submission fails.\n\nBoth flows are per-network: every call takes a `networkID` that must match one\nof the title's configured `Networks` (EVM or Solana), each with its own\ndeposit/withdrawal enable flags, contract/vault addresses, and (for NFTs) a\ncollection binding to an item catalog. Withdrawals additionally run through a\nlong chain of server-side gates (balances, per-network minimums, account\nsafety, KYC, daily/monthly compliance limits, a collective title-wide pool\ncap, and platform commission) — see\n[Withdrawal gates](#withdrawal-gates-what-can-reject-a-request) for the full\nlist with verbatim error strings.\n\nFor the full config/state field shapes (network definitions, NFT collection\nbindings, KYC tiers, transaction documents, signature payloads), read\n[references/data-model.md](references/data-model.md). You do **not** need it\nto call the methods — only to drive richer UI (network pickers, KYC gates,\ntransaction history tables).\n\n## Setup\n\n```ts\nimport { createIDosGamesClient } from \"@idosgames/core\";\n\nconst client = createIDosGamesClient({ titleID: \"your-title-id\" });\nawait client.auth.loginWithDeviceID(); // or any auth.* method\n\nconst blockchain = client.blockchain; // the BlockchainService\n```\n\nEvery blockchain method requires an authenticated session. Without one they\nreturn `{ ok: false, reason: \"unauthorized\" }` — they do not throw.\n\n## Methods\n\nAll methods return `Promise<OperationResult<T>>`: a discriminated union that\nis either `{ ok: true, data }` or `{ ok: false, reason, error }`. Always\nbranch on `result.ok` before touching `result.data`. `reason` is one of\n`\"client\"` (missing/empty required arg — rejected before any network call),\n`\"unauthorized\"`, `\"throttled\"` (fired the same endpoint again inside the\n600ms client-side throttle window), `\"connection\"` (transient, offer Retry),\n`\"validation\"` (response/schema drift), or `\"server\"` (backend rejected it —\n`error` carries the exact backend message). Withdrawals in particular can be\nrejected by a long chain of server-side gates — see\n[Withdrawal gates](#withdrawal-gates-what-can-reject-a-request) below for the\nfull list with verbatim error strings.\n\n| Method | Purpose | `data` on success |\n| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ----------------------------- |\n| `getDefinitions()` | Load the title's blockchain config: networks, NFT bindings, crypto currencies. | `BlockchainConfigResponse` |\n| `getUserState()` | Load this player's on-chain state: linked wallets, pending withdrawals, KYC, stats, crypto balances. | `UserBlockchainStateResponse` |\n| `depositToken(networkID, transactionHash)` | Report an on-chain token transfer; credits the matching crypto balance. | `DepositTokenResponse` |\n| `depositNFT(networkID, transactionHash)` | Report an on-chain NFT transfer; grants the matching in-game item. | `DepositNFTResponse` |\n| `requestTokenWithdrawal(currencyID, networkID, walletAddress, amount, category?)` | Debit a crypto balance and get a signed payload to withdraw on-chain. | `TokenWithdrawalResponse` |\n| `requestNFTWithdrawal(itemID, networkID, walletAddress, amount, category?, level?, itemInstanceID?)` | Consume an in-game item and get a signed payload to withdraw the NFT on-chain. | `NFTWithdrawalResponse` |\n| `getTransactionHistory(limit?)` | Load recent token + NFT transaction documents (default limit 50). | `TransactionHistoryResponse` |\n| `retryWithdrawal(titleTransactionID)` | Re-issue a fresh signature for a still-`Pending` withdrawal without re-debiting. | `RetryWithdrawalResponse` |\n| `confirmWithdrawal(titleTransactionID, onChainTransactionHash)` | Tell the backend the signed withdrawal was submitted on-chain, with its tx hash. | `ConfirmWithdrawalResponse` |\n| `donateToDeveloper(networkID, transactionHash)` | Report an on-chain transfer as a donation to the developer pool (no personal credit). | `DonationResponse` |\n| `donateToUsersPool(networkID, transactionHash)` | Report an on-chain transfer as a donation to the users' pool (no personal credit). | `DonationResponse` |\n\nAll string args (`networkID`, `transactionHash`, `currencyID`,\n`walletAddress`, `amount`, `itemID`, `titleTransactionID`,\n`onChainTransactionHash`) are required and checked client-side before any\nnetwork call — an empty one short-circuits with `reason: \"client\"`. `amount`\nis a decimal string for token withdrawals and an integer-as-string for NFT\nwithdrawals / not used for deposits (deposit amounts come from the verified\non-chain transaction, not from the client). `getTransactionHistory(limit)`\ndefaults to `50`, is capped at **200** server-side (values above are silently\nclamped, values `<= 0` fall back to 50), and is sent as `Amount` on the wire\n(reused request field, not an actual currency amount).\n\n`requestNFTWithdrawal`'s trailing `level`/`itemInstanceID` are both optional\nand only matter for NFT catalogs with leveled or unique (ERC-721) bindings:\n`level` selects which leveled instance/tokenId to withdraw (omit or `1` →\nbase level, prior behavior); `itemInstanceID` is **required** when the\nitem's NFT binding is ERC-721 — it tells the server exactly which\nunstackable instance to debit and tokenize (preserving its Level/RemainingUses/\nCustomData in the on-chain registry via a separate ItemBridge contract).\nBoth are ignored for stackable/ERC-1155 items.\n\nOn success, most methods **mirror the confirmed change into the cache and\nemit an event** — see the next section for exactly which cache each method\ntouches, since it's not uniform across this module.\n\n## Withdrawal gates (what can reject a request)\n\n`requestTokenWithdrawal` / `requestNFTWithdrawal` run through a long chain of\nserver-side checks, each a `reason: \"server\"` failure with a specific `error`\nstring. Surface the string; don't try to pre-validate all of these\nclient-side — the gate list can change without a client update:\n\n- **Global kill switch** — withdrawals can be turned off platform-wide\n independently of any per-network/per-currency flag: `\"Withdrawals are\ncurrently disabled.\"`\n- **Network / currency / binding disabled** — `\"Withdrawals disabled for this\nnetwork.\"`, `\"Withdrawals are disabled for currency '{id}'.\"`, `\"This\ncurrency cannot be withdrawn in this network.\"`, or (currency under\n maintenance) `\"Currency '{id}' is under maintenance. Try again later.\"`\n- **Per-network minimum** — every currency has a `MinWithdraw` for each\n network it's bound to (`CryptoNetworkBinding.MinWithdraw`, see the\n currency-system skill's data-model for the full shape): `\"Minimum withdraw\nis {MinWithdraw} {currencyID}.\"`\n- **Insufficient balance** — `\"Not enough balance: have {available}\n{currencyID}, need {amount}.\"` (tokens) or `\"Not enough items: have {owned},\nneed {amount}.\"` (NFTs).\n- **Account safety** (`BlockchainAccountSafetyPolicy`, read-only in\n `getDefinitions()`'s `AccountSafety` block) — applies to withdrawals only,\n never deposits: account younger than `MinAccountAgeDays` →\n `\"Account is too fresh. Try again later.\"`; banned account → `\"Account is\nbanned. Contact support.\"`; withdrawing to a wallet address another account\n already used, when `MultiAccountCheckEnabled` +\n `BanOnSharedWithdrawalAddress` are both on, **bans the account on the\n spot** and returns `\"Account banned. Contact support.\"`\n- **Compliance / KYC** (`CryptoCurrencyDefinition.Limits`, per currency) —\n checked in USD-equivalent of the requested amount:\n - Above `Limits.KycRequiredAboveUsd` without `Kyc.Status === \"Verified\"` →\n `\"KYC verification required for withdrawals above {threshold} USD.\"`\n - This UTC calendar day's spend would exceed `Limits.DailyWithdrawUsd`\n (window resets at 00:00 UTC, not a rolling 24h window) →\n `\"Daily withdraw limit exceeded ({spentSoFar} + {thisAmount} >\n{dailyLimit} USD).\"`\n - This UTC calendar month's spend would exceed `Limits.MonthlyWithdrawUsd`\n (window resets 00:00 UTC on the 1st) → `\"Monthly withdraw limit exceeded\n({spentSoFar} + {thisAmount} > {monthlyLimit} USD).\"`\n - Any `Limits` field can be absent/null, which disables that specific\n check for that currency. The daily/monthly counters live server-side on\n `UserCryptoCurrencyState.Compliance` (not exposed as its own client\n method) and reset at UTC day/month boundaries — there is no way to read\n \"USD spent so far today\" from the client ahead of a request; read it off\n a rejection's `error` string instead.\n- **Collective pool cap** — independent of the player's own balance, the\n title's whole player-withdrawable pool for that (network, currency) pair\n can be exhausted: `\"Title users-withdrawable limit reached: available\n{available} {currencyID}, requested {amount}.\"` This is a title-wide\n economic limit, not specific to one player — if you see it, don't retry\n immediately.\n- **Platform commission** — a platform-wide withdrawal commission percent can\n reduce the net payout; if it would consume the entire requested amount,\n the request is rejected outright: `\"Withdrawal amount is fully consumed by\nplatform commission.\"` Otherwise the withdrawal proceeds and\n `NetAmountNative` reflects the amount after commission (see\n [Gotchas](#gotchas)).\n\nNone of these are configurable or visible as a single \"can I withdraw right\nnow\" flag — the practical pattern is: build the request, call it, and render\n`error` on failure. Use `getDefinitions()`'s `AccountSafety` block and the\ncurrency's `Limits` (from `getDefinitions()`'s sibling `CryptoCurrencies` map)\nonly for soft, non-authoritative UI hints (e.g. \"KYC may be required above\n$X\").\n\n## Reading state and reacting to changes\n\n```ts\n// On-chain activity state (only present after getUserState()):\nconst bc = client.data.user.state?.Blockchain;\nbc?.LinkedWallets; // Record<networkID, LinkedWalletInfo>\nbc?.PendingWithdrawals; // PendingWithdrawalRef[] — light refs, not full tx docs\nbc?.Kyc; // UserKycState\nbc?.Stats; // BlockchainStats (deposit/withdrawal counters & volume)\n\n// Crypto balances (decimal-as-string), same cache Currency module reads:\nclient.data.user.getCryptoCurrencyAmount(\"usdt\");\n\n// Definitions (cached after getDefinitions()):\nimport type { BlockchainDefinitions } from \"@idosgames/core\";\nconst defs = client.data.config.getSection<BlockchainDefinitions>(\"Blockchain\");\n```\n\nSubscribe with `client.on(...)`; each returns an unsubscribe fn:\n\n- `blockchain:definitionsLoaded` → `BlockchainConfigResponse`\n- `blockchain:userStateLoaded` → `UserBlockchainStateResponse`\n- `blockchain:tokenDeposited` → `DepositTokenResponse`\n- `blockchain:nftDeposited` → `DepositNFTResponse`\n- `blockchain:tokenWithdrawalRequested` → `TokenWithdrawalResponse`\n- `blockchain:nftWithdrawalRequested` → `NFTWithdrawalResponse`\n- `blockchain:transactionHistoryLoaded` → `TransactionHistoryResponse`\n- `blockchain:withdrawalRetried` → `RetryWithdrawalResponse`\n- `blockchain:withdrawalConfirmed` → `ConfirmWithdrawalResponse`\n- `blockchain:donatedToDeveloper` → `DonationResponse`\n- `blockchain:donatedToUsersPool` → `DonationResponse`\n\n**Cache writes are not uniform across this module — read this carefully:**\n\n- `getUserState()` is the only call that writes `client.data.user.state.Blockchain`\n (`LinkedWallets`, `PendingWithdrawals`, `Kyc`, `Stats`) and fires the coarse\n `user:blockchainUpdated` (+ `user:anyUpdated`).\n- `depositToken` / `requestTokenWithdrawal` patch only the crypto **balance**\n (`InventoryV2.CryptoCurrencies`) via a decimal delta, firing\n `user:inventoryUpdated` (+ `user:anyUpdated`) — **not** `user:blockchainUpdated`.\n- `depositNFT` / `requestNFTWithdrawal` patch inventory (items and/or\n currencies) via the shared `Resources` resource-operation pipeline, firing\n `user:inventoryUpdated` (and `user:virtualCurrencyUpdated` if VC moved) —\n again **not** `user:blockchainUpdated`.\n- `getTransactionHistory`, `retryWithdrawal`, `confirmWithdrawal`,\n `donateToDeveloper`, `donateToUsersPool` only emit their own\n `blockchain:*` event — they don't touch `client.data.user.state` at all.\n\nPractical consequence: after a deposit or withdrawal request, your **balance**\nis fresh in the cache, but `client.data.user.state.Blockchain.PendingWithdrawals`\nand `.Stats` are stale until you call `getUserState()` again. Re-fetch\n`getUserState()` after a withdrawal request/confirm/retry if your UI shows the\npending-withdrawals list or stats.\n\n**`StateDelta` / `Inventory` — the response already carries what changed, if\nyou want to apply it yourself instead of re-fetching.** `DepositTokenResponse`,\n`TokenWithdrawalResponse`, `NFTWithdrawalResponse`, and\n`ConfirmWithdrawalResponse` all carry an optional `StateDelta`\n(`BlockchainStateDelta`): a signed `CryptoBalances` delta per currency\n(`{ AmountDelta, FrozenDelta, UpdatedAt }` — add, don't overwrite), a\n`PendingAdded` ref (this call's newly-added pending withdrawal, if any), and\n`PendingRemovedIDs` (pending withdrawals this call confirmed or lazily\nexpired). `DepositNFTResponse` / `NFTWithdrawalResponse` similarly carry an\n`Inventory` (`InventoryDelta`) for the NFT's `UnstackableItems` instance —\nsame shape/semantics as the character-system module's `Inventory` deltas\n(`ChangedInstances` to upsert, `RemovedInstanceIDs` to drop). This mirrors the\nself-sufficient-response pattern used elsewhere in this SDK (see the\ncharacter-system skill) so a client that wants to reconcile\n`PendingWithdrawals`/balances/instances without another round trip can do so\nstraight from the mutating call's response. **Note:** `BlockchainService`\nitself does not auto-apply `StateDelta`/`Inventory` into\n`client.data.user.state.Blockchain` today — only the crypto **balance**\n(via the existing `AmountNative`-based patch) and item `Resources` are\napplied automatically. If you need `PendingWithdrawals` reconciled without a\nfull `getUserState()` refetch, read `result.data.StateDelta` yourself. Both\nare `null`/absent on an idempotent replay (nothing new to apply).\n\n```ts\nconst off = client.on(\"blockchain:tokenWithdrawalRequested\", (r) => {\n console.log(`Withdrawal ${r.TitleTransactionID} expires at ${r.ExpiresAt}`);\n});\n// later: off();\n```\n\n## Recipes\n\n### Load config + state on a wallet/blockchain screen\n\n```ts\nawait client.blockchain.getDefinitions();\nawait client.blockchain.getUserState();\n\nconst defs = client.data.config.getSection<BlockchainDefinitions>(\"Blockchain\");\nconst bc = client.data.user.state?.Blockchain;\n\nfor (const [networkID, net] of Object.entries(defs?.Networks ?? {})) {\n if (!net.DepositsEnabled && !net.WithdrawalsEnabled) continue;\n // render a network card; net.NftCollections binds contracts to item catalogs\n}\nbc?.Kyc?.Status; // gate withdrawal UI on KYC if the title requires it\n```\n\n### Deposit a token (player already sent it on-chain)\n\n```ts\nconst res = await client.blockchain.depositToken(\"polygon\", \"0xabc123...\");\nif (!res.ok) return showError(res.error); // e.g. \"Transaction not found on chain.\",\n// \"Not enough confirmations (required 12). Try again in a few minutes.\",\n// \"Transaction hash already used.\"\n\nres.data.CurrencyID; // e.g. \"usdt\"\nres.data.AmountNative; // decimal string credited\n// Balance is already updated in the cache:\nclient.data.user.getCryptoCurrencyAmount(res.data.CurrencyID!);\n```\n\n### Full withdrawal lifecycle: request -> submit on-chain -> confirm, with a retry-after-failure path\n\n```ts\n// 1. Request the withdrawal — debits in-game immediately, returns a signature payload.\nconst req = await client.blockchain.requestTokenWithdrawal(\n \"usdt\",\n \"polygon\",\n \"0xPlayerWallet...\",\n \"25.00\",\n);\nif (!req.ok) return showError(req.error); // e.g. \"Not enough balance: have 10 usdt, need 25.00.\",\n// \"KYC verification required for withdrawals above 1000 USD.\",\n// \"Title users-withdrawable limit reached: available 5 usdt, requested 25.00.\"\n// — see \"Withdrawal gates\" above for the full list.\n\nconst { TitleTransactionID, EvmSignature, ExpiresAt } = req.data;\n// Balance is already debited (gross amount) in the cache.\n\n// 2. Hand EvmSignature (or SolanaSignature on a Solana network) to the\n// player's wallet SDK to submit the on-chain transaction yourself —\n// this SDK does not sign/broadcast. That step can fail (rejected in\n// wallet, gas issue).\n\n// 2a. If on-chain submission failed WHILE the transaction is still Pending\n// (before ExpiresAt), retry — this re-issues a fresh signature WITHOUT\n// debiting again:\nconst retry = await client.blockchain.retryWithdrawal(TitleTransactionID!);\nif (!retry.ok) return showError(retry.error); // e.g. \"Transaction is not in Pending state (current: Abandoned).\"\nconst freshSignature = retry.data.EvmSignature ?? retry.data.SolanaSignature;\n// Submit freshSignature on-chain instead, then continue to step 3.\n//\n// IMPORTANT: retryWithdrawal only works while the transaction is Pending. If\n// ExpiresAt already passed, the backend has lazily moved it to Abandoned and\n// retryWithdrawal will reject it — there is no \"re-request\" for an Abandoned\n// withdrawal (the asset was already debited and is not refunded). The only\n// way to still complete it is confirmWithdrawal with a hash, if the player\n// actually managed to submit the original signature before it was swept —\n// see the Gotchas section.\n\n// 3. Once the wallet actually broadcasts the transaction, tell the backend\n// the resulting on-chain hash so it can verify and close out the withdrawal:\nconst confirm = await client.blockchain.confirmWithdrawal(\n TitleTransactionID!,\n \"0xOnChainTxHash...\",\n);\nif (!confirm.ok) return showError(confirm.error);\nconfirm.data.Status; // e.g. \"Completed\" once the chain confirms it\n\n// 4. Refresh state — request/retry/confirm don't touch Blockchain cache themselves.\nawait client.blockchain.getUserState();\nclient.data.user.state?.Blockchain?.PendingWithdrawals; // should no longer list it once Completed\n```\n\n### KYC-gated withdrawal\n\nThe client never decides whether KYC is required — the backend compares the\nwithdrawal's USD-equivalent against the currency's configured threshold at\nrequest time. Use `Kyc.Status` only to pre-empt an obvious rejection in the\nUI; still branch on the real error:\n\n```ts\nawait client.blockchain.getUserState();\nconst kyc = client.data.user.state?.Blockchain?.Kyc;\n\nif (kyc?.Status !== \"Verified\") {\n // Optional UX nicety: warn before the call for large amounts. This SDK has\n // no startKyc/submitKyc method — verification happens through whatever KYC\n // provider integration the title uses outside this SDK; Kyc here only\n // reflects the result.\n}\n\nconst req = await client.blockchain.requestTokenWithdrawal(\n \"usdt\",\n \"polygon\",\n \"0xPlayerWallet...\",\n \"5000.00\",\n);\nif (!req.ok) {\n if (req.error.startsWith(\"KYC verification required\")) {\n // Route the player to the title's KYC verification flow.\n }\n return showError(req.error);\n}\n```\n\n### Deposit / withdraw an NFT\n\n```ts\n// Deposit: player already transferred the NFT to the vault address on-chain.\nconst dep = await client.blockchain.depositNFT(\"ethereum\", \"0xNftDepositTx...\");\nif (!dep.ok) return showError(dep.error);\ndep.data.ItemID; // the in-game item granted\ndep.data.Resources; // already applied to inventory in the cache\n\n// Withdraw: consumes the in-game item, returns a signature to submit on-chain.\nconst wd = await client.blockchain.requestNFTWithdrawal(\n \"sword-of-embers-inst-1\", // ItemID (per NFTWithdrawalResponse/BlockchainRequest shape)\n \"ethereum\",\n \"0xPlayerWallet...\",\n \"1\",\n);\nif (!wd.ok) return showError(wd.error);\nwd.data.TitleTransactionID; // use with retryWithdrawal / confirmWithdrawal exactly as tokens above\n\n// ERC-721 unique NFT: pass the specific instance to tokenize. level/itemInstanceID\n// are the trailing optional args — see the Methods table above.\nconst wd721 = await client.blockchain.requestNFTWithdrawal(\n \"sword-of-embers\",\n \"ethereum\",\n \"0xPlayerWallet...\",\n \"1\",\n undefined, // category\n 1, // level\n \"sword-of-embers-inst-1\", // ItemInstanceID — required for ERC-721 bindings\n);\n```\n\n### Edge case: not logged in / missing args\n\n```ts\nconst res = await client.blockchain.depositToken(\"\", \"0xabc\");\n// res.ok === false, res.reason === \"client\" — \"NetworkID is required.\" — no network call.\n\nconst res2 = await client.blockchain.getUserState();\n// If called before auth.loginWithDeviceID() (or any auth.* login):\n// res2.ok === false, res2.reason === \"unauthorized\"\n```\n\n### Donate crypto (no personal credit)\n\n```ts\nconst res = await client.blockchain.donateToDeveloper(\n \"polygon\",\n \"0xdonateTx...\",\n);\nif (!res.ok) return showError(res.error);\nres.data.Target; // \"Developer\" — confirms which pool bucket it landed in\n\n// donateToUsersPool is identical in shape, credits the users' pool bucket instead:\nawait client.blockchain.donateToUsersPool(\"polygon\", \"0xdonateTx2...\");\n```\n\n## Gotchas\n\n- **Withdrawal request debits immediately; the on-chain leg is separate and\n can fail.** `requestTokenWithdrawal`/`requestNFTWithdrawal` already took the\n asset from the player before any on-chain transaction exists. If the\n player's wallet fails to submit (rejected, gas issue) **while the\n transaction is still `Pending`**, don't ask them to request again — that\n would debit twice. Use `retryWithdrawal` with the same\n `TitleTransactionID` to get a fresh signature without a new charge. This\n only works before `ExpiresAt` — see the next two points for what happens\n after.\n- **`retryWithdrawal` vs `confirmWithdrawal` are opposite ends of the same\n flow.** Retry re-issues the _signed payload_ before submission (nothing has\n reached the chain yet); confirm reports the _resulting tx hash_ after\n submission (the chain now has it). Calling confirm with a hash from a\n transaction that never actually landed on-chain will simply fail\n server-side verification — don't fabricate a hash to \"force\" completion.\n- **`ExpiresAt` is real, expiry does not refund the player, and — contrary to\n what the name suggests — an expired withdrawal is NOT retryable.** A\n withdrawal signature is time-boxed (`TokenWithdrawalResponse.ExpiresAt` /\n `NFTWithdrawalResponse.ExpiresAt`, driven by\n `BlockchainAccountSafetyPolicy.PendingWithdrawalTtlHours`). Once it passes\n without a submission, the backend lazily transitions the transaction to\n **`Abandoned`** (not `Expired` — that enum value exists but this backend\n path never assigns it) and drops it off `PendingWithdrawals` — but the\n already-debited asset is **not** credited back; this is intentional, not a\n bug. Critically, `retryWithdrawal` requires the transaction to still be\n `Pending` — calling it on an `Abandoned` one fails with `\"Transaction is\nnot in Pending state (current: Abandoned).\"` There is no \"re-request\"\n operation for an abandoned withdrawal.\n- **A withdrawal can still be confirmed after it's `Abandoned`.** If the\n player submits late — after `ExpiresAt` passed and the backend already\n swept it to `Abandoned` — `confirmWithdrawal` still accepts it as long as\n the on-chain transaction verifies (the signature itself doesn't expire\n on-chain, only the title's own bookkeeping window does). Don't treat an\n `Abandoned` transaction as unrecoverable if the player insists they\n submitted it; calling `confirmWithdrawal` with the resulting hash is still\n the right move, and is in fact the _only_ way to close out an\n already-expired-but-actually-submitted withdrawal.\n- **`retryWithdrawal` only works on a `Pending` transaction the caller owns.**\n It fails with `\"Transaction not found.\"` for an unknown or someone else's\n `TitleTransactionID`, `\"Transaction is not in Pending state (current:\n{status}).\"` if it already completed/failed/was abandoned, or\n `\"Signature data not found for this transaction.\"` if there's nothing to\n reissue. A banned account additionally gets `\"Account is banned. Contact\nsupport.\"` on retry (deposits stay allowed for banned accounts; retrying a\n withdrawal does not).\n- **Gross vs. net amounts on token withdrawals.** `AmountNative` is what was\n debited from the player (gross); `NetAmountNative` is what actually gets\n paid out on-chain after a platform commission percentage **and** an\n optional on-chain burn are deducted (`NetAmountNative = AmountNative −\ncommission − BurnAmountNative`). Show the player the net figure they'll\n receive, not the gross debit, to avoid support tickets about a \"missing\"\n amount. NFT withdrawals have no such split — there's no `NetAmountNative`\n on `NFTWithdrawalResponse`.\n- **Burn on withdrawal (EVM-only).** `TokenWithdrawalResponse.BurnAmountNative`\n is the amount burned on-chain (sent to the DEAD address) for this\n withdrawal, driven by the currency's `WithdrawalBurnPercent` (see the\n currency-system skill) — `0` if burn is disabled for that currency or the\n network is Solana. The raw-units counterpart, `WithdrawalSignatureResponse.\nBurnAmount`, is bound into the signed hash and must be passed to the\n contract call verbatim, same as `Amount`/`Nonce` — `@idosgames/wallet`'s\n `submitEvmTokenWithdrawal` does this for you; a client calling\n `withdrawERC20` directly must include it too, or the signature check fails.\n- **`client.data.user.state.Blockchain` goes stale after deposits/withdrawal\n requests.** Only `getUserState()` refreshes `LinkedWallets`,\n `PendingWithdrawals`, `Kyc`, and `Stats`. A deposit/withdrawal call updates\n your _balance_/_inventory_ cache correctly, but if your UI also shows the\n pending-withdrawals list or lifetime stats, re-call `getUserState()`\n afterward (see the withdrawal recipe above).\n- **Deposits are reporting, not sending.** `depositToken`/`depositNFT` don't\n move any asset on-chain — they tell the backend \"verify this transaction\n hash and credit me.\" The actual on-chain transfer to the platform's pool/\n vault address must already have happened via a wallet SDK before you call\n these.\n- **This SDK never signs or broadcasts.** `EvmSignature`/`SolanaSignature`\n payloads are inputs to a wallet SDK/contract call that happens outside\n `@idosgames/core`. Don't look for a \"submit on-chain\" method here — there\n isn't one; `confirmWithdrawal` only reports the result afterward. The\n `@idosgames/wallet` companion package is that outside layer — it submits the\n signature on-chain and calls `confirmWithdrawal` for you.\n- **Donations never touch personal balances.** `donateToDeveloper` /\n `donateToUsersPool` intentionally don't credit the player anything and\n don't touch `client.data.user.state` — they only emit their own\n `blockchain:donated*` event for a confirmation toast/receipt.\n- **Render from the cache, handle the error from the result.** The happy\n path updates the relevant cache slice + emits an event; the failure path\n gives you `reason` + `error`. Use `reason` to decide behavior (retry on\n `\"connection\"`, re-auth on `\"unauthorized\"`, toast the `error` on\n `\"server\"`).\n\n## Full reference\n\n[references/data-model.md](references/data-model.md) — every config and\nstate field: network definitions, NFT collection bindings, account-safety\npolicy, KYC state, transaction documents, the withdrawal-gate limits, and the\nEVM/Solana withdrawal signature payload shapes. Read it when building network\npickers, a transaction-history table, or KYC/limit-aware withdrawal UI. For\nthe shared `ResourceConsume`/`ResourceGrant`/`ResourceOperation`\ncost-and-reward shapes riding along on `depositNFT`/`requestNFTWithdrawal`,\nand for the full `CryptoCurrencyDefinition` shape (`Limits`, `Networks[].\nMinWithdraw`, `Permissions`) that the withdrawal gates enforce,\nsee the currency-system skill.\n",
4
+ "content": "---\nname: blockchain-system\ndescription: >-\n Bridge in-game assets on-chain in a game on the iDosGames TypeScript SDK\n (@idosgames/core) via client.blockchain (BlockchainService): load blockchain\n network/config definitions, load the player's on-chain state (linked\n wallets, pending withdrawals, KYC, stats), deposit a token or NFT from a\n wallet into the game, request a token or NFT withdrawal out to a wallet,\n read on-chain transaction history, retry a still-pending withdrawal's\n signature, confirm a withdrawal's on-chain tx hash, and donate crypto to\n the developer or a users' pool. Use this whenever the user is working in\n the iDosGames TS SDK or its game templates (board-game, idle-rpg) and wants crypto wallets, NFT\n deposits/withdrawals, token bridging, on-chain asset transfers, KYC status,\n or otherwise touches client.blockchain, BlockchainService,\n BlockchainDefinitions, UserBlockchainState, DepositTokenResponse,\n TokenWithdrawalResponse, or NFTWithdrawalResponse — even if they don't name\n the module explicitly.\n---\n\n# Blockchain system (iDosGames TS SDK)\n\nThe Blockchain module bridges in-game assets to and from real wallets on\nsupported chains (EVM and Solana networks). A player can deposit a token or\nNFT they already sent on-chain (crediting their in-game balance/inventory),\nor request a withdrawal that pays an in-game token/NFT out to their wallet\n(debiting their in-game balance/inventory and producing a signature the\nplayer submits on-chain themselves). Everything is **server-authoritative**:\nthe client reports/requests, the backend validates the transaction against\nthe chain, applies rules (network enabled, KYC, account-safety policy), and\nthe SDK mirrors the confirmed result into a local cache your UI reads. You\nnever credit/debit balances yourself.\n\nThis skill is for **using** the production `BlockchainService`, not for\nporting or extending it, and not for signing/broadcasting transactions\nyourself — this SDK reports deposits and requests withdrawals; actually\nsending the on-chain transaction (the deposit transfer, or broadcasting a\nwithdrawal signature) happens with a wallet SDK outside this client.\n\n> **The on-chain half is the `@idosgames/wallet` companion package.** It\n> connects browser & mobile wallets (EVM via wagmi/viem/WalletConnect, Solana\n> via wallet-adapter) and runs the exact RewardPool contract calls, threading\n> them through this service's request → submit → confirm / approve → deposit →\n> report lifecycle. If the user wants to actually connect a wallet and move\n> tokens/NFTs (not just call `client.blockchain.*`), reach for that package —\n> see its README. Everything below documents the server-authoritative\n> `client.blockchain` surface that `@idosgames/wallet` builds on. The wallet\n> package's EVM surface covers both NFT standards: `submitEvmNftWithdrawal` /\n> `depositNftEvm` (+ `erc1155Abi`) for ERC-1155 collections, and\n> `submitEvmNftWithdrawal721` / `depositNftEvm721` (+ `erc721Abi`) for\n> ERC-721 unique-item collections (4-arg `safeTransferFrom`, no `id`/`amount`\n> — the token is always qty 1). `submitEvmTokenWithdrawal`'s `withdrawERC20`\n> call now also threads `sig.BurnAmount` through (see\n> [Burn on withdrawal](#gotchas) below) — the ABI/contract call order changed,\n> so an app pinned to an older `@idosgames/wallet` build will revert on-chain\n> against an updated RewardPool contract.\n\n> **Never import `@idosgames/wallet/react` (or `/react/solana`) from a file\n> that loads on startup.** Those subpaths pull in Reown AppKit, and AppKit is\n> deliberately _not_ a dependency of a generated project — the live preview\n> resolves every declared dependency up front and times out on AppKit's tree.\n> A static import therefore blanks the preview before any game code runs\n> (`Could not find dependency: '@reown/appkit-adapter-wagmi'`), while the real\n> build stays green — that mismatch is the signature of this mistake.\n> Two rules keep both working:\n>\n> - **Sign-in button:** import `LazyWalletLogin` / `LazySolanaWalletLogin` from\n> `@idosgames/wallet/react/lazy` (that entry has no AppKit in its graph; it\n> also re-exports the chains as plain objects — never import chains from\n> `wagmi/chains` or `viem/chains`, that barrel breaks the preview too).\n> - **In-game deposit/withdraw panel:** import `LazyWalletPanel` from\n> `@idosgames/wallet/react/lazy` and pass it the authenticated `client` (a\n> prop, like the login button — never a module context). Same lazy contract:\n> AppKit stays out of the startup graph. Don't hand-roll your own\n> `await import(\"./PanelImpl\")` wrapper — `LazyWalletPanel` is that wrapper.\n> Because the wallet config is memoised per WalletConnect project id, the\n> panel reuses the wallet the player connected at sign-in: same store, so it\n> opens already-connected, no second tap and no second modal. This is exactly\n> how the board-game and idle-rpg modules wire their `WalletPanel.tsx`.\n> ONE panel for EVM and Solana: it reads the title's networks and loads the\n> right one — same form, deposit and withdraw on both (Solana through the\n> platform pool, `createPlatformPoolAdapter`). The base already puts it in the\n> lobby header (`src/base/lobby/WalletButton.tsx`) — don't add a second one.\n\n> **The game cannot reach the wallet while it is embedded in an idosgames.com iframe** (owner's\n> decision, 2026-09-17 — deposit/withdraw goes through the buttons in the site's own wallet card).\n> A wallet BUTTON inside the frame calls `openPlatformWalletPanel()` (from `@idosgames/wallet/react/lazy`)\n> — the site shows its own wallet card; that is what the base's lobby button does.\n> `LazyWalletPanel` itself renders nothing there, and\n> `LazyWalletLogin` / `LazySolanaWalletLogin` stay a working \"Sign in with wallet\" button — inside\n> the frame the SITE's connected wallet signs the engine's login message for the game\n> (`loginWithWalletViaPlatform` from `@idosgames/wallet`, used by the buttons automatically). Never\n> show a \"use idosgames.com\" notice inside the game. Every flow function that talks to the wallet\n> directly (`depositTokenEvm`, `withdrawTokenEvm`, `loginWithWalletEvm`, their Solana equivalents,\n> `payWithWalletEvm`) refuses with `WALLET_USE_SITE_PANEL` inside a frame. A game opened by its own\n> direct link (not embedded) is unaffected — every one of these works exactly as before there.\n\n### Login mode and play access by token balance (`cfg.Blockchain.PlayAccess`)\n\nA title can require players to HOLD tokens to play. The publisher picks one of three login modes:\n\n| `Mode` | Who can sign in | Balance check |\n| --------------------- | ----------------------------- | -------------------------------------------- |\n| `Open` (default) | every method, guests included | none |\n| `AnyWithLinkedWallet` | every method except guest | the wallet the player linked by signature |\n| `WalletOnly` | wallet login only | the wallet they signed in with — and only it |\n\nIn `WalletOnly` the account must BE the wallet's account: an account created another way before the\nmode was switched on gets `PLAY_ACCESS_WALLET_LOGIN_ONLY` on every check, and `linkWallet` refuses\nany wallet but the account's own with the same code — don't offer \"link wallet\" there, offer\n\"log out and sign in with your wallet\".\n\nRequirements are `TokenGates` (`CurrencyID`, `MinBalance`, `BalanceSource`: `OnChain` wallet /\n`InGame` game balance — no wallet needed / `Combined`; `NetworkID` for wallet ones). The SERVER\nchecks the balance on every login and session refresh — silently, no signature — and on\n`client.blockchain.confirmPlayAccess()`. Gameplay calls without a valid pass fail with HTTP 403\n`PLAY_ACCESS_REQUIRED`; `Blockchain` itself, account linking and the login-time `User` reads stay open.\n\n**The host template already handles all of it — don't rebuild it.** `mountHost` shows the\nplay-access screen (`renderPlayAccess`, the template's `src/PlayAccessScreen.tsx` over\n`DefaultPlayAccessScreen`) instead of the game whenever `client.auth.playAccess?.Granted === false`\nor `playAccess:required` fires, and the template's login screen hides the methods the mode refuses\n(`client.auth.getAuthOptions()` → `PlayAccessMode`). \"Link wallet\" on that screen is\n`LazyWalletLogin mode=\"link\"` (`renderWalletLink` in `src/walletLogin.tsx`); inside the\nidosgames.com frame the site's wallet signs the link (`linkWalletViaPlatform`).\n\nClient surface, if you roll your own screen: `client.auth.playAccess` (+ `playAccess:changed`),\n`client.blockchain.getPlayAccess()` (mode, requirements, the player's signature-linked wallets, last\ncheck), `client.blockchain.confirmPlayAccess(networkID?)` (choose a linked wallet and check now),\n`client.auth.linkWallet(address, networkID, signature?)` (two steps; the second returns the pass\nchecked against that wallet), `linkWalletEvm` / `linkWalletSolana` / `linkWalletViaPlatform` in\n`@idosgames/wallet`. Refusal codes: `PLAY_ACCESS_WALLET_REQUIRED`,\n`PLAY_ACCESS_WALLET_NETWORK_NOT_GATED`, `PLAY_ACCESS_GUEST_DISABLED`, `PLAY_ACCESS_WALLET_LOGIN_ONLY`,\n`PLAY_ACCESS_CHECK_FAILED` (the RPC could not be read — NOT an empty wallet; check again), or the\nrequirement's own `DenyMessage`. A login or refresh never fails for lack of balance — in every mode\nthe session is issued and the game stays closed until the pass is granted.\n\n### Operation category (`game_topup` by default)\n\nThe updated RewardPool contract tags every deposit/withdrawal with a string\n**category** (default `\"game_topup\"`; `\"community_reward\"` is the other known\nvalue, and arbitrary strings are allowed). On a **withdrawal** the server signs\nthe category into the on-chain hash and returns it on the signature payload\n(`EvmSignature.Category` / `.TitleID`); whoever submits the transaction **must\npass the same value on-chain verbatim** or the contract rejects the signature —\n`@idosgames/wallet` does this for you. Pass it as the optional last arg to\n`requestTokenWithdrawal`/`requestNFTWithdrawal` (omit → `\"game_topup\"`). On a\n**deposit** the category is read back from the on-chain transaction, so you\ndon't pass it to `depositToken`/`depositNFT`. It also appears on transaction\ndocuments as `Category`. Import the constants from `@idosgames/core`:\n`BlockchainOperationCategory.GameTopUp` / `.CommunityReward`.\n\n## Mental model: deposits vs. withdrawals\n\n- **Deposit** = the player already sent tokens/an NFT to the platform's pool\n or vault address on-chain. The client then calls `depositToken`/`depositNFT`\n with that transaction's hash so the backend can verify it and credit the\n player in-game. One-shot: the credit happens directly on a successful call.\n- **Withdrawal** = the player wants an in-game token/NFT sent out to their\n wallet. The client calls `requestTokenWithdrawal`/`requestNFTWithdrawal`,\n which **debits in-game immediately** and returns a signed payload\n (`EvmSignature` or `SolanaSignature`) the player's wallet must submit\n on-chain to actually receive the asset. This is a **multi-step, async\n flow** — see [Recipes](#recipes) for the full lifecycle, including what to\n do when the on-chain submission fails.\n\nBoth flows are per-network: every call takes a `networkID` that must match one\nof the title's configured `Networks` (EVM or Solana), each with its own\ndeposit/withdrawal enable flags, contract/vault addresses, and (for NFTs) a\ncollection binding to an item catalog. Withdrawals additionally run through a\nlong chain of server-side gates (balances, per-network minimums, account\nsafety, KYC, daily/monthly compliance limits, a collective title-wide pool\ncap, and platform commission) — see\n[Withdrawal gates](#withdrawal-gates-what-can-reject-a-request) for the full\nlist with verbatim error strings.\n\nFor the full config/state field shapes (network definitions, NFT collection\nbindings, KYC tiers, transaction documents, signature payloads), read\n[references/data-model.md](references/data-model.md). You do **not** need it\nto call the methods — only to drive richer UI (network pickers, KYC gates,\ntransaction history tables).\n\n## Setup\n\n```ts\nimport { createIDosGamesClient } from \"@idosgames/core\";\n\nconst client = createIDosGamesClient({ titleID: \"your-title-id\" });\nawait client.auth.loginWithDeviceID(); // or any auth.* method\n\nconst blockchain = client.blockchain; // the BlockchainService\n```\n\nEvery blockchain method requires an authenticated session. Without one they\nreturn `{ ok: false, reason: \"unauthorized\" }` — they do not throw.\n\n## Methods\n\nAll methods return `Promise<OperationResult<T>>`: a discriminated union that\nis either `{ ok: true, data }` or `{ ok: false, reason, error }`. Always\nbranch on `result.ok` before touching `result.data`. `reason` is one of\n`\"client\"` (missing/empty required arg — rejected before any network call),\n`\"unauthorized\"`, `\"throttled\"` (fired the same endpoint again inside the\n600ms client-side throttle window), `\"connection\"` (transient, offer Retry),\n`\"validation\"` (response/schema drift), or `\"server\"` (backend rejected it —\n`error` carries the exact backend message). Withdrawals in particular can be\nrejected by a long chain of server-side gates — see\n[Withdrawal gates](#withdrawal-gates-what-can-reject-a-request) below for the\nfull list with verbatim error strings.\n\n| Method | Purpose | `data` on success |\n| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ----------------------------- |\n| `getDefinitions()` | Load the title's blockchain config: networks, NFT bindings, crypto currencies. | `BlockchainConfigResponse` |\n| `getUserState()` | Load this player's on-chain state: linked wallets, pending withdrawals, KYC, stats, crypto balances. | `UserBlockchainStateResponse` |\n| `depositToken(networkID, transactionHash)` | Report an on-chain token transfer; credits the matching crypto balance. | `DepositTokenResponse` |\n| `depositNFT(networkID, transactionHash)` | Report an on-chain NFT transfer; grants the matching in-game item. | `DepositNFTResponse` |\n| `requestTokenWithdrawal(currencyID, networkID, walletAddress, amount, category?)` | Debit a crypto balance and get a signed payload to withdraw on-chain. | `TokenWithdrawalResponse` |\n| `requestNFTWithdrawal(itemID, networkID, walletAddress, amount, category?, level?, itemInstanceID?)` | Consume an in-game item and get a signed payload to withdraw the NFT on-chain. | `NFTWithdrawalResponse` |\n| `getTransactionHistory(limit?)` | Load recent token + NFT transaction documents (default limit 50). | `TransactionHistoryResponse` |\n| `retryWithdrawal(titleTransactionID)` | Re-issue a fresh signature for a still-`Pending` withdrawal without re-debiting. | `RetryWithdrawalResponse` |\n| `confirmWithdrawal(titleTransactionID, onChainTransactionHash)` | Tell the backend the signed withdrawal was submitted on-chain, with its tx hash. | `ConfirmWithdrawalResponse` |\n| `donateToDeveloper(networkID, transactionHash)` | Report an on-chain transfer as a donation to the developer pool (no personal credit). | `DonationResponse` |\n| `donateToUsersPool(networkID, transactionHash)` | Report an on-chain transfer as a donation to the users' pool (no personal credit). | `DonationResponse` |\n\nAll string args (`networkID`, `transactionHash`, `currencyID`,\n`walletAddress`, `amount`, `itemID`, `titleTransactionID`,\n`onChainTransactionHash`) are required and checked client-side before any\nnetwork call — an empty one short-circuits with `reason: \"client\"`. `amount`\nis a decimal string for token withdrawals and an integer-as-string for NFT\nwithdrawals / not used for deposits (deposit amounts come from the verified\non-chain transaction, not from the client). `getTransactionHistory(limit)`\ndefaults to `50`, is capped at **200** server-side (values above are silently\nclamped, values `<= 0` fall back to 50), and is sent as `Amount` on the wire\n(reused request field, not an actual currency amount).\n\n`requestNFTWithdrawal`'s trailing `level`/`itemInstanceID` are both optional\nand only matter for NFT catalogs with leveled or unique (ERC-721) bindings:\n`level` selects which leveled instance/tokenId to withdraw (omit or `1` →\nbase level, prior behavior); `itemInstanceID` is **required** when the\nitem's NFT binding is ERC-721 — it tells the server exactly which\nunstackable instance to debit and tokenize (preserving its Level/RemainingUses/\nCustomData in the on-chain registry via a separate ItemBridge contract).\nBoth are ignored for stackable/ERC-1155 items.\n\nOn success, most methods **mirror the confirmed change into the cache and\nemit an event** — see the next section for exactly which cache each method\ntouches, since it's not uniform across this module.\n\n## Withdrawal gates (what can reject a request)\n\n`requestTokenWithdrawal` / `requestNFTWithdrawal` run through a long chain of\nserver-side checks, each a `reason: \"server\"` failure with a specific `error`\nstring. Surface the string; don't try to pre-validate all of these\nclient-side — the gate list can change without a client update:\n\n- **Global kill switch** — withdrawals can be turned off platform-wide\n independently of any per-network/per-currency flag: `\"Withdrawals are\ncurrently disabled.\"`\n- **Network / currency / binding disabled** — `\"Withdrawals disabled for this\nnetwork.\"`, `\"Withdrawals are disabled for currency '{id}'.\"`, `\"This\ncurrency cannot be withdrawn in this network.\"`, or (currency under\n maintenance) `\"Currency '{id}' is under maintenance. Try again later.\"`\n- **Per-network minimum** — every currency has a `MinWithdraw` for each\n network it's bound to (`CryptoNetworkBinding.MinWithdraw`, see the\n currency-system skill's data-model for the full shape): `\"Minimum withdraw\nis {MinWithdraw} {currencyID}.\"`\n- **Insufficient balance** — `\"Not enough balance: have {available}\n{currencyID}, need {amount}.\"` (tokens) or `\"Not enough items: have {owned},\nneed {amount}.\"` (NFTs).\n- **Account safety** (`BlockchainAccountSafetyPolicy`, read-only in\n `getDefinitions()`'s `AccountSafety` block) — applies to withdrawals only,\n never deposits: account younger than `MinAccountAgeDays` →\n `\"Account is too fresh. Try again later.\"`; banned account → `\"Account is\nbanned. Contact support.\"`; withdrawing to a wallet address another account\n already used, when `MultiAccountCheckEnabled` +\n `BanOnSharedWithdrawalAddress` are both on, **bans the account on the\n spot** and returns `\"Account banned. Contact support.\"`\n- **Compliance / KYC** (`CryptoCurrencyDefinition.Limits`, per currency) —\n checked in USD-equivalent of the requested amount:\n - Above `Limits.KycRequiredAboveUsd` without `Kyc.Status === \"Verified\"` →\n `\"KYC verification required for withdrawals above {threshold} USD.\"`\n - This UTC calendar day's spend would exceed `Limits.DailyWithdrawUsd`\n (window resets at 00:00 UTC, not a rolling 24h window) →\n `\"Daily withdraw limit exceeded ({spentSoFar} + {thisAmount} >\n{dailyLimit} USD).\"`\n - This UTC calendar month's spend would exceed `Limits.MonthlyWithdrawUsd`\n (window resets 00:00 UTC on the 1st) → `\"Monthly withdraw limit exceeded\n({spentSoFar} + {thisAmount} > {monthlyLimit} USD).\"`\n - Any `Limits` field can be absent/null, which disables that specific\n check for that currency. The daily/monthly counters live server-side on\n `UserCryptoCurrencyState.Compliance` (not exposed as its own client\n method) and reset at UTC day/month boundaries — there is no way to read\n \"USD spent so far today\" from the client ahead of a request; read it off\n a rejection's `error` string instead.\n- **Collective pool cap** — independent of the player's own balance, the\n title's whole player-withdrawable pool for that (network, currency) pair\n can be exhausted: `\"Title users-withdrawable limit reached: available\n{available} {currencyID}, requested {amount}.\"` This is a title-wide\n economic limit, not specific to one player — if you see it, don't retry\n immediately.\n- **Platform commission** — a platform-wide withdrawal commission percent can\n reduce the net payout; if it would consume the entire requested amount,\n the request is rejected outright: `\"Withdrawal amount is fully consumed by\nplatform commission.\"` Otherwise the withdrawal proceeds and\n `NetAmountNative` reflects the amount after commission (see\n [Gotchas](#gotchas)).\n\nNone of these are configurable or visible as a single \"can I withdraw right\nnow\" flag — the practical pattern is: build the request, call it, and render\n`error` on failure. Use `getDefinitions()`'s `AccountSafety` block and the\ncurrency's `Limits` (from `getDefinitions()`'s sibling `CryptoCurrencies` map)\nonly for soft, non-authoritative UI hints (e.g. \"KYC may be required above\n$X\").\n\n## Reading state and reacting to changes\n\n```ts\n// On-chain activity state (only present after getUserState()):\nconst bc = client.data.user.state?.Blockchain;\nbc?.LinkedWallets; // Record<networkID, LinkedWalletInfo>\nbc?.PendingWithdrawals; // PendingWithdrawalRef[] — light refs, not full tx docs\nbc?.Kyc; // UserKycState\nbc?.Stats; // BlockchainStats (deposit/withdrawal counters & volume)\n\n// Crypto balances (decimal-as-string), same cache Currency module reads:\nclient.data.user.getCryptoCurrencyAmount(\"usdt\");\n\n// Definitions (cached after getDefinitions()):\nimport type { BlockchainDefinitions } from \"@idosgames/core\";\nconst defs = client.data.config.getSection<BlockchainDefinitions>(\"Blockchain\");\n```\n\nSubscribe with `client.on(...)`; each returns an unsubscribe fn:\n\n- `blockchain:definitionsLoaded` → `BlockchainConfigResponse`\n- `blockchain:userStateLoaded` → `UserBlockchainStateResponse`\n- `blockchain:tokenDeposited` → `DepositTokenResponse`\n- `blockchain:nftDeposited` → `DepositNFTResponse`\n- `blockchain:tokenWithdrawalRequested` → `TokenWithdrawalResponse`\n- `blockchain:nftWithdrawalRequested` → `NFTWithdrawalResponse`\n- `blockchain:transactionHistoryLoaded` → `TransactionHistoryResponse`\n- `blockchain:withdrawalRetried` → `RetryWithdrawalResponse`\n- `blockchain:withdrawalConfirmed` → `ConfirmWithdrawalResponse`\n- `blockchain:donatedToDeveloper` → `DonationResponse`\n- `blockchain:donatedToUsersPool` → `DonationResponse`\n\n**Cache writes are not uniform across this module — read this carefully:**\n\n- `getUserState()` is the only call that writes `client.data.user.state.Blockchain`\n (`LinkedWallets`, `PendingWithdrawals`, `Kyc`, `Stats`) and fires the coarse\n `user:blockchainUpdated` (+ `user:anyUpdated`).\n- `depositToken` / `requestTokenWithdrawal` patch only the crypto **balance**\n (`InventoryV2.CryptoCurrencies`) via a decimal delta, firing\n `user:inventoryUpdated` (+ `user:anyUpdated`) — **not** `user:blockchainUpdated`.\n- `depositNFT` / `requestNFTWithdrawal` patch inventory (items and/or\n currencies) via the shared `Resources` resource-operation pipeline, firing\n `user:inventoryUpdated` (and `user:virtualCurrencyUpdated` if VC moved) —\n again **not** `user:blockchainUpdated`.\n- `getTransactionHistory`, `retryWithdrawal`, `confirmWithdrawal`,\n `donateToDeveloper`, `donateToUsersPool` only emit their own\n `blockchain:*` event — they don't touch `client.data.user.state` at all.\n\nPractical consequence: after a deposit or withdrawal request, your **balance**\nis fresh in the cache, but `client.data.user.state.Blockchain.PendingWithdrawals`\nand `.Stats` are stale until you call `getUserState()` again. Re-fetch\n`getUserState()` after a withdrawal request/confirm/retry if your UI shows the\npending-withdrawals list or stats.\n\n**`StateDelta` / `Inventory` — the response already carries what changed, if\nyou want to apply it yourself instead of re-fetching.** `DepositTokenResponse`,\n`TokenWithdrawalResponse`, `NFTWithdrawalResponse`, and\n`ConfirmWithdrawalResponse` all carry an optional `StateDelta`\n(`BlockchainStateDelta`): a signed `CryptoBalances` delta per currency\n(`{ AmountDelta, FrozenDelta, UpdatedAt }` — add, don't overwrite), a\n`PendingAdded` ref (this call's newly-added pending withdrawal, if any), and\n`PendingRemovedIDs` (pending withdrawals this call confirmed or lazily\nexpired). `DepositNFTResponse` / `NFTWithdrawalResponse` similarly carry an\n`Inventory` (`InventoryDelta`) for the NFT's `UnstackableItems` instance —\nsame shape/semantics as the character-system module's `Inventory` deltas\n(`ChangedInstances` to upsert, `RemovedInstanceIDs` to drop). This mirrors the\nself-sufficient-response pattern used elsewhere in this SDK (see the\ncharacter-system skill) so a client that wants to reconcile\n`PendingWithdrawals`/balances/instances without another round trip can do so\nstraight from the mutating call's response. **Note:** `BlockchainService`\nitself does not auto-apply `StateDelta`/`Inventory` into\n`client.data.user.state.Blockchain` today — only the crypto **balance**\n(via the existing `AmountNative`-based patch) and item `Resources` are\napplied automatically. If you need `PendingWithdrawals` reconciled without a\nfull `getUserState()` refetch, read `result.data.StateDelta` yourself. Both\nare `null`/absent on an idempotent replay (nothing new to apply).\n\n```ts\nconst off = client.on(\"blockchain:tokenWithdrawalRequested\", (r) => {\n console.log(`Withdrawal ${r.TitleTransactionID} expires at ${r.ExpiresAt}`);\n});\n// later: off();\n```\n\n## Recipes\n\n### Load config + state on a wallet/blockchain screen\n\n```ts\nawait client.blockchain.getDefinitions();\nawait client.blockchain.getUserState();\n\nconst defs = client.data.config.getSection<BlockchainDefinitions>(\"Blockchain\");\nconst bc = client.data.user.state?.Blockchain;\n\nfor (const [networkID, net] of Object.entries(defs?.Networks ?? {})) {\n if (!net.DepositsEnabled && !net.WithdrawalsEnabled) continue;\n // render a network card; net.NftCollections binds contracts to item catalogs\n}\nbc?.Kyc?.Status; // gate withdrawal UI on KYC if the title requires it\n```\n\n### Deposit a token (player already sent it on-chain)\n\n```ts\nconst res = await client.blockchain.depositToken(\"polygon\", \"0xabc123...\");\nif (!res.ok) return showError(res.error); // e.g. \"Transaction not found on chain.\",\n// \"Not enough confirmations (required 12). Try again in a few minutes.\",\n// \"Transaction hash already used.\"\n\nres.data.CurrencyID; // e.g. \"usdt\"\nres.data.AmountNative; // decimal string credited\n// Balance is already updated in the cache:\nclient.data.user.getCryptoCurrencyAmount(res.data.CurrencyID!);\n```\n\n### Full withdrawal lifecycle: request -> submit on-chain -> confirm, with a retry-after-failure path\n\n```ts\n// 1. Request the withdrawal — debits in-game immediately, returns a signature payload.\nconst req = await client.blockchain.requestTokenWithdrawal(\n \"usdt\",\n \"polygon\",\n \"0xPlayerWallet...\",\n \"25.00\",\n);\nif (!req.ok) return showError(req.error); // e.g. \"Not enough balance: have 10 usdt, need 25.00.\",\n// \"KYC verification required for withdrawals above 1000 USD.\",\n// \"Title users-withdrawable limit reached: available 5 usdt, requested 25.00.\"\n// — see \"Withdrawal gates\" above for the full list.\n\nconst { TitleTransactionID, EvmSignature, ExpiresAt } = req.data;\n// Balance is already debited (gross amount) in the cache.\n\n// 2. Hand EvmSignature (or SolanaSignature on a Solana network) to the\n// player's wallet SDK to submit the on-chain transaction yourself —\n// this SDK does not sign/broadcast. That step can fail (rejected in\n// wallet, gas issue).\n\n// 2a. If on-chain submission failed WHILE the transaction is still Pending\n// (before ExpiresAt), retry — this re-issues a fresh signature WITHOUT\n// debiting again:\nconst retry = await client.blockchain.retryWithdrawal(TitleTransactionID!);\nif (!retry.ok) return showError(retry.error); // e.g. \"Transaction is not in Pending state (current: Abandoned).\"\nconst freshSignature = retry.data.EvmSignature ?? retry.data.SolanaSignature;\n// Submit freshSignature on-chain instead, then continue to step 3.\n//\n// IMPORTANT: retryWithdrawal only works while the transaction is Pending. If\n// ExpiresAt already passed, the backend has lazily moved it to Abandoned and\n// retryWithdrawal will reject it — there is no \"re-request\" for an Abandoned\n// withdrawal (the asset was already debited and is not refunded). The only\n// way to still complete it is confirmWithdrawal with a hash, if the player\n// actually managed to submit the original signature before it was swept —\n// see the Gotchas section.\n\n// 3. Once the wallet actually broadcasts the transaction, tell the backend\n// the resulting on-chain hash so it can verify and close out the withdrawal:\nconst confirm = await client.blockchain.confirmWithdrawal(\n TitleTransactionID!,\n \"0xOnChainTxHash...\",\n);\nif (!confirm.ok) return showError(confirm.error);\nconfirm.data.Status; // e.g. \"Completed\" once the chain confirms it\n\n// 4. Refresh state — request/retry/confirm don't touch Blockchain cache themselves.\nawait client.blockchain.getUserState();\nclient.data.user.state?.Blockchain?.PendingWithdrawals; // should no longer list it once Completed\n```\n\n### KYC-gated withdrawal\n\nThe client never decides whether KYC is required — the backend compares the\nwithdrawal's USD-equivalent against the currency's configured threshold at\nrequest time. Use `Kyc.Status` only to pre-empt an obvious rejection in the\nUI; still branch on the real error:\n\n```ts\nawait client.blockchain.getUserState();\nconst kyc = client.data.user.state?.Blockchain?.Kyc;\n\nif (kyc?.Status !== \"Verified\") {\n // Optional UX nicety: warn before the call for large amounts. This SDK has\n // no startKyc/submitKyc method — verification happens through whatever KYC\n // provider integration the title uses outside this SDK; Kyc here only\n // reflects the result.\n}\n\nconst req = await client.blockchain.requestTokenWithdrawal(\n \"usdt\",\n \"polygon\",\n \"0xPlayerWallet...\",\n \"5000.00\",\n);\nif (!req.ok) {\n if (req.error.startsWith(\"KYC verification required\")) {\n // Route the player to the title's KYC verification flow.\n }\n return showError(req.error);\n}\n```\n\n### Deposit / withdraw an NFT\n\n```ts\n// Deposit: player already transferred the NFT to the vault address on-chain.\nconst dep = await client.blockchain.depositNFT(\"ethereum\", \"0xNftDepositTx...\");\nif (!dep.ok) return showError(dep.error);\ndep.data.ItemID; // the in-game item granted\ndep.data.Resources; // already applied to inventory in the cache\n\n// Withdraw: consumes the in-game item, returns a signature to submit on-chain.\nconst wd = await client.blockchain.requestNFTWithdrawal(\n \"sword-of-embers-inst-1\", // ItemID (per NFTWithdrawalResponse/BlockchainRequest shape)\n \"ethereum\",\n \"0xPlayerWallet...\",\n \"1\",\n);\nif (!wd.ok) return showError(wd.error);\nwd.data.TitleTransactionID; // use with retryWithdrawal / confirmWithdrawal exactly as tokens above\n\n// ERC-721 unique NFT: pass the specific instance to tokenize. level/itemInstanceID\n// are the trailing optional args — see the Methods table above.\nconst wd721 = await client.blockchain.requestNFTWithdrawal(\n \"sword-of-embers\",\n \"ethereum\",\n \"0xPlayerWallet...\",\n \"1\",\n undefined, // category\n 1, // level\n \"sword-of-embers-inst-1\", // ItemInstanceID — required for ERC-721 bindings\n);\n```\n\n### Edge case: not logged in / missing args\n\n```ts\nconst res = await client.blockchain.depositToken(\"\", \"0xabc\");\n// res.ok === false, res.reason === \"client\" — \"NetworkID is required.\" — no network call.\n\nconst res2 = await client.blockchain.getUserState();\n// If called before auth.loginWithDeviceID() (or any auth.* login):\n// res2.ok === false, res2.reason === \"unauthorized\"\n```\n\n### Donate crypto (no personal credit)\n\n```ts\nconst res = await client.blockchain.donateToDeveloper(\n \"polygon\",\n \"0xdonateTx...\",\n);\nif (!res.ok) return showError(res.error);\nres.data.Target; // \"Developer\" — confirms which pool bucket it landed in\n\n// donateToUsersPool is identical in shape, credits the users' pool bucket instead:\nawait client.blockchain.donateToUsersPool(\"polygon\", \"0xdonateTx2...\");\n```\n\n## Gotchas\n\n- **Withdrawal request debits immediately; the on-chain leg is separate and\n can fail.** `requestTokenWithdrawal`/`requestNFTWithdrawal` already took the\n asset from the player before any on-chain transaction exists. If the\n player's wallet fails to submit (rejected, gas issue) **while the\n transaction is still `Pending`**, don't ask them to request again — that\n would debit twice. Use `retryWithdrawal` with the same\n `TitleTransactionID` to get a fresh signature without a new charge. This\n only works before `ExpiresAt` — see the next two points for what happens\n after.\n- **`retryWithdrawal` vs `confirmWithdrawal` are opposite ends of the same\n flow.** Retry re-issues the _signed payload_ before submission (nothing has\n reached the chain yet); confirm reports the _resulting tx hash_ after\n submission (the chain now has it). Calling confirm with a hash from a\n transaction that never actually landed on-chain will simply fail\n server-side verification — don't fabricate a hash to \"force\" completion.\n- **`ExpiresAt` is real, expiry does not refund the player, and — contrary to\n what the name suggests — an expired withdrawal is NOT retryable.** A\n withdrawal signature is time-boxed (`TokenWithdrawalResponse.ExpiresAt` /\n `NFTWithdrawalResponse.ExpiresAt`, driven by\n `BlockchainAccountSafetyPolicy.PendingWithdrawalTtlHours`). Once it passes\n without a submission, the backend lazily transitions the transaction to\n **`Abandoned`** (not `Expired` — that enum value exists but this backend\n path never assigns it) and drops it off `PendingWithdrawals` — but the\n already-debited asset is **not** credited back; this is intentional, not a\n bug. Critically, `retryWithdrawal` requires the transaction to still be\n `Pending` — calling it on an `Abandoned` one fails with `\"Transaction is\nnot in Pending state (current: Abandoned).\"` There is no \"re-request\"\n operation for an abandoned withdrawal.\n- **A withdrawal can still be confirmed after it's `Abandoned`.** If the\n player submits late — after `ExpiresAt` passed and the backend already\n swept it to `Abandoned` — `confirmWithdrawal` still accepts it as long as\n the on-chain transaction verifies (the signature itself doesn't expire\n on-chain, only the title's own bookkeeping window does). Don't treat an\n `Abandoned` transaction as unrecoverable if the player insists they\n submitted it; calling `confirmWithdrawal` with the resulting hash is still\n the right move, and is in fact the _only_ way to close out an\n already-expired-but-actually-submitted withdrawal.\n- **`retryWithdrawal` only works on a `Pending` transaction the caller owns.**\n It fails with `\"Transaction not found.\"` for an unknown or someone else's\n `TitleTransactionID`, `\"Transaction is not in Pending state (current:\n{status}).\"` if it already completed/failed/was abandoned, or\n `\"Signature data not found for this transaction.\"` if there's nothing to\n reissue. A banned account additionally gets `\"Account is banned. Contact\nsupport.\"` on retry (deposits stay allowed for banned accounts; retrying a\n withdrawal does not).\n- **Gross vs. net amounts on token withdrawals.** `AmountNative` is what was\n debited from the player (gross); `NetAmountNative` is what actually gets\n paid out on-chain after a platform commission percentage **and** an\n optional on-chain burn are deducted (`NetAmountNative = AmountNative −\ncommission − BurnAmountNative`). Show the player the net figure they'll\n receive, not the gross debit, to avoid support tickets about a \"missing\"\n amount. NFT withdrawals have no such split — there's no `NetAmountNative`\n on `NFTWithdrawalResponse`.\n- **Burn on withdrawal (EVM-only).** `TokenWithdrawalResponse.BurnAmountNative`\n is the amount burned on-chain (sent to the DEAD address) for this\n withdrawal, driven by the currency's `WithdrawalBurnPercent` (see the\n currency-system skill) — `0` if burn is disabled for that currency or the\n network is Solana. The raw-units counterpart, `WithdrawalSignatureResponse.\nBurnAmount`, is bound into the signed hash and must be passed to the\n contract call verbatim, same as `Amount`/`Nonce` — `@idosgames/wallet`'s\n `submitEvmTokenWithdrawal` does this for you; a client calling\n `withdrawERC20` directly must include it too, or the signature check fails.\n- **`client.data.user.state.Blockchain` goes stale after deposits/withdrawal\n requests.** Only `getUserState()` refreshes `LinkedWallets`,\n `PendingWithdrawals`, `Kyc`, and `Stats`. A deposit/withdrawal call updates\n your _balance_/_inventory_ cache correctly, but if your UI also shows the\n pending-withdrawals list or lifetime stats, re-call `getUserState()`\n afterward (see the withdrawal recipe above).\n- **Deposits are reporting, not sending.** `depositToken`/`depositNFT` don't\n move any asset on-chain — they tell the backend \"verify this transaction\n hash and credit me.\" The actual on-chain transfer to the platform's pool/\n vault address must already have happened via a wallet SDK before you call\n these.\n- **This SDK never signs or broadcasts.** `EvmSignature`/`SolanaSignature`\n payloads are inputs to a wallet SDK/contract call that happens outside\n `@idosgames/core`. Don't look for a \"submit on-chain\" method here — there\n isn't one; `confirmWithdrawal` only reports the result afterward. The\n `@idosgames/wallet` companion package is that outside layer — it submits the\n signature on-chain and calls `confirmWithdrawal` for you.\n- **Donations never touch personal balances.** `donateToDeveloper` /\n `donateToUsersPool` intentionally don't credit the player anything and\n don't touch `client.data.user.state` — they only emit their own\n `blockchain:donated*` event for a confirmation toast/receipt.\n- **Render from the cache, handle the error from the result.** The happy\n path updates the relevant cache slice + emits an event; the failure path\n gives you `reason` + `error`. Use `reason` to decide behavior (retry on\n `\"connection\"`, re-auth on `\"unauthorized\"`, toast the `error` on\n `\"server\"`).\n\n## Full reference\n\n[references/data-model.md](references/data-model.md) — every config and\nstate field: network definitions, NFT collection bindings, account-safety\npolicy, KYC state, transaction documents, the withdrawal-gate limits, and the\nEVM/Solana withdrawal signature payload shapes. Read it when building network\npickers, a transaction-history table, or KYC/limit-aware withdrawal UI. For\nthe shared `ResourceConsume`/`ResourceGrant`/`ResourceOperation`\ncost-and-reward shapes riding along on `depositNFT`/`requestNFTWithdrawal`,\nand for the full `CryptoCurrencyDefinition` shape (`Limits`, `Networks[].\nMinWithdraw`, `Permissions`) that the withdrawal gates enforce,\nsee the currency-system skill.\n",
5
5
  "references": [
6
6
  {
7
7
  "path": "data-model.md",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "idosgames-compose-modules",
3
- "description": "Put an iDosGames app together from the base and modules — the systems (shop, heroes, leaderboards, rewards…) as lobby tabs, one or several games behind \"Play\", progress shared across them. Use this whenever a developer wants to COMBINE or MERGE modules into a single title, add or remove a system, add a second game, switch between the lobby and game modes, share currency/inventory across modules, or asks how the lobby, \"Play\", ctx.modes, activeOnly panels, the shared-UI roles (sharedUi, shouldDraw, the \"modes\" role), typed cross-module events (defineTopic/shape) or host-level shared state work. Builds on idosgames-getting-started (scaffolding) and idosgames-module-contract (a single module).",
4
- "content": "---\nname: idosgames-compose-modules\ndescription: >-\n Put an iDosGames app together from the base and modules — the systems (shop, heroes, leaderboards,\n rewards…) as lobby tabs, one or several games behind \"Play\", progress shared across them. Use this\n whenever a developer wants to COMBINE or MERGE modules into a single title, add or remove a system,\n add a second game, switch between the lobby and game modes, share currency/inventory across modules,\n or asks how the lobby, \"Play\", ctx.modes, activeOnly panels, the shared-UI roles (sharedUi,\n shouldDraw, the \"modes\" role), typed cross-module events (defineTopic/shape) or host-level shared\n state work. Builds on idosgames-getting-started (scaffolding) and idosgames-module-contract (a single\n module).\n---\n\n# Putting an app together: the base + modules\n\nEvery project is **the base + modules**. The base (`src/base/`, from the host scaffold) is sign-in and\nthe lobby; everything else is a module in `src/modules/<id>/`:\n\n- **systems** (`type: feature`, `inBase: true` in the catalog) — the shop, heroes, inventory,\n leaderboards, rewards, craft, marketplace, deals, events, season, friends, chat, invite, arena,\n profile, tutorials, workshop. Each registers its screen as a **feature** → a tab of the lobby. The\n platform installs all of them with the base into every new project; remove the ones the app does not\n need.\n- **games** (`type: template`) — board-game, idle-rpg, voxelcraft, mini-game, or the game's own. Each\n registers a **route** → a \"Play\" button in the lobby.\n\n## Register modules\n\n```ts\n// src/modules.ts — the platform regenerates it; by hand it is imports + the array\nexport const modules: Module[] = [\n storeModule, // systems: lobby tabs\n characterModule,\n leaderboardModule,\n boardGameModule, // games: \"Play\"\n idleRpgModule,\n];\n```\n\n`src/main.tsx` mounts `[baseModule, ...modules]`. After sign-in the player lands in the lobby\n(`src/app.config.ts` `start` can send them straight into a game). \"Play\" switches the host to the\ngame's mode: only the active mode's scene is mounted and ticking; the rest are suspended (their RAF\nstops). This is why two different engines (Three + Phaser) live in one project — they never render\nat the same time. Over a game the base draws only a small \"To the lobby\" button.\n\n- A system tab is hidden while the title has nothing for it (no store offers, no heroes…): the module\n registers with `available: false` and calls `ctx.features.setAvailable(id, ok, reason)`.\n- `ctx.modes.list()` / `current()` / `subscribe()` — every mode (id, label, icon, module, module type);\n the lobby builds \"Play\" from the `game` ones. Switch with `ctx.navigate(id)` (`\"lobby\"` is the base).\n- Open another system's screen by id: `ctx.features.open(\"store\")` — from a game too (the host shows\n it in a window while the lobby is off screen). Never import another module.\n\n## Share progress across modes (the merge)\n\nShared state lives in the ONE SDK client, not in any module. Every module reads/writes the same\n`client` (currency, inventory, characters), so progress carries across modes automatically:\n\n- Gold earned idle in the RPG mode is spendable in the Board mode and in the shop — same\n `client.currency`, same cache. No cross-module plumbing needed for durable state.\n- For live cross-module signals (not durable state), use `ctx.events` with a **typed topic** — see\n \"Signals between modules\" below.\n- Modules never import each other's files or `src/base/`. The client and the event bus are the seams\n between them — which is what keeps a module reusable in another game. Code several of THIS game's\n modules need (shared types, the game's UI kit, helpers) goes to `src/shared/`, which never imports a\n module (see idosgames-project-structure).\n\n## Shared chrome: roles, and the base takes them\n\nBalances, the crypto wallet, the status line, \"Log out\" / player ID, the menu of features and the\nswitch between modes are **shared-UI roles** (`currency-bar | wallet | status | account | menu |\nmodes`). A module that draws one for EVERY mode declares it statically on the module object —\nthe base does:\n\n```ts\ndefineModule({\n id: \"base\",\n meta: { name: \"Base\", type: \"app\", engine: \"dom\" },\n sharedUi: {\n provides: [\"currency-bar\", \"wallet\", \"account\", \"menu\", \"modes\"],\n },\n setup(ctx) {\n /* the lobby: balances, wallet, profile, tabs, \"Play\" */\n },\n});\n```\n\nThe host resolves role owners from these declarations BEFORE any `setup()` — the first provider wins,\na conflict is warned — and every module asks `ctx.sharedUi.shouldDraw(role)`. A game draws its own\ncopy only while nobody took the role. So:\n\n- Next to the base a game hides its own balances and wallet by itself. Do NOT edit a catalog game to\n remove them: it does that itself, and an edit marks it customized (no more catalog updates).\n- `status` — the line of a game's own actions (\"Rolling…\") — stays with each game.\n- A game installed without a base stays complete — nobody owns a role, it draws everything, and the\n host draws its own nav of routes, ☰ and \"Log out\" (those are the host-drawn roles `modes`, `menu`,\n `account`).\n- A new module that needs, say, the balance bar but does not draw it declares\n `sharedUi: { requires: [\"currency-bar\"] }`; with no provider installed the host warns.\n\n**Layout is the host's job.** A game's overlay fills the screen under the base's small button; a\nscene's own DOM HUD can keep clear of host chrome with the CSS variables on the host root —\n`top: calc(var(--idos-safe-top, 0px) + 8px)`, `bottom: calc(var(--idos-safe-bottom, 0px) + 8px)`\n(voxelcraft's hotbar does this). Both are 0 when nothing is pinned. `hud`-slot panels are wrapped in\n`display: contents`, so a panel can stretch (`flex: 1`) and decide its own pointer-events: let clicks\nthrough to the game, take them only on controls.\n\n## Signals between modules (typed topics)\n\nA topic is a token passed by value: the name carries the major version, the payload is a flat JSON\nshape — one artifact that gives the TS type, the runtime check and the catalog entry.\n\n```ts\n// idle-rpg/events.ts — the EMITTER owns the topic\nimport { defineTopic, shape } from \"@idosgames/module-sdk\";\nexport const characterUpgraded = defineTopic(\n \"idle-rpg:character-upgraded@1\",\n shape({ characterId: \"string\", level: \"number\" }),\n);\n// setup(): hand the panel a callback that does\n// ctx.events.emit(characterUpgraded, { characterId, level });\n```\n\n```ts\n// board-game/events.ts — the LISTENER keeps its OWN copy (copied from the catalog), never an import.\n// Optional: idle-rpg may not be installed. Only the fields this module reads.\nexport const idleCharacterUpgraded = defineTopic(\n \"idle-rpg:character-upgraded@1\",\n shape({ level: \"number\" }),\n);\n// setup() — NOT a panel effect (activeOnly panels unmount with their mode and miss events):\nctx.events.on(idleCharacterUpgraded, ({ level }) =>\n news.push(`Idle RPG hero reached Lv ${level}`),\n);\n```\n\nDeclare both sides in `module.meta.json` — the catalog and the agent read this, not your code:\n\n```json\n\"events\": {\n \"emits\": [{ \"topic\": \"idle-rpg:character-upgraded@1\", \"when\": \"a hero levelled up\",\n \"payload\": { \"characterId\": \"string\", \"level\": \"number\" } }],\n \"listens\": [{ \"topic\": \"idle-rpg:character-upgraded@1\", \"why\": \"news chip in the board HUD\" }]\n}\n```\n\nRules:\n\n- Name `<your-module-id>:<event>@<major>`. Emit only into your own namespace — the host drops an\n emit into another module's namespace with `console.error`; `host:` is reserved. The only topics\n you import are `hostTopics` from `@idosgames/module-sdk` (`hostTopics.modeChanged` =\n `host:mode-changed@1 { from?: string; to: string }`, sent on every mode switch).\n- Shape leaves: `\"string\" | \"number\" | \"boolean\"`, with `\"[]\"` and/or a trailing `\"?\"`; nested\n objects allowed. Payloads are plain JSON — no functions, class instances or engine objects.\n- An incompatible change is a NEW topic `@2` (send both during the transition); within a major, only\n add fields. A listener whose fields are missing is skipped (one `console.warn`), never crashed.\n- An event is a signal, not state, and is never replayed — \"what exists now\" is SDK data or\n `ctx.sharedUi`. No request/response between modules: if you need an answer, it is data.\n- A throwing handler does not stop other listeners or reach the emitter; the host removes every\n subscription on logout, so re-login does not double handlers.\n- In the AI editor's preview, `gameState` returns the last 50 events, who listens to what, and hints\n like \"board-game listens to x@1 but only x@2 is emitted\".\n- A game's OWN modules may keep shared topic tokens in `src/shared/events/` and import them on both\n sides — still declare them in each `module.meta.json`.\n\n## Reference app\n\nThe base + the systems + `board-game` + `idle-rpg`:\n\n- sign-in → the lobby: balances, wallet and profile on top, the systems as tabs, \"Play\" with two games;\n- \"Play\" → one engine scene mounted at a time; the base's button returns to the lobby;\n- the games hide their own balances and wallet (the lobby has them); their status lines stay theirs;\n- currency changed in one mode is immediately visible in the others and in the lobby; levelling a hero\n in Idle RPG shows a news chip on the board (`idle-rpg:character-upgraded@1`).\n\nTo pull the modules, use `get_module {id}` for each (MCP) and register them as above. Adjust layouts\nper module (a full-bleed overlay UI vs a docked side panel) — see each module's RootPanel.\n",
3
+ "description": "Put an iDosGames app together from the base and modules — the systems (shop, heroes, leaderboards, quests, chests, multiplayer…) as lobby tabs, one or several games behind \"Play\", progress shared across them. Use this whenever a developer wants to COMBINE or MERGE modules into a single title, add or remove a system, add a second game, switch between the lobby and game modes, share currency/inventory across modules, or asks how the lobby, \"Play\", ctx.modes, activeOnly panels, the shared-UI roles (sharedUi, shouldDraw, the \"modes\" role), typed cross-module events (defineTopic/shape) or host-level shared state work. Builds on idosgames-getting-started (scaffolding) and idosgames-module-contract (a single module).",
4
+ "content": "---\nname: idosgames-compose-modules\ndescription: >-\n Put an iDosGames app together from the base and modules — the systems (shop, heroes, leaderboards,\n quests, chests, multiplayer…) as lobby tabs, one or several games behind \"Play\", progress shared across them. Use this\n whenever a developer wants to COMBINE or MERGE modules into a single title, add or remove a system,\n add a second game, switch between the lobby and game modes, share currency/inventory across modules,\n or asks how the lobby, \"Play\", ctx.modes, activeOnly panels, the shared-UI roles (sharedUi,\n shouldDraw, the \"modes\" role), typed cross-module events (defineTopic/shape) or host-level shared\n state work. Builds on idosgames-getting-started (scaffolding) and idosgames-module-contract (a single\n module).\n---\n\n# Putting an app together: the base + modules\n\nEvery project is **the base + modules**. The base (`src/base/`, from the host scaffold) is sign-in and\nthe lobby; everything else is a module in `src/modules/<id>/`:\n\n- **systems** (`type: feature`) — one per player-facing module of the engine: store, premium (VIP),\n character, inventory, lootboxes, boosts, leaderboard, rewards (daily), quests, collections, craft,\n marketplace, deals, events, coop-events, season, friends, chat, invite, pvp, multiplayer, profile,\n tutorials, workshop, ai, mailbox. Each registers its screen as a **feature** → a tab of the lobby.\n The base installs only six of them into every new project (`inBase: true`: profile, inventory,\n invite, friends, quests, mailbox); every other system is installed only when the app needs it — a game\n brings the ones it lists in `uses`, and you install any other one as soon as the task needs what\n it `provides` (InstallModule / `get_module`) — the user does not have to name the module; reuse it\n instead of writing that feature again. Never install one the task does not need.\n- **games** (`type: template`) — board-game, idle-rpg, voxelcraft, mini-game, or the game's own. Each\n registers a **route** → a \"Play\" button in the lobby. A game that plugs into a system lists it in\n `uses` in its module.meta.json (`ctx.multiplayer` → `\"multiplayer\"`, `ctx.content` → `\"workshop\"`;\n `npm run check` enforces those two) — install those together with the game.\n\n## Register modules\n\n```ts\n// src/modules.ts — the platform regenerates it; by hand it is imports + the array\nexport const modules: Module[] = [\n storeModule, // systems: lobby tabs\n characterModule,\n leaderboardModule,\n boardGameModule, // games: \"Play\"\n idleRpgModule,\n];\n```\n\n`src/main.tsx` mounts `[baseModule, ...modules]`. After sign-in the player lands in the lobby\n(`src/app.config.ts` `start` can send them straight into a game). \"Play\" switches the host to the\ngame's mode: only the active mode's scene is mounted and ticking; the rest are suspended (their RAF\nstops). This is why two different engines (Three + Phaser) live in one project — they never render\nat the same time. Over a game the base draws only a small \"To the lobby\" button.\n\n- A system tab is hidden while the title has nothing for it (no store offers, no heroes…): the module\n registers with `available: false` and calls `ctx.features.setAvailable(id, ok, reason)`.\n- `ctx.modes.list()` / `current()` / `subscribe()` — every mode (id, label, icon, module, module type);\n the lobby builds \"Play\" from the `game` ones. Switch with `ctx.navigate(id)` (`\"lobby\"` is the base).\n- Open another system's screen by id: `ctx.features.open(\"store\")` — from a game too (the host shows\n it in a window while the lobby is off screen). Never import another module.\n\n## Share progress across modes (the merge)\n\nShared state lives in the ONE SDK client, not in any module. Every module reads/writes the same\n`client` (currency, inventory, characters), so progress carries across modes automatically:\n\n- Gold earned idle in the RPG mode is spendable in the Board mode and in the shop — same\n `client.currency`, same cache. No cross-module plumbing needed for durable state.\n- For live cross-module signals (not durable state), use `ctx.events` with a **typed topic** — see\n \"Signals between modules\" below.\n- Modules never import each other's files or `src/base/`. The client and the event bus are the seams\n between them — which is what keeps a module reusable in another game. Code several of THIS game's\n modules need (shared types, the game's UI kit, helpers) goes to `src/shared/`, which never imports a\n module (see idosgames-project-structure).\n\n## Shared chrome: roles, and the base takes them\n\nBalances, the crypto wallet, the status line, \"Log out\" / player ID, the menu of features and the\nswitch between modes are **shared-UI roles** (`currency-bar | wallet | status | account | menu |\nmodes`). A module that draws one for EVERY mode declares it statically on the module object —\nthe base does:\n\n```ts\ndefineModule({\n id: \"base\",\n meta: { name: \"Base\", type: \"app\", engine: \"dom\" },\n sharedUi: {\n provides: [\"currency-bar\", \"wallet\", \"account\", \"menu\", \"modes\"],\n },\n setup(ctx) {\n /* the lobby: balances, wallet, profile, tabs, \"Play\" */\n },\n});\n```\n\nThe host resolves role owners from these declarations BEFORE any `setup()` — the first provider wins,\na conflict is warned — and every module asks `ctx.sharedUi.shouldDraw(role)`. A game draws its own\ncopy only while nobody took the role. So:\n\n- Next to the base a game hides its own balances and wallet by itself. Do NOT edit a catalog game to\n remove them: it does that itself, and an edit marks it customized (no more catalog updates).\n- `status` — the line of a game's own actions (\"Rolling…\") — stays with each game.\n- A game installed without a base stays complete — nobody owns a role, it draws everything, and the\n host draws its own nav of routes, ☰ and \"Log out\" (those are the host-drawn roles `modes`, `menu`,\n `account`).\n- A new module that needs, say, the balance bar but does not draw it declares\n `sharedUi: { requires: [\"currency-bar\"] }`; with no provider installed the host warns.\n\n**Layout is the host's job.** A game's overlay fills the screen under the base's small button; a\nscene's own DOM HUD can keep clear of host chrome with the CSS variables on the host root —\n`top: calc(var(--idos-safe-top, 0px) + 8px)`, `bottom: calc(var(--idos-safe-bottom, 0px) + 8px)`\n(voxelcraft's hotbar does this). Both are 0 when nothing is pinned. `hud`-slot panels are wrapped in\n`display: contents`, so a panel can stretch (`flex: 1`) and decide its own pointer-events: let clicks\nthrough to the game, take them only on controls.\n\n## Signals between modules (typed topics)\n\nA topic is a token passed by value: the name carries the major version, the payload is a flat JSON\nshape — one artifact that gives the TS type, the runtime check and the catalog entry.\n\n```ts\n// idle-rpg/events.ts — the EMITTER owns the topic\nimport { defineTopic, shape } from \"@idosgames/module-sdk\";\nexport const characterUpgraded = defineTopic(\n \"idle-rpg:character-upgraded@1\",\n shape({ characterId: \"string\", level: \"number\" }),\n);\n// setup(): hand the panel a callback that does\n// ctx.events.emit(characterUpgraded, { characterId, level });\n```\n\n```ts\n// board-game/events.ts — the LISTENER keeps its OWN copy (copied from the catalog), never an import.\n// Optional: idle-rpg may not be installed. Only the fields this module reads.\nexport const idleCharacterUpgraded = defineTopic(\n \"idle-rpg:character-upgraded@1\",\n shape({ level: \"number\" }),\n);\n// setup() — NOT a panel effect (activeOnly panels unmount with their mode and miss events):\nctx.events.on(idleCharacterUpgraded, ({ level }) =>\n news.push(`Idle RPG hero reached Lv ${level}`),\n);\n```\n\nDeclare both sides in `module.meta.json` — the catalog and the agent read this, not your code:\n\n```json\n\"events\": {\n \"emits\": [{ \"topic\": \"idle-rpg:character-upgraded@1\", \"when\": \"a hero levelled up\",\n \"payload\": { \"characterId\": \"string\", \"level\": \"number\" } }],\n \"listens\": [{ \"topic\": \"idle-rpg:character-upgraded@1\", \"why\": \"news chip in the board HUD\" }]\n}\n```\n\nRules:\n\n- Name `<your-module-id>:<event>@<major>`. Emit only into your own namespace — the host drops an\n emit into another module's namespace with `console.error`; `host:` is reserved. The only topics\n you import are `hostTopics` from `@idosgames/module-sdk` (`hostTopics.modeChanged` =\n `host:mode-changed@1 { from?: string; to: string }`, sent on every mode switch).\n- Shape leaves: `\"string\" | \"number\" | \"boolean\"`, with `\"[]\"` and/or a trailing `\"?\"`; nested\n objects allowed. Payloads are plain JSON — no functions, class instances or engine objects.\n- An incompatible change is a NEW topic `@2` (send both during the transition); within a major, only\n add fields. A listener whose fields are missing is skipped (one `console.warn`), never crashed.\n- An event is a signal, not state, and is never replayed — \"what exists now\" is SDK data or\n `ctx.sharedUi`. No request/response between modules: if you need an answer, it is data.\n- A throwing handler does not stop other listeners or reach the emitter; the host removes every\n subscription on logout, so re-login does not double handlers.\n- In the AI editor's preview, `gameState` returns the last 50 events, who listens to what, and hints\n like \"board-game listens to x@1 but only x@2 is emitted\".\n- A game's OWN modules may keep shared topic tokens in `src/shared/events/` and import them on both\n sides — still declare them in each `module.meta.json`.\n\n## Reference app\n\nThe base + the systems + `board-game` + `idle-rpg`:\n\n- sign-in → the lobby: balances, wallet and profile on top, the systems as tabs, \"Play\" with two games;\n- \"Play\" → one engine scene mounted at a time; the base's button returns to the lobby;\n- the games hide their own balances and wallet (the lobby has them); their status lines stay theirs;\n- currency changed in one mode is immediately visible in the others and in the lobby; levelling a hero\n in Idle RPG shows a news chip on the board (`idle-rpg:character-upgraded@1`).\n\nTo pull the modules, use `get_module {id}` for each (MCP) and register them as above. Adjust layouts\nper module (a full-bleed overlay UI vs a docked side panel) — see each module's RootPanel.\n",
5
5
  "references": []
6
6
  }