From eea2deb1fb45b585eb0b7688d1fcf580fef7ac66 Mon Sep 17 00:00:00 2001 From: Eric Meehan Date: Wed, 28 Oct 2026 17:09:58 -0400 Subject: [PATCH] Removed markets --- README.md | 59 ++++++++++------------ compose.custody-pilot.yaml | 1 + compose.custody.yaml | 1 + compose.mainnet.yaml | 1 + compose.testnet.yaml | 11 ++-- compose.yaml | 1 + docs/market-host-configuration.md | 9 ++-- server/testnet/http.ts | 84 ++++++++++++++++++------------- src/App.tsx | 30 ++++++----- tests/api.test.ts | 7 ++- tests/project-copy.test.ts | 23 ++++----- 11 files changed, 122 insertions(+), 105 deletions(-) diff --git a/README.md b/README.md index 93c572b..f5fb87a 100644 --- a/README.md +++ b/README.md @@ -1,42 +1,44 @@ # Wikideck -**Production roadmap:** see the [production delivery plan](docs/production-plan.md) for XMR-native pricing, custodial-market implementation, fixed-price-first launch scope and release gates. New v3 listings use exact native-XMR prices; historical v2 USD records keep their original terms. All payments remain simulated. The [custodial design and implementation status](docs/custodial-market-design.md) distinguish the sandbox ledger from future live custody. - -Wikideck is an NFT blockchain where mining a block rewards the miner with a collectible card based on a Wikipedia page. Build collections, trade cards with other collectors, or host a peer with its own marketplace. Trading card games (TCGs), including custom games hosted by peers, are planned for a later release. +Wikideck is an experimental blockchain game about **mining, collecting, and trading illustrated Wikipedia cards**. Mine a block with the native RandomX CPU miner to earn a card, build a collection in a local wallet, and trade cards directly with another player. The default app has no marketplace, prices, or checkout. Mining uses **RandomX, the proof-of-work algorithm also used by Monero**, designed to keep general-purpose consumer CPUs competitive. Wikideck is an independent blockchain, not part of Monero or its mining/security network. Hardware, total network hashpower and difficulty determine results; no particular mining reward rate or profitability is guaranteed. **This is a local test network, not a public mainnet or an investment product.** No public bootnodes or hosted network are provided. Test NFTs have no promised value. Do not use funds or valuable assets. This project is not affiliated with Wikipedia or the Wikimedia Foundation. -## Collect, trade, and build your own community +## Mine, collect, and trade cards - **Mine Wikipedia cards.** Each accepted block mints a native NFT for the miner from a random illustrated English Wikipedia article. The card records the article snapshot and mint-time statistics. The same page can appear on more than one distinct card. The reward is a card representing a page—not ownership of the page, its copyright, or a payment to Wikipedia. -- **Build collections.** Assemble a broad cabinet of discoveries or focus on a subject, series or theme. Browse public decks and exchange up to eight cards on each side in one atomic trade. -- **Buy and sell in peer-hosted markets.** Running a peer lets you host a market for the shared chain's cards. Your community can be general-purpose or focus on a particular collection. Listings, auctions and orders belong to that market host; card ownership and mined transfers are shared through the blockchain. -- **Support the host and project author.** Sales allocate a configurable hosting fee to the peer's market operator (2.5% by default) and a separate hardcoded **1% author fee** to the project's fixed XMR address. Both are deducted from seller proceeds; the default total is 3.5%. In the intended cryptocurrency settlement model the host retains its fee, while the author allocation is paid separately. Today all payment, fee and payout accounting is simulated. -- **Cryptocurrency checkout.** New market prices are quoted directly in **Monero (XMR)** atomic units. The current testnet checkout is mock-only: no real cryptocurrency is accepted or sent. -- **Play TCGs — planned.** The roadmap is to use these same cards in trading card games and let peers host custom TCG experiences. There is no playable game engine, match system, deck legality or custom rules hosting yet. Current card stats are not a promise of future game balance. +- **Build collections.** Browse chain discoveries or focus on a subject, series, or theme. Cards are controlled by your encrypted local wallet. +- **Trade directly.** Look up another public wallet and exchange up to eight cards on each side in one signed, atomic trade. Offers are shared between the two players; the app does not list cards for sale or process payments. +- **Gameplay is not included yet.** The current release supports mining, collecting, transfers, and direct trades. Playable card games are future work. -## Peer ownership and customization +## Optional legacy market modules -**Understand the market before trading:** [Payment flow and buyer/seller protections](docs/market-transparency.md) explains who controls cards and funds, both fees, deadlines, refund/reorg limits, privacy and host accountability. Current payments are mock-only; seller delivery still transfers the actual card. No guaranteed refund, insurance or built-in arbitration is provided. +Market and custody code remains in the repository for separate experiments, but it is **not part of the default card-trading experience**. The server does not open a market journal, expose market APIs, or run its reconciliation worker unless `WIKIDECK_MARKET_RUNTIME_ENABLED=1` is explicitly set. Enabling it is an operator decision; market orders are local to the node, checkout is simulated, and no real XMR is accepted or sent. See the [market implementation notes](docs/marketplace.md) and [security boundaries](docs/market-transparency.md) before enabling it. Existing market data is not deleted when the feature is off, but disabling an existing market pauses order resolution; review outstanding orders before switching modes. -The project's open-source direction is to give peer operators substantial freedom to adapt their own market: presentation, community focus, curation and future game rules. A collection-focused community can run the current general listing interface today; built-in collection filters, moderation/admission tooling and custom TCG hosting are future work, not existing operator controls. Operators can already configure their hosting fee and run their own local marketplace journal. - -Market customization does not let one peer rewrite shared NFT ownership or unilaterally change consensus for other peers. Compatible peers must follow the same network rules. The author fee is hardcoded in the distributed implementation; it is not a hosting configuration option. Any source modifications and redistribution must respect the eventual project license and third-party licenses. - -**Licensing status:** this checkout does not yet contain a project LICENSE file. Source availability alone does not grant open-source modification/redistribution rights. Publishing an appropriate license is still required before describing those freedoms as legally granted. Wikipedia text/images and dependencies retain their separate licenses; a Wikideck software license would not replace them. +**Licensing status:** this checkout does not yet contain a project LICENSE file. Source availability alone does not grant open-source modification/redistribution rights. Wikipedia text/images and dependencies retain their separate licenses. ## What's available now -| Available in the testnet | Planned / not enabled | +| Available in the testnet | Not included in the default experience | | --- | --- | -| RandomX mining and illustrated Wikipedia NFT rewards | Reviewed production network launch | -| Encrypted local wallets, collections and atomic card trades | Playable TCGs and peer-hosted custom games | -| Per-peer fixed-price listings and timed auctions | Built-in collection-specific curation/admission controls | - | Mock native-XMR checkout and host/author fee accounting | Real cryptocurrency settlement and production custody operations | +| RandomX mining and illustrated Wikipedia card rewards | Marketplace listings, auctions, and checkout | +| Encrypted local wallets, collections, transfers, and atomic card trades | Real cryptocurrency payments or custody | +| Local single-node or optional three-node testnet | Playable card games and production network launch | -## Run the three-node testnet (Docker) +## Quick start: one local node (Docker) + +Install Docker Desktop with Linux containers and Docker Compose v2. From the repository root: + +```sh +docker compose up --build -d +docker compose ps +``` + +Open **http://127.0.0.1:3001**. The first run builds the node and native RandomX engine. The node does not mine automatically. Open the wallet panel to create a local wallet and encrypted backup, then follow [Mine Wikipedia cards with RandomX](#mine-wikipedia-cards-with-randomx) to run the miner. The default stack leaves marketplace startup and APIs disabled. Stop the node with `docker compose down`; the ledger volume remains. **Do not add `-v` unless you intend to delete that data.** + +## Optional: three-node testnet (Docker) Install Docker Desktop with Linux containers and Docker Compose v2. From the repository root, start three connected nodes: @@ -46,7 +48,7 @@ docker compose -f compose.testnet.yaml ps docker compose -f compose.testnet.yaml logs -f node-a ``` -Open **http://127.0.0.1:3101**. The other nodes are at **http://127.0.0.1:3102** and **http://127.0.0.1:3103**. Each node validates blocks independently and stores its ledger in a separate Docker volume. Mining does not start automatically. A healthy node is not necessarily connected to its peers; check the peer status in the interface or request `/api/peers`. Nodes need outbound access to Wikipedia when generating mining templates and capturing mint-time statistics. If that data is unavailable, the node returns an error and mining can be retried. +Open **http://127.0.0.1:3101**. The other nodes are at **http://127.0.0.1:3102** and **http://127.0.0.1:3103**. Each node validates blocks independently and stores its ledger in a separate Docker volume. Marketplace runtime is disabled by default; mining does not start automatically. A healthy node is not necessarily connected to its peers; check the peer status in the interface or request `/api/peers`. Nodes need outbound access to Wikipedia when generating mining templates and capturing mint-time statistics. If that data is unavailable, the node returns an error and mining can be retried. Stop the nodes with: @@ -60,15 +62,7 @@ For an existing host install, keep the old data directory intact and set `WIKIDE ## Run on your host -### Optional custody accounting preview - -**Optional market hosting:** set `WIKIDECK_MARKET_ENABLED=0` to suppress public listings/new trading, or `WIKIDECK_MARKET_TRADING_ENABLED=0` for a browsable paused market. Configure hosting-fee payouts with `WIKIDECK_MARKET_HOST_FEE_ADDRESS` (defaults to the author wallet); the fixed 1% author fee remains separate. Existing orders/balance resolution stay accessible. See [host configuration](docs/market-host-configuration.md) for strict values, signed recipient snapshots and safe container recreation. - -For a **persistent PostgreSQL-backed local stack**, use [the deployment guide](docs/persistent-custody-sandbox.md) and [compose.custody.yaml](compose.custody.yaml), or the VS Code **Start persistent custody sandbox** task. It starts PostgreSQL plus Wikideck at port 3422, with generated scoped credentials, verified database TLS and explicit migrations. Existing single/three-node commands are unchanged. This uses separate volumes and does not migrate existing SQLite custody or enable real payments. - -The marketplace's **Custody preview** tab is separate from existing mock checkout. Explicit `WIKIDECK_CUSTODY_MODE=sandbox` on the server enables fictitious test balances, signed fixed-price reservations and withdrawal holds on testnet only. Default is `off`; live modes and mainnet sandbox fail closed. Use a disposable data directory and configure `PUBLIC_ORIGIN` to the exact browser origin. No Monero addresses, wallet RPC or real withdrawals are available. [PostgreSQL financial storage](docs/postgres-financial-storage.md) is selectable with `WIKIDECK_CUSTODY_STORAGE=postgres`, explicit schema/role setup and a secret-file connection configuration; existing SQLite custody requires a stopped-node import, never automatic fallback. - -Reservations stop at `awaiting-lock` because reviewed NFT sale-lock consensus rules are not implemented. They can be cancelled while their outbox intent is blocked; they do not deliver cards. Local SQLite custody is included by stopped-node backup/restore when present; PostgreSQL-bound nodes require coordinated database/node backups and the SQLite-only backup command refuses them. Real treasury observation/settlement, signing controls and production review remain future work. See [the implementation record](docs/custodial-market-design.md). +The legacy market can be explicitly enabled with `WIKIDECK_MARKET_RUNTIME_ENABLED=1`; do not enable it for a node that has unresolved orders without reviewing its local journal first. When disabled, the market journal is left untouched, but the node does not reconcile it or expose market APIs. The separate custody and Monero experiments require dedicated configurations and are not needed to mine or trade cards. Their deployment instructions remain in the `docs/` directory, but are outside the supported quick-start path. Requirements: Node.js 24, npm, Git, CMake 3.24+, and a C/C++17 toolchain. The first native-engine configuration downloads the pinned RandomX source over HTTPS. On Windows, install a compatible toolchain (for example, MinGW-w64 and make) and use the matching CMake generator. Do not change generators in an existing `native/build` directory; use a fresh build directory when switching toolchains. @@ -115,7 +109,6 @@ Light mode needs a 256 MiB cache plus scratchpad and process overhead. `--fast` - **My collection** shows NFTs owned by the active local wallet on the connected node's canonical chain. - **Block explorer** distinguishes block IDs, NFT token IDs, and RandomX proof hashes. A submitted transfer is pending until a block confirms it. Reorganizations can change canonical ownership and confirmations. - **Trade decks** lets you look up another public wallet by receive address, select up to eight cards on each side, prepare a signed offer, and accept another player's offer. Offers are shared as JSON for the other player to review; they are not submitted until accepted. The two parties sign the same card list, and validators apply the whole bundle atomically or reject it entirely. Offers are not reservations: before acceptance the app re-checks ownership, maturity, sequences, and pending activity; stale offers must be recreated. -- **Marketplace** is the connected peer's market: new fixed-price listings and timed auctions use native XMR amounts; historical USD listings remain read-only. Checkout, fees and payouts are simulated. Sales allocate a configurable fee to the hosting operator (default 2.5%) and a hardcoded 1% author fee (3.5% total by default). Sellers still sign real card delivery after the mock payment step. **Never send real XMR: no payable checkout address or live processor is enabled.** Listings/orders are local to the selected market host, not gossiped; listing does not lock a card on-chain. See [peer markets, fees and payment status](docs/marketplace.md). - Each minted card shows current Wikipedia statistics alongside its immutable at-mint snapshot: pageviews, article size, language links, revision, and derived scores. Current values may change; at-mint values are committed to the block. Missing pageview data stays unavailable, not zero. - The appearance selector offers Catppuccin Mocha, Macchiato, Frappé, and Latte themes. diff --git a/compose.custody-pilot.yaml b/compose.custody-pilot.yaml index 3a84fda..8ab0e06 100755 --- a/compose.custody-pilot.yaml +++ b/compose.custody-pilot.yaml @@ -89,6 +89,7 @@ services: WIKIDECK_MARKET_TRADING_ENABLED: "${WIKIDECK_MARKET_TRADING_ENABLED:-1}" WIKIDECK_MARKET_HOST_FEE_ADDRESS: "${WIKIDECK_MARKET_HOST_FEE_ADDRESS:-44xHcCdFhW4b951yBHpkTPdLSJ85qTCnFQ8N7m96TtqqRL3dbhzbEH4fe2SJ3a6ESHcNyzCYH5nYJ9ActR1JtkeA7QYGbQv}" WIKIDECK_CUSTODY_MODE: sandbox + WIKIDECK_MARKET_RUNTIME_ENABLED: "${WIKIDECK_MARKET_RUNTIME_ENABLED:-1}" WIKIDECK_CUSTODY_STORAGE: postgres WIKIDECK_CUSTODY_PG_URL_FILE: /secrets/runtime/url WIKIDECK_CUSTODY_PG_CA_FILE: /secrets/runtime/ca.crt diff --git a/compose.custody.yaml b/compose.custody.yaml index 6cac6c0..874b83d 100755 --- a/compose.custody.yaml +++ b/compose.custody.yaml @@ -79,6 +79,7 @@ services: WIKIDECK_MARKET_TRADING_ENABLED: "${WIKIDECK_MARKET_TRADING_ENABLED:-1}" WIKIDECK_MARKET_HOST_FEE_ADDRESS: "${WIKIDECK_MARKET_HOST_FEE_ADDRESS:-44xHcCdFhW4b951yBHpkTPdLSJ85qTCnFQ8N7m96TtqqRL3dbhzbEH4fe2SJ3a6ESHcNyzCYH5nYJ9ActR1JtkeA7QYGbQv}" WIKIDECK_CUSTODY_MODE: sandbox + WIKIDECK_MARKET_RUNTIME_ENABLED: "${WIKIDECK_MARKET_RUNTIME_ENABLED:-1}" WIKIDECK_CUSTODY_STORAGE: postgres WIKIDECK_CUSTODY_PG_URL_FILE: /secrets/runtime/url WIKIDECK_CUSTODY_PG_CA_FILE: /secrets/runtime/ca.crt diff --git a/compose.mainnet.yaml b/compose.mainnet.yaml index 4dc4fb4..f31b66a 100755 --- a/compose.mainnet.yaml +++ b/compose.mainnet.yaml @@ -12,6 +12,7 @@ services: - "127.0.0.1:${WIKIDECK_MAINNET_PORT:-3201}:3001" environment: WIKIDECK_NETWORK: mainnet + WIKIDECK_MARKET_RUNTIME_ENABLED: "${WIKIDECK_MARKET_RUNTIME_ENABLED:-1}" WIKIDECK_PAYMENT_MODE: mock WIKIDECK_MARKET_ENABLED: "${WIKIDECK_MARKET_ENABLED:-1}" WIKIDECK_MARKET_TRADING_ENABLED: "${WIKIDECK_MARKET_TRADING_ENABLED:-1}" diff --git a/compose.testnet.yaml b/compose.testnet.yaml index 4f79b13..2ec60a7 100644 --- a/compose.testnet.yaml +++ b/compose.testnet.yaml @@ -1,7 +1,8 @@ -# Three independent validators, separate volumes, no miner auto-starts. -x-market-environment: &market-environment +# Three independent validators, separate volumes, no miner or market auto-starts. +x-node-environment: &node-environment WIKIDECK_NETWORK: testnet WIKIDECK_PAYMENT_MODE: mock + WIKIDECK_MARKET_RUNTIME_ENABLED: "${WIKIDECK_MARKET_RUNTIME_ENABLED:-0}" WIKIDECK_MARKET_ENABLED: "${WIKIDECK_MARKET_ENABLED:-1}" WIKIDECK_MARKET_TRADING_ENABLED: "${WIKIDECK_MARKET_TRADING_ENABLED:-1}" WIKIDECK_MARKET_HOST_FEE_ADDRESS: "${WIKIDECK_MARKET_HOST_FEE_ADDRESS:-44xHcCdFhW4b951yBHpkTPdLSJ85qTCnFQ8N7m96TtqqRL3dbhzbEH4fe2SJ3a6ESHcNyzCYH5nYJ9ActR1JtkeA7QYGbQv}" @@ -13,7 +14,7 @@ services: build: { context: ., target: runtime } ports: ["127.0.0.1:3101:3001"] environment: - <<: *market-environment + <<: *node-environment PUBLIC_ORIGIN: http://127.0.0.1:3101 WIKIDECK_PEERS: http://node-b:3001,http://node-c:3001 WIKIDECK_ALLOW_PRIVATE_PEERS: "1" @@ -32,7 +33,7 @@ services: build: { context: ., target: runtime } ports: ["127.0.0.1:3102:3001"] environment: - <<: *market-environment + <<: *node-environment PUBLIC_ORIGIN: http://127.0.0.1:3102 WIKIDECK_PEERS: http://node-a:3001,http://node-c:3001 WIKIDECK_ALLOW_PRIVATE_PEERS: "1" @@ -51,7 +52,7 @@ services: build: { context: ., target: runtime } ports: ["127.0.0.1:3103:3001"] environment: - <<: *market-environment + <<: *node-environment PUBLIC_ORIGIN: http://127.0.0.1:3103 WIKIDECK_PEERS: http://node-a:3001,http://node-b:3001 WIKIDECK_ALLOW_PRIVATE_PEERS: "1" diff --git a/compose.yaml b/compose.yaml index 7d79e10..5a493a4 100644 --- a/compose.yaml +++ b/compose.yaml @@ -12,6 +12,7 @@ services: WIKIDECK_PEERS: "${WIKIDECK_PEERS:-}" WIKIDECK_ALLOW_PRIVATE_PEERS: "${WIKIDECK_ALLOW_PRIVATE_PEERS:-0}" WIKIDECK_PAYMENT_MODE: mock + WIKIDECK_MARKET_RUNTIME_ENABLED: "${WIKIDECK_MARKET_RUNTIME_ENABLED:-0}" WIKIDECK_MARKET_ENABLED: "${WIKIDECK_MARKET_ENABLED:-1}" WIKIDECK_MARKET_TRADING_ENABLED: "${WIKIDECK_MARKET_TRADING_ENABLED:-1}" WIKIDECK_MARKET_HOST_FEE_ADDRESS: "${WIKIDECK_MARKET_HOST_FEE_ADDRESS:-44xHcCdFhW4b951yBHpkTPdLSJ85qTCnFQ8N7m96TtqqRL3dbhzbEH4fe2SJ3a6ESHcNyzCYH5nYJ9ActR1JtkeA7QYGbQv}" diff --git a/docs/market-host-configuration.md b/docs/market-host-configuration.md index 93b8eda..bd1e16b 100755 --- a/docs/market-host-configuration.md +++ b/docs/market-host-configuration.md @@ -1,9 +1,10 @@ # Optional market hosting and host fee wallet -These are **server runtime** environment variables, forwarded by the single-node, three-node, gated mainnet and persistent custody Compose files. They do not enable real payments. +These are **server runtime** environment variables, not browser settings. The single-node and three-node Compose profiles default the market runtime to off; the gated mainnet and dedicated custody profiles opt in. They do not enable real payments. | Variable | Default | Effect | | --- | --- | --- | +| `WIKIDECK_MARKET_RUNTIME_ENABLED` | `0` | `1` opens the local market journal, exposes market APIs, and starts reconciliation. `0` leaves market data untouched, does not reconcile it, and returns 404 for market APIs. Resolve existing orders before disabling a market with unresolved activity. | | `WIKIDECK_MARKET_ENABLED` | `1` | `0` removes public listings and rejects new listings, bids, purchases, custody reservations and fictitious funding. Node validation, mining, peer sync and free transfers/trades continue unchanged. | | `WIKIDECK_MARKET_TRADING_ENABLED` | `1` | `0` pauses new trading/funding but keeps public listings browsable. Useful for maintenance/read-only operation. | | `WIKIDECK_MARKET_HOST_FEE_ADDRESS` | Fixed project author XMR address | Public Monero recipient for the **hosting commission**, independently of the fixed additional author commission. | @@ -16,13 +17,13 @@ Default wallet: 44xHcCdFhW4b951yBHpkTPdLSJ85qTCnFQ8N7m96TtqqRL3dbhzbEH4fe2SJ3a6ESHcNyzCYH5nYJ9ActR1JtkeA7QYGbQv -Set the variables in the shell/Compose environment or a local Compose environment file, then recreate the intended app container. They are not browser build variables. Merely restarting a container does not replace its environment. Existing Compose defaults preserve current hosting behavior. In the three-node configuration shared values apply to all nodes; per-service environment overrides allow different hosts/fees. Do not point independent markets at a shared financial schema. +Set supported variables in the shell/Compose environment or a local Compose environment file, then recreate the intended app container. They are not browser build variables. Merely restarting a container does not replace its environment. The quick-start single-node and three-node profiles deliberately leave the market runtime off; explicitly enable it only for an operator-managed market. In the three-node configuration shared values apply to all nodes; per-service environment overrides allow different hosts/fees. Do not point independent markets at a shared financial schema. ## Existing obligations remain available -Disabling market hosting is **not a funds freeze or deletion**. Signed private activity, existing-order mock payment/delivery/refund, listing retirement/cancellation, custody cancellation and withdrawal-hold requests remain available under their existing checks. Reconciliation continues and data is retained. PostgreSQL remains required if that node already has PostgreSQL-backed liabilities; the switch is not a shortcut to abandoning custody responsibilities. Existing valid command receipts remain replayable without creating another mutation. +Turning off the market runtime is **not a funds freeze or deletion**. The market journal is preserved, but APIs and reconciliation are unavailable until the runtime is enabled again; this can pause existing-order resolution. Do not disable or stop an active market with unresolved orders or custody liabilities. PostgreSQL remains required if that node has PostgreSQL-backed liabilities; the switch is not a shortcut to abandoning custody responsibilities. The separate `WIKIDECK_MARKET_ENABLED=0` policy is different: it pauses new activity while retaining the market runtime and its existing resolution controls. -A peer that never wants custody can leave `WIKIDECK_CUSTODY_MODE=off` and use the ordinary single/three-node stack with `WIKIDECK_MARKET_ENABLED=0`; it does not need the dedicated PostgreSQL stack. Do not turn custody off merely to hide pre-existing liabilities; first resolve them under a reviewed shutdown procedure. The marketplace UI retains an activity/resolution surface and displays the disabled/paused policy rather than hiding recovery controls. +A peer that never wants custody can leave `WIKIDECK_CUSTODY_MODE=off`; mining, peer sync, and free card transfers/trades do not require the market runtime or dedicated PostgreSQL stack. ## Fee recipient and signature compatibility diff --git a/server/testnet/http.ts b/server/testnet/http.ts index 3ee425f..6a6cee0 100644 --- a/server/testnet/http.ts +++ b/server/testnet/http.ts @@ -16,6 +16,7 @@ import { wikipediaEnrichment } from '../enrichment.ts'; import { snapshotStats } from '../../shared/enrichment.ts'; import { wikipediaArticles } from '../wiki.ts'; import { Market, marketConfig } from '../market/store.ts'; +import { paymentMode } from '../market/payments.ts'; import { marketCommandSchema } from '../../shared/market.ts'; import { marketCommandV3Schema } from '../../shared/market-v3.ts'; import { custodyCommandSchema } from '../../shared/custody.ts'; @@ -40,9 +41,18 @@ import { trustedProxies, operationsPort, startOperations } from '../operations.t const root = fileURLToPath(new URL('../../', import.meta.url)); assertLaunchAllowed(); -const paymentConfig = marketConfig(); // Fail before opening node resources if live payments are requested. -await validateMarketPolicy(paymentConfig); // Reject invalid recipient checksum/network before opening node resources. +const marketRuntimeSetting = process.env.WIKIDECK_MARKET_RUNTIME_ENABLED ?? '0'; +if (marketRuntimeSetting !== '0' && marketRuntimeSetting !== '1') { + throw new Error('WIKIDECK_MARKET_RUNTIME_ENABLED must be exactly 0 or 1'); +} +const marketRuntimeEnabled = marketRuntimeSetting === '1'; const custodyConfig = custodyMode(); // Explicit opt-in sandbox only. Unknown/live modes fail before opening resources. +paymentMode(); // Keep real-payment modes fail-closed even when the optional market runtime is off. +let paymentConfig: ReturnType | undefined; +if (marketRuntimeEnabled || custodyConfig === 'sandbox') { + paymentConfig = marketConfig(); + await validateMarketPolicy(paymentConfig); // Reject invalid recipient checksum/network before opening node resources. +} const canonicalObserverMode = process.env.WIKIDECK_CUSTODY_CANONICAL_REHEARSAL; if (canonicalObserverMode !== undefined && canonicalObserverMode !== '0' && canonicalObserverMode !== '1') { throw new Error('WIKIDECK_CUSTODY_CANONICAL_REHEARSAL must be exactly 0 or 1'); @@ -86,8 +96,8 @@ let peers: PeerNetwork; try { peers = new PeerNetwork({ ledger, urls:(process.env.WIKIDECK_PEERS ?? '').split(',').map(s=>s.trim()).filter(Boolean), allowPrivate:process.env.WIKIDECK_ALLOW_PRIVATE_PEERS === '1' }); } catch(e) {ledger.close();engine.close();await lock.close();await unlink(lockPath);throw e;} -let market: Market; -try { market = await Market.open(dataDir, ledger, paymentConfig, Date.now, { worker: true }); } +let market: Market | undefined; +try { if (marketRuntimeEnabled) market = await Market.open(dataDir, ledger, paymentConfig!, Date.now, { worker: true }); } catch(e) {peers.close();ledger.close();engine.close();await lock.close();await unlink(lockPath);throw e;} let custody: CustodyMarket | PostgresCustody | undefined; let custodyObserver: CanonicalObserver | undefined; @@ -97,7 +107,7 @@ let moneroDepositContext: MainnetEnrollmentContext | undefined; let moneroWithdrawalPool: Pool | undefined; let moneroWithdrawalCustodianId: string | undefined; try { - if (custodyConfig === 'sandbox') custody = await openCustodyStorage(dataDir, { ...paymentConfig, + if (custodyConfig === 'sandbox') custody = await openCustodyStorage(dataDir, { ...paymentConfig!, card: (hash, owner, sequence) => { const nft = ledger.nft(hash); if (!nft || nft.owner !== owner || nft.confirmations < CONSENSUS.coinbaseMaturity || nft.sequence !== sequence || @@ -147,7 +157,7 @@ try { await verifyMainnetCustodyIdentity(moneroWithdrawalPool, moneroWithdrawalCustodianId); await moneroWithdrawalPool.query('SELECT 1 FROM wk_custody.monero_withdrawal_intents LIMIT 0'); } -} catch(e) {await moneroWithdrawalPool?.end();await moneroDepositPool?.end();await custodyObserver?.close();await custody?.close();await market.close();peers.close();ledger.close();engine.close();await lock.close();await unlink(lockPath);throw e;} +} catch(e) {await moneroWithdrawalPool?.end();await moneroDepositPool?.end();await custodyObserver?.close();await custody?.close();await market?.close();peers.close();ledger.close();engine.close();await lock.close();await unlink(lockPath);throw e;} const app = express(); app.disable('x-powered-by'); if(proxyTrust.length)app.set('trust proxy',proxyTrust); @@ -181,7 +191,23 @@ app.get('/api/canonical',(req,res)=>{ app.get('/api/network',(_req,res)=>res.json(launchManifest())); app.get('/api/chain',(_req,res)=>res.json(ledger.legacySnapshot(limits.legacyBlocks))); app.get('/api/peers',(_req,res)=>res.json({peers:peers.status()})); -app.get('/api/market', (req,res)=>res.json(market.browse(Number(req.query.offset ?? 0)))); +if (market) { +app.get('/api/market', (req,res)=>res.json(market!.browse(Number(req.query.offset ?? 0)))); +app.post('/api/market/command',rateLimit({windowMs:60000,limit:60,standardHeaders:'draft-8',legacyHeaders:false}),async(req,res)=>{ + const current = marketCommandV3Schema.safeParse(req.body); + const command = current.success ? current.data : marketCommandSchema.parse(req.body); + try { + const result = await market!.execute(command); + res.json(result); + if(command.action.type==='deliver')void peers.broadcastTransfer(command.action.transfer).catch(()=>{}); + } catch(error) { + if(error instanceof RpcError)throw error; + // Marketplace storage/payment internals must never leak through the generic node error handler. + if(error instanceof Error && !/SQLITE|constraint|database/i.test(error.message))res.status(400).json({error:error.message.slice(0,200)}); + else res.status(409).json({error:'Marketplace state conflict. Refresh and retry.'}); + } +}); +} app.get('/api/custody', async (req,res)=> { if (!custody) { res.json({ enabled: false }); return; } try { res.json(await custody.browse(Number(req.query.offset ?? 0))); } @@ -252,20 +278,6 @@ if (withdrawalRequestMode === '1' && moneroWithdrawalPool && moneroWithdrawalCus } }); } -app.post('/api/market/command',rateLimit({windowMs:60000,limit:60,standardHeaders:'draft-8',legacyHeaders:false}),async(req,res)=>{ - const current = marketCommandV3Schema.safeParse(req.body); - const command = current.success ? current.data : marketCommandSchema.parse(req.body); - try { - const result = await market.execute(command); - res.json(result); - if(command.action.type==='deliver')void peers.broadcastTransfer(command.action.transfer).catch(()=>{}); - } catch(error) { - if(error instanceof RpcError)throw error; - // Marketplace storage/payment internals must never leak through the generic node error handler. - if(error instanceof Error && !/SQLITE|constraint|database/i.test(error.message))res.status(400).json({error:error.message.slice(0,200)}); - else res.status(409).json({error:'Marketplace state conflict. Refresh and retry.'}); - } -}); app.get('/api/decks/:address', rateLimit({windowMs:60000,limit:60,standardHeaders:'draft-8',legacyHeaders:false}), (req,res)=>{ if(typeof req.params.address!=='string'||!/^[a-f0-9]{64}$/.test(req.params.address)){ res.status(400).json({error:'Invalid wallet address'});return; @@ -359,7 +371,7 @@ const server=app.listen(port,host,()=>{ const operations=startOperations(opsPort,()=>({network:NETWORK,paymentMode:'mock', ledger:ledger.diagnostics(),native:engine.diagnostics(), peers:{configured:peers.status().length,connected:peers.status().filter(p=>p.connected).length}, - rpc:{api:apiBudget.status(),p2p:peerBudget.status()},market:market.diagnostics(), + rpc:{api:apiBudget.status(),p2p:peerBudget.status()},market:market?.diagnostics() ?? { enabled:false }, canonicalObserver:custodyObserver?.status(), custody: custody && 'diagnostics' in custody ? custody.diagnostics() : { backend: custody ? 'sqlite-sandbox' : 'off' }}),resolve(dataDir,PROFILE)); server.maxConnections=256; @@ -368,16 +380,16 @@ server.requestTimeout=15000; server.keepAliveTimeout=5000; server.setTimeout(30000,socket=>socket.destroy()); // Advance simulated payout/expiry state even when no browser is open. No real funds are sent. -const marketTimer=setInterval(()=>{try {market.browse();}catch{console.error('Marketplace reconciliation failed; operator review required.');}},15000); -marketTimer.unref(); let stopping=false; let catchupPaused=false; let catchupImmediate:NodeJS.Immediate|undefined; +let marketTimer:NodeJS.Timeout|undefined; +let marketCatchupTimer:NodeJS.Timeout|undefined; // Drain durable catch-up without page-load dependence. Each pass is a smaller synchronous // SQLite slice, then setImmediate yields so HTTP and peer work can run between passes. const advanceMarketCatchup=()=>{ catchupImmediate=undefined; - if(stopping||catchupPaused||market.isReconciliationWorkerBusy()||!market.hasReconciliationBacklog())return; + if(!market||stopping||catchupPaused||market.isReconciliationWorkerBusy()||!market.hasReconciliationBacklog())return; if(market.isReconciliationWorkerFailed()){ catchupPaused=true;console.error('Marketplace reconciliation worker failed; operator review required.');return; } @@ -387,17 +399,21 @@ const advanceMarketCatchup=()=>{ catchupImmediate=setImmediate(advanceMarketCatchup);catchupImmediate.unref(); } }; -const marketCatchupTimer=setInterval(()=>{ - if(!stopping&&!catchupPaused&&!catchupImmediate&&market.hasReconciliationBacklog()){ - catchupImmediate=setImmediate(advanceMarketCatchup);catchupImmediate.unref(); - } -},250); -marketCatchupTimer.unref(); +if (market) { + marketTimer=setInterval(()=>{try {market!.browse();}catch{console.error('Marketplace reconciliation failed; operator review required.');}},15000); + marketTimer.unref(); + marketCatchupTimer=setInterval(()=>{ + if(!stopping&&!catchupPaused&&!catchupImmediate&&market!.hasReconciliationBacklog()){ + catchupImmediate=setImmediate(advanceMarketCatchup);catchupImmediate.unref(); + } + },250); + marketCatchupTimer.unref(); +} for(const signal of ['SIGTERM','SIGINT']as const)process.once(signal,()=>{ - if(stopping)return;stopping=true;peers.close();operations.close();clearInterval(marketTimer);clearInterval(marketCatchupTimer); + if(stopping)return;stopping=true;peers.close();operations.close();if(marketTimer)clearInterval(marketTimer);if(marketCatchupTimer)clearInterval(marketCatchupTimer); if(catchupImmediate)clearImmediate(catchupImmediate); const observerDrain=custodyObserver?.close()??Promise.resolve(); const timeout=setTimeout(()=>process.exit(1),25000);timeout.unref(); - server.close(async()=>{await observerDrain;await moneroWithdrawalPool?.end();await moneroDepositPool?.end();await custody?.close();await market.close();ledger.close();engine.close();await lock.close();await unlink(lockPath).catch(()=>{});clearTimeout(timeout);process.exit(0);}); + server.close(async()=>{await observerDrain;await moneroWithdrawalPool?.end();await moneroDepositPool?.end();await custody?.close();await market?.close();ledger.close();engine.close();await lock.close();await unlink(lockPath).catch(()=>{});clearTimeout(timeout);process.exit(0);}); }); -server.on('error',async()=>{stopping=true;clearInterval(marketTimer);clearInterval(marketCatchupTimer);if(catchupImmediate)clearImmediate(catchupImmediate);operations.close();peers.close();await custodyObserver?.close();await moneroWithdrawalPool?.end();await moneroDepositPool?.end();await custody?.close();await market.close();ledger.close();engine.close();await lock.close();await unlink(lockPath).catch(()=>{});process.exit(1);}); +server.on('error',async()=>{stopping=true;if(marketTimer)clearInterval(marketTimer);if(marketCatchupTimer)clearInterval(marketCatchupTimer);if(catchupImmediate)clearImmediate(catchupImmediate);operations.close();peers.close();await custodyObserver?.close();await moneroWithdrawalPool?.end();await moneroDepositPool?.end();await custody?.close();await market?.close();ledger.close();engine.close();await lock.close();await unlink(lockPath).catch(()=>{});process.exit(1);}); diff --git a/src/App.tsx b/src/App.tsx index 4b9a3d2..2f5566a 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,7 +1,7 @@ import { useEffect, useRef, useState } from 'react'; import { ArrowDownLeft, ArrowLeftRight, ArrowRight, ArrowUpRight, BookOpen, Check, ChevronRight, CircleHelp, Copy, Cpu, Download, ExternalLink, Globe2, Layers3, LayoutDashboard, LoaderCircle, - Pickaxe, Search, Shield, ShoppingBag, Sparkles, Wallet as WalletIcon, X } from 'lucide-react'; + Pickaxe, Search, Shield, Sparkles, Wallet as WalletIcon, X } from 'lucide-react'; import { rarity } from '../shared/protocol.ts'; import { CONSENSUS, NETWORK, isNftTrade, nftTransferMessage, testnetOwnerOf, transactionCardIds, type TestnetBlock, type TestnetSnapshot } from '../shared/testnet.ts'; @@ -11,13 +11,12 @@ import { WalletPanel } from './WalletPanel.tsx'; import { useModalFocus } from './useModalFocus.ts'; import { ThemePicker } from './ThemePicker.tsx'; import { TradeDesk } from './TradeDesk.tsx'; -import { Marketplace } from './Marketplace.tsx'; import { IS_MAINNET, IS_PILOT, NETWORK_LABEL } from '../shared/network.ts'; import { StateClient } from '../shared/rpc-client.ts'; import './App.css'; import './testnet.css'; -type View = 'Discover' | 'My collection' | 'Block explorer' | 'Trade decks' | 'Marketplace'; +type View = 'Discover' | 'My collection' | 'Block explorer' | 'Trade cards'; const short = (s: string) => s ? `${s.slice(0, 6)}…${s.slice(-4)}` : '—'; const asCard = (block: TestnetBlock): CardData => ({ article: block.article, hash: block.powHash, block }); const message = (error: unknown) => error instanceof Error ? error.message : 'Request failed. Please try again.'; @@ -162,8 +161,8 @@ export default function App() {