Files
CustomNPC-Plus/1.11_Market_Update.md
T
2026-01-23 21:53:12 -05:00

21 KiB

CustomNPC+ 1.11 Market Update - Implementation Plan

Overview

The 1.11 Market Update introduces a comprehensive economy system for CustomNPC+:

  1. Currency System - Built-in CNPC+ currency with optional Vault integration
  2. Trader Enhancements - Stock system, currency-based trades, reset timers
  3. Auction House - Global auction system with bidding, buyout, and claims

1. Currency System

Status: COMPLETE ✅

The currency system provides a unified economy for CNPC+ features.

Features

  • Built-in CNPC+ Currency - Stored in PlayerData, persists across profile slots
  • Vault Integration - Optional, when enabled all operations use Vault instead
  • Scripting API - Full access via IPlayer methods
  • Unified Usage - Both Trader and Auction systems use PlayerCurrencyData which auto-delegates to Vault

Vault Integration Flow

┌─────────────────────────────────────────────────────────────────┐
│                    PlayerCurrencyData                            │
│                                                                  │
│  shouldUseVault() = ConfigMarket.UseVault && VaultUtil.isEnabled()│
│                                                                  │
│  ┌─────────────────────────────────────────────────────────────┐ │
│  │ All methods check shouldUseVault() first:                    │ │
│  │   - getBalance() → VaultUtil.getBalance() or local balance   │ │
│  │   - withdraw()   → VaultUtil.withdrawMoney() or local        │ │
│  │   - deposit()    → VaultUtil.addMoney() or local             │ │
│  │   - canAfford()  → VaultUtil.has() or local check            │ │
│  └─────────────────────────────────────────────────────────────┘ │
│                                                                  │
│  Used by: ContainerNPCTrader, AuctionController                  │
└─────────────────────────────────────────────────────────────────┘

Key Files

File Purpose
PlayerCurrencyData.java Per-player currency storage, Vault delegation
IPlayerCurrencyData.java API interface for currency operations
ConfigMarket.java Currency configuration (UseVault, CurrencyName, StartingBalance, MaxBalance)
VaultUtil.java Vault API integration via reflection

Configuration (ConfigMarket.java)

Market.Currency:
  - Use Vault: false
  - Currency Name: "Coins"
  - Starting Balance: 0
  - Max Balance: 2147483647

Scripting API (IPlayer)

player.getCurrencyBalance()        // Get balance
player.setCurrencyBalance(amount)  // Set balance
player.depositCurrency(amount)     // Add currency (returns success)
player.withdrawCurrency(amount)    // Remove currency (returns success)
player.canAffordCurrency(amount)   // Check if can afford
player.isUsingVaultCurrency()      // Check if Vault is active
player.getFormattedCurrencyBalance() // Get formatted string

2. Trader Enhancements

Status: COMPLETE ✅


2.1 Stock System - COMPLETE ✅

Traders can have limited stock that resets on configurable schedules.

Stock Modes

Mode Description Status
Global All players share the same stock pool ✅ Working
Per-Player Each player has their own stock counts ✅ Working

Stock Reset Types (EnumStockReset)

Type Description Status
NONE Stock never resets ✅ Working
MCDAILY Resets every MC day (24000 ticks) ✅ Working
MCWEEKLY Resets every 7 MC days (168000 ticks) ✅ Working
MCCUSTOM Custom MC tick interval ✅ Working
RLDAILY Resets every 24 real-life hours ✅ Working
RLWEEKLY Resets every 7 real-life days ✅ Working
RLCUSTOM Custom real-time interval ✅ Working

Stock UI Features - COMPLETE ✅

Feature Status Notes
Stock count per item ✅ Shows to right of output slot
Out of stock indicator ✅ Dark overlay + red count
Reset timer countdown ✅ Real-time client-side countdown in top-right
"Reopen Trader" message ✅ Shows when countdown reaches 0
Admin stock configuration ✅ SubGuiNpcTraderStock
Per-slot stock limits ✅ SubGuiNpcTraderStockSlots
Reset stock button ✅ With confirmation dialog
Reset cooldown button ✅ With confirmation dialog

2.2 Trader Currency Support - COMPLETE ✅

Trades can require BOTH items AND currency (additive costs). Uses PlayerCurrencyData which auto-delegates to Vault when enabled.

Trade Entry Structure

Each trade slot can have:

  • Sold Item - What the player receives ✅
  • Currency 1 - First item cost (existing) ✅
  • Currency 2 - Second item cost (existing) ✅
  • Currency Cost - CNPC+ Currency / Vault cost ✅ NEW

Implementation Details

  • Currency cost stored as long[] currencyCost[18] in RoleTrader
  • Uses data.currencyData.getBalance() and data.currencyData.withdraw()
  • Automatically uses Vault when ConfigMarket.UseVault is enabled
  • NBT serialization for persistence ✅

2.3 Player Trader GUI - COMPLETE ✅

Display Features

Element Position Status
"Trader" label Top-left ✅
Reset countdown Top-right ✅ Real-time ticking
Stock count Right of each trade ✅ Green/Red
Player balance Bottom-right ✅
Status message Bottom-left ✅ On hover

2.4 Multi-Player Sync - COMPLETE ✅

MarketRegistry provides linked market synchronization across all NPCs sharing the same market.


2.5 Scripting API - COMPLETE ✅

Full API available via IRoleTrader interface.


3. Auction House System

Status: COMPLETE ✅

3.1 Architecture Overview

┌─────────────────────────────────────────────────────────────────┐
│                     AuctionController                            │
│  - Manages all auction data with player indices                  │
│  - Handles listing/bidding/buyout logic                          │
│  - Race-condition protected with ReentrantReadWriteLock          │
│  - Async saves on CNPC+ thread                                   │
│  - 20-second update cycle for performance                        │
└─────────────────────────────────────────────────────────────────┘
                              │
              Uses PlayerCurrencyData (Vault-aware)
                              │
┌─────────────────────────────────────────────────────────────────┐
│                   AuctionNotification                            │
│  - Tracks pending notifications per player                       │
│  - Sends notifications on login                                  │
│  - Types: Won, Outbid, Sold, Expired, Claimed                    │
└─────────────────────────────────────────────────────────────────┘

3.2 Vault Integration

The Auction system uses PlayerCurrencyData for all currency operations:

  • AuctionController.createListing() → currencyData.withdraw(fee)
  • AuctionController.placeBid() → currencyData.withdraw(bidAmount)
  • AuctionController.buyout() → currencyData.withdraw(buyoutPrice)
  • AuctionController.claimCurrency() → currencyData.deposit(amount)

When Vault is enabled (ConfigMarket.UseVault = true):

  • All operations automatically use Vault economy
  • No code changes required - PlayerCurrencyData handles delegation

3.3 GUI Structure

GuiAuctionInterface (Base GUI - opened via Auctioneer NPC)
    │
    ├── GuiAuctionListing (Browse auctions - PAGE_LISTINGS)
    │   - 9x5 grid of auction items
    │   - Filter button with tooltip showing current settings
    │   - Click item → Opens GuiAuctionBidding
    │   - Pagination with up/down arrows
    │
    ├── GuiAuctionSell (Create new listing - PAGE_SELL)
    │   - Sell slot for item to auction (cloned from inventory)
    │   - Click inventory: left=add stack, right=add 1
    │   - Click sell slot: left=clear, right=remove 1
    │   - Starting price + buyout price text fields
    │   - Allow Buyout toggle button
    │   - Listing fee display
    │   - Confirm button with coin icon
    │
    ├── GuiAuctionTrades (My Trades - PAGE_CLAIMS)
    │   - 9x5 grid showing: active listings, active bids, claims
    │   - Blue tint: active listings/bids
    │   - Green tint: claimable items
    │   - Red tint: refunds
    │   - Confirmation system for cancel/claim operations
    │
    ├── GuiAuctionBidding (View listing details)
    │   - Item display slot
    │   - Auction info (seller, price, time, bids)
    │   - Bid button → SubGuiAuctionBid
    │   - Buy Now button → SubGuiAuctionBuyNow
    │   - Own listings: buttons hidden, view-only
    │
    ├── SubGuiAuctionBid (Bid confirmation popup)
    │   - Shows minimum bid, player balance
    │   - Bid amount input field
    │   - Place Bid / Cancel buttons
    │
    ├── SubGuiAuctionBuyNow (Buyout confirmation popup)
    │   - Shows buyout price, player balance
    │   - Yes / Cancel buttons
    │
    └── SubGuiAuctionSearch (Filter popup)
        - Search text input
        - Apply/Cancel buttons

3.4 Client Config Sync

The client uses AuctionClientConfig to cache server settings:

  • Synced via LoginPacket on player join
  • Client never uses ConfigMarket directly for display
  • Ensures server authority over fees, currency name, etc.
// Server sends config in LoginPacket
AuctionClientConfig.writeToNBT(compound);  // Server side

// Client receives and caches
AuctionClientConfig.readFromNBT(compound);  // Client side

// Client GUI uses cached values
AuctionClientConfig.getListingFee();
AuctionClientConfig.getCurrencyName();
AuctionClientConfig.getMinBidIncrement();

3.5 Data Structures

AuctionListing

public class AuctionListing {
    String id;                 // Unique listing ID (UUID-based)
    UUID sellerUUID;           // Seller's UUID
    String sellerName;         // Seller's display name
    ItemStack item;            // Item being sold
    long startingPrice;        // Minimum starting bid
    long buyoutPrice;          // Instant buy price (0 = no buyout)
    long currentBid;           // Current highest bid
    UUID highBidderUUID;       // Current high bidder (null if no bids)
    String highBidderName;     // High bidder display name
    int bidCount;              // Number of bids placed
    long createdTime;          // When listing was created
    long endTime;              // When auction ends
    EnumAuctionStatus status;  // ACTIVE, ENDED, CANCELLED, CLAIMED
}

AuctionClaim

public class AuctionClaim {
    String id;                 // Unique claim ID
    UUID playerUUID;           // Player who can claim
    String listingId;          // Related auction listing
    EnumClaimType type;        // ITEM, CURRENCY, REFUND
    ItemStack item;            // Item to claim (if type = ITEM)
    long currency;             // Currency to claim (if type = CURRENCY/REFUND)
    long createdTime;          // When claim was created
    boolean claimed;           // Whether claimed
}

3.6 Security Features

All actions are validated server-side:

Check Location Description
Own item bid prevention placeBid() listing.isSeller(playerUUID) check
Own item buyout prevention buyout() listing.isSeller(playerUUID) check
Auction expiry check placeBid()/buyout() Double-check inside write lock
Currency validation All actions Verify balance before operations
Claim ownership claimItem()/claimCurrency() claim.isForPlayer(playerUUID) check

3.7 Snipe Protection

When a bid is placed with less than SnipeProtectionMinutes remaining:

  • Extend the auction end time TO SnipeProtectionMinutes from now
  • Never extend beyond SnipeProtectionMinutes
  • Default: 2 minutes

Example: Auction ends in 30 seconds, someone bids → Timer resets to 2:00


4. AuctionController Performance & Thread Safety

4.1 Threading Model

┌─────────────────────────────────────────────────────────────────┐
│                    AuctionController                              │
│                                                                   │
│  ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐   │
│  │ ReentrantRWLock │  │ AtomicBoolean   │  │ CNPC+ Thread    │   │
│  │ (dataLock)      │  │ dirty, saving   │  │ (async saves)   │   │
│  └─────────────────┘  └─────────────────┘  └─────────────────┘   │
│                                                                   │
│  Read operations → Read Lock (concurrent)                         │
│  Write operations → Write Lock (exclusive)                        │
│  Save operations → Async on CNPC+ thread                          │
└─────────────────────────────────────────────────────────────────┘

4.2 Player Indices for O(1) Lookups

Index Type Purpose
playerListingIds Map<UUID, Set<String>> Active listings by seller
playerBidIds Map<UUID, Set<String>> Listings where player has active bid
playerClaimIds Map<UUID, Set<String>> Unclaimed claims by player

Performance Impact:

  • getPlayerListingCount(): O(n) → O(1)
  • getPlayerActiveListings(): O(n) → O(k) where k = player's listings
  • getPlayerActiveBids(): O(n) → O(k)
  • getPlayerClaims(): O(n) → O(k)

4.3 Update Intervals

Operation Interval Rationale
Process ended auctions 20 seconds (400 ticks) Reduces server load
Process expired claims 20 seconds (400 ticks) Same cycle as auctions
Save dirty data 60 seconds (1200 ticks) Batches writes, reduces I/O

4.4 Race Condition Prevention

  1. Bid vs Auction End - Double-check isExpired() inside write lock
  2. Currency Deduction - Withdraw before updating listing
  3. Previous Bidder Refund - Store info before modification
  4. Concurrent Saves - AtomicBoolean prevents duplicates
  5. Index Consistency - All updates within same write lock

4.5 Server Shutdown Handling

On FMLServerStoppedEvent:

  1. AuctionController.save() called synchronously
  2. Uses CNPC+ thread (single-threaded executor)
  3. All pending saves complete before shutdown

5. File Structure

New Files Created

constants/
  EnumAuctionStatus.java     ✅
  EnumAuctionSort.java       ✅
  EnumClaimType.java         ✅
  EnumNotificationType.java  ✅

controllers/
  AuctionController.java     ✅ (with threading, indices, Vault support)

controllers/data/
  AuctionListing.java        ✅
  AuctionClaim.java          ✅
  AuctionFilter.java         ✅
  AuctionNotification.java   ✅

roles/
  RoleAuctioneer.java        ✅

containers/
  ContainerAuction.java         ✅
  ContainerAuctionListing.java  ✅
  ContainerAuctionBidding.java  ✅
  ContainerAuctionTrades.java   ✅
  ContainerAuctionSell.java     ✅
  InventoryAuctionDisplay.java  ✅
  SlotAuctionDisplay.java       ✅

client/
  AuctionClientConfig.java      ✅ (client-side config cache)

client/gui/player/
  GuiAuctionInterface.java      ✅
  GuiAuctionListing.java        ✅
  GuiAuctionSell.java           ✅
  GuiAuctionTrades.java         ✅
  GuiAuctionBidding.java        ✅
  SubGuiAuctionSearch.java      ✅
  SubGuiAuctionBid.java         ✅
  SubGuiAuctionBuyNow.java      ✅
  AuctionTooltipHandler.java    ✅

client/gui/util/
  GuiAuctionNavButton.java      ✅

network/packets/player/
  AuctionDataPacket.java        ✅
  AuctionActionPacket.java      ✅

Files Modified

CustomNpcs.java              ✅ Initialize AuctionController, save on shutdown
EnumRoleType.java            ✅ Added Auctioneer
EnumGuiType.java             ✅ Added PlayerAuction, PlayerAuctionSell, PlayerAuctionTrades, PlayerAuctionBidding
EnumPlayerPacket.java        ✅ Added AuctionData, AuctionAction
CommonProxy.java             ✅ Handle auction container types
ClientProxy.java             ✅ Handle auction GUI types
DataAdvanced.java            ✅ Handle Auctioneer role
ConfigMarket.java            ✅ Added Auction section
LoginPacket.java             ✅ Sync auction config to client
en_US.lang                   ✅ Added auction lang keys

6. Configuration

ConfigMarket.java Structure

// =========================================
// Currency (Market.Currency)
// =========================================
public static boolean UseVault = false;          // Use Vault economy
public static String CurrencyName = "Coins";     // Display name
public static long StartingBalance = 0;          // New player balance
public static long MaxBalance = Long.MAX_VALUE;  // Balance cap

// =========================================
// Auction (Market.Auction)
// =========================================
public static boolean AuctionEnabled = true;
public static int AuctionDurationHours = 48;     // Auction length
public static long ListingFee = 10;              // Fee to create listing
public static double SalesTaxPercent = 0.05;     // 5% tax on sales
public static int DefaultMaxListings = 10;       // Per player
public static int SnipeProtectionMinutes = 2;    // Anti-snipe timer
public static int ClaimExpirationDays = 30;      // Days before unclaimed deleted
public static double MinBidIncrementPercent = 0.05; // 5% minimum bid increase

// =========================================
// Auction Logging
// =========================================
public static boolean AuctionLoggingEnabled = true;
public static boolean LogAuctionCreated = true;
public static boolean LogAuctionBid = true;
public static boolean LogAuctionBuyout = true;
public static boolean LogAuctionSold = true;
public static boolean LogAuctionExpired = true;
public static boolean LogAuctionCancelled = true;
public static boolean LogAuctionClaimed = true;

7. Implementation Status

Phase 1: Currency System - COMPLETE ✅

Phase 2: Trader Enhancements - COMPLETE ✅

Phase 3: Auction Core - COMPLETE ✅

Phase 4: Auction GUI - COMPLETE ✅

Phase 5: Auction Network - COMPLETE ✅

Phase 6: Performance & Safety - COMPLETE ✅

  1. Threading model with ReentrantReadWriteLock
  2. Player indices for O(1) lookups
  3. 20-second update cycle
  4. Async saves on CNPC+ thread
  5. Race condition prevention
  6. Server shutdown handling
  7. Own listing view (buttons hidden)
  8. Server-side security checks

Remaining Work

  • GuiManageAuction (Admin GUI)
  • Permission system integration
  • Additional testing

8. Design Decisions

Decision Choice Rationale
Claims System Everything to claims Prevents offline handling issues
Vault Integration Via PlayerCurrencyData Single point of delegation, reused by Trader & Auction
Update Interval 20 seconds Performance vs responsiveness tradeoff
Player Indices ConcurrentHashMap + Sets O(1) lookups, thread-safe
Async Saves CNPC+ Thread Doesn't block server tick
Config Sync LoginPacket → AuctionClientConfig Client never accesses server config directly

9. Future Considerations (Not in 1.11)

  • Category-based filtering
  • Advanced blacklist system (items, mods, NBT patterns)
  • Auction history/statistics
  • Command-based auction access
  • Auction house tax sink
  • Reserve prices
  • Private auctions