Files
metin2-server/tools/economy

Durable economy transactions

This is the replacement DB transaction path for offline sales and Gaya. It is implemented separately from the unsafe legacy offline-shop protocol. Do not change PortOfflineShopEconomyReady() to enable that old protocol.

Current entry points

  • /mt_economy status [PAGE] lists recent results, public/owned listings, buyer orders and available proceeds. Pages start at zero.
  • /mt_economy list CELL PRICE places the complete inventory stack in custody.
  • /mt_economy buy LISTING PRICE reserves that listing and holds the price in its order. An outdated price or another buyer's reservation is rejected.
  • /mt_economy refund ORDER returns the held price and reopens the listing.
  • /mt_economy claim ORDER moves the original item ID into the buyer account's mall storage and credits the seller's proceeds in the same transaction.
  • /mt_economy cancel LISTING returns an OPEN listing to its owner's mall.
  • /mt_economy withdraw transfers available proceeds into character gold.
  • /mt_economy gaya_retire retires a migrated catalogue after its Gaya balance reaches zero and active listings, refundable orders and proceeds are settled. It permanently disables this character's Gaya catalogue so the native character deletion flow can proceed. It uses the same logout/save fences. Positive balances are refused, never silently discarded or refunded.
  • Existing /gem buy, refresh and expansion commands/items submit DB intents. Gaya purchases deliver stable item IDs to account mall storage. Paid refresh and expansion consume their item in the same transaction as their effect.

All mutating requests close the game connection through the normal logout path. Reconnect and select the same character: DB evicts its caches, completes the queued SQL writes, settles the durable intent, and resumes character load. No in-game gold, Gaya, inventory or paid catalogue change happens before this handoff. status and the new ui query do not disconnect. The native client now loads the original AVA2 offline window through its inventory button/F8 and routes confirmed actions to this backend. Buying reserves an order; claiming is a separate action that delivers to mall and credits the seller. Real connected cross-channel/mobile acceptance is still pending. World NPC creation and legacy NPC-to-new-seller mapping are not implemented by this window adapter.

The window uses /mt_economy ui MODE PAGE SEQ OWNER TOKEN (mode 0 public, 1 owned, 2 READY orders; zero-based pages of 20). A consistent read transaction builds and validates complete MTECON1 begin/row/meta/result/end command frames before sending any. Read failures return MTECON1 error SEQ storage. /mt_economy act TOKEN OP ... preserves a nonzero random 32-hex receipt for list/buy/claim/refund/cancel/withdraw. List additionally carries expected vnum and count. Account, character and wallet fields always come from the session; exact-token receipt queries are account/character scoped. Immediate rejection returns MTECON1 action_error TOKEN rejected. UiStatus=12 cannot be enqueued as a mutation; schema version and internal record sizes are unchanged.

An order remains READY until claimed or refunded; there is no automatic order expiry. A full mall or gold/proceeds limit leaves the order/custody intact and allows a later request. Seller proceeds become available after successful delivery, rather than while the buyer can still refund the reservation.

Storage and ownership

Storage Authority
item Normal inventory, equipment, safebox and mall item rows
port_economy_custody Exact original item row while a listing is OPEN/RESERVED
port_economy_listings Seller, immutable price and current listing/order state
port_economy_orders Held buyer payment and READY/CLAIMED/REFUNDED result
port_economy_credit Seller proceeds awaiting withdrawal
port_economy_requests / pending Immutable token/body, result and one pending intent per character
port_economy_item_reservations Durable high-water marks for allocated Gaya reward IDs, including aborted intents
port_economy_gaya Catalogue generation, deadline and all 27 offers
player.gold / quest gem flags Character wallet and unlocked slots, changed only after logout/fencing

The old offline_shop_npc, offline_shop_item, offline_shop_log and player.shop_money are preserved. They are not imported or treated as new orders. Their old writes did not record enough evidence to infer missing buyer refunds or delivery safely. Existing production custody and balances must be reconciled against actual item IDs, owners, statuses and logs before any live migration. This batch has not modified or inspected production assets.

Custody uses an exact CREATE TABLE ... LIKE item layout; transactions copy all stored columns, retaining sockets, attributes, extra state and the original ID. Game item saves/destruction cannot write a custodial ID. ID range startup reads the maximum across normal items, custody and durable reward reservations, so a restart cannot reissue an escrowed or pending reward ID. Unmigrated legacy offline_shop_item IDs are also reserved when that table exists, even before the new economy schema is installed; lookup errors refuse range allocation. Reservation tombstones must not be casually deleted during cleanup or rollback.

Gaya imports an existing validated local catalogue on its first economic transaction. Its committed SQL catalogue then supersedes the local file and does not depend on that file/directory being writable. Balance, reward rows and offer/generation commit together; refresh/expansion effects and consumables do likewise. The normal quest-save path remains a wallet mirror during play and is fully drained before settlement. Wallet snapshots that do not match persisted values are rejected, rather than spending an older balance.

Native character deletion is refused while there is pending work, active custody, a refundable order, unclaimed proceeds or an active migrated Gaya catalogue. Explicit gaya_retire preserves all offers, deadline and paid slots; the reserved generation 9223372036854775807 marks the retained SQL row retired. The immutable request records the original generation in its result reference. Repeated retirement is harmless. Buy, refresh, expansion and local-file fallback cannot reactivate the retired catalogue. Deletion remains blocked if a quest writer later adds a nonzero Gaya balance. Spend Gaya and settle external assets before retiring; this is not a balance forfeiture or currency conversion feature. Use coordinated game/DB binaries that understand operation 11 and the terminal generation. Existing table version 1 and request record sizes stay unchanged; old pending requests remain readable. No additional startup DDL is required.

Installation and recovery boundaries

schema.sql is an explicit, reviewable migration, never startup DDL. It supports the unsuffixed player schema only. player, item and quest, plus every new participant, must use InnoDB; readiness refuses missing/nontransactional tables and differing custody/item column layouts. This script does not convert those three existing tables or overwrite existing balances/history. Install and change schemas only while all writers are stopped, with verified backups and asset reconciliation. Schema presence is cached until process restart.

Deploy matching game, DB and all internal libraries together: internal packet 77 and the AsyncSQL fence ABI require coordinated binaries. The classic client wire version stays mt20261024; deploy the matching native window client and its offline layout/image resources with this integration. Do not downgrade to a version that ignores custody and ID reservations after new transactions have been accepted. Disabling the old offline-shop gate is not a recovery mechanism for the new path.

SQL failures retain the same pending token for retry. An ambiguous COMMIT is resolved from the committed request/order state. Connections can reconnect before a new attempt, but automatic reconnect is disabled throughout a pinned transaction. Failed final saves abort the intent without economic mutations. Result/history and reservation rows are retained; no automatic log truncation or destructive compensation is performed.

Verification

tests/features/test_economy.py runs the actual C++ store with an explicit SQLite SQL-dialect adapter and ASan/UBSan. The same C++ scenarios in fixtures/economy_probe.cpp also run against isolated real MySQL 5.6/InnoDB on FreeBSD i386. They cover all nine mutation types, each settlement statement/COMMIT exit boundary after durable enqueue, competing buyers, duplicate claim/refund settlement, partial reward SQL failure, full mall rollback, wallet changes and stable-ID replay.

test_economy_coordinator.py executes the production DB coordinator with peer, cache and FIFO completion boundaries replaced. test_gaya_runtime.py executes the production Gaya unit with SQL/item-factory/submission boundaries replaced, verifying it does not charge, grant or consume paid items in game.

Evidence and real MySQL connection-loss/server-SIGKILL recovery results are in the client repository's audit/evidence/planb-economy-20261020/. These tests do not constitute a connected multi-core game/client or mobile-device acceptance. No production installation or migration was performed.

Current acceptance scope

The user excluded historical asset migration/compensation from the current repair scope. Existing legacy rows remain preserved; no legacy import or refund is implied by accepting new transactions. The optional read-only reconcile.py utility is available for a future review and is not a current release gate. Native NPC/window routing, complete connected acceptance, actual mall checkout, mobile interaction and remaining Plan B product checks still require evidence.