Integrate shared planetary inventories and account sales with the current site

Merge the supplied inventory/exchange package into the latest DuneRealms source.
Keep community-reward receipts, verified UUID linking, native menus and current
website artwork, Dutch naming and account controls. Wire the inventory/sales
adapters into the real CP session and verified-link schema, with isolated reads
and honest unconfigured states. Preserve lobby/ender separation and Core-owned
atomic exchange checkpoints.

Validation: website build and 56 tests; 12 inventory/market adapter tests;
Core/Essentials and NPC/Terrain/Lobby builds and tests; local browser inspection
of the themed inventory, mannequin and History of sales with fictional fixtures.
Paper 1.21.8 source only: live 1.21.4 binaries and databases are unchanged.
This commit is contained in:
unimatrixgit 2026-10-27 19:44:22 +01:00
commit 9dcd9b084a
298 changed files with 3246 additions and 978 deletions

View file

@ -19,12 +19,14 @@ jobs:
uses: actions/setup-node@v4
with:
node-version: '22'
- name: Build the illustrated website and API
run: node scripts/build.mjs
- name: Install website server dependencies
run: npm install --omit=dev --no-audit --no-fund
- name: Build the illustrated website and API
run: node scripts/build.mjs
- name: Test feeds and compiled pages
run: node --test tests/*.test.mjs
- name: Test inventory ownership and private market bridge
run: node --test ../control-panel-inventory/tests/*.test.mjs
- name: Upload website build
uses: actions/upload-artifact@v4
with:

4
.gitignore vendored
View file

@ -10,3 +10,7 @@ __pycache__/
/built-crossplay/
/DuneRealms-Velocity-Network/
/DuneRealms-Velocity-Network.zip
# Private database credentials and manual profile recovery snapshots
/network/database/.env
**/inventory-recovery/

View file

@ -1,32 +1,30 @@
# CHOAM exchange — DuneEss 1.0.2
# CHOAM exchange — DuneEss 1.0.4
Install `DuneEss-1.0.2.jar` with Vault and the existing DuneCore/DuneTerrain/DuneNPC suite on Paper 1.21.4 / Java 21. Replace the previous DuneEss JAR while the server is stopped. Existing wallet and listing tables are retained; startup adds nullable item-payload and display-name columns to the listing table.
Install matching DuneRealms-Core.jar (1.0.12) and DuneRealms-Essentials.jar (1.0.4), with Vault and existing modules on Java 21 / Paper 1.21.8. Stop all planetary servers, back up SQL/player data, replace only these plugin JARs and configure the shared PostgreSQL database on every backend before starting. Preserve all worlds/configurations. See [database setup](../network/database/README.md).
## Player controls
- `/exchange` (also `/choam` or `/market`): faction-themed standard inventory menu. Actual DuneCore faction selection controls its appearance, including Ordos and unaffiliated Guild styling. Uses vanilla inventory slots; no Java-only client UI is required.
- `/exchange sell <amount> <price-each>`: reserve 1–64 held items, priced per item, maximum 1,000,000 Solaris with two decimal places. You cannot offer more than the held stack. Item names, enchantments, Dune tags and other serialized item data are preserved. Operator admin rods cannot be sold.
- `/exchange buy <id>`: review a listing, then confirm purchase of **one** item. The inventory GUI uses the same confirmation. Self-purchases are refused.
- `/exchange mine`: view your offers; select one to confirm cancellation and reclaim all unsold items. Only the seller can cancel. Your offers span all planets regardless of the browsing filter.
- `/exchange cancel <id>`: open the reclaim confirmation directly.
- `/exchange admin`: permission `dune.admin`, with all-planet listing inspection and a real connection check. Normal ownership rules still apply.
- `/exchange` (`/choam`, `/market`): native Java/Bedrock exchange menu.
- `/exchange sell <amount> <price-each>`: list 1–64 held items, up to 1,000,000 Solari per item, two decimal places. Items are escrowed with names, enchantments, Dune metadata and item data. Administrative items are rejected.
- `/exchange buy <id>`: inspect and confirm the purchase of one item.
- `/exchange mine`: browse your listings and reclaim unsold stock.
- `/exchange cancel <id>`: confirm cancellation of your own listing.
- `/exchange admin`: operator inspection and database check. Ownership rules still apply.
Category filters, all-items browsing, planet filters and pagination work together. The GUI identifies its own inventories through holders, cancels item transfers and drags, and prevents queued duplicate confirmations after a screen changes.
Filters, pagination, capacity checks, stale-confirmation handling and self-purchase rejection remain supported. Missing/incompatible shared Core profiles refuse to trade; lobby inventories never enter the planetary exchange.
## Shared database
## Transactions and history
Enable PostgreSQL in `plugins/DuneCore/config.yml`, using the same database on every backend. Leave `database.use-core-database: true` in DuneEss. DuneEss first initializes the existing shared `dune_economy_balances` ledger, then initializes the exchange. Restart after configuration changes. The exchange refuses to trade against fallback local wallets or an unavailable shared economy. Menu/guide access still works when unconnected, and no demo items are sold in-game.
Every actual player trade runs through Core's owned profile connection. Listing escrow, buyer debit, seller credit, stock changes, the resulting authoritative player inventory checkpoint, and any completed sale history commit together. A normal SQL failure restores the in-memory inventory and rolls back all SQL. If the commit outcome is uncertain, the profile is quarantined and ordinary quit saving is suppressed until manual recovery. Excess item delivery aborts the transaction instead of dropping items into the world.
Payments, seller credit and stock changes share one SQL transaction with a locked listing row. Buying the final item deletes the row instead of attempting an invalid zero quantity. Insufficient funds, a missing seller wallet or another transaction failure rolls back the database changes. Legacy material-only listings remain readable. Unsold item payloads are stored in PostgreSQL.
The sales ledger `dune_exchange_sales` retains a row per completed unit purchase, including seller/buyer names and UUIDs, item/material, quantity, exact unit/total price, origin and timestamp. Cancelling or failing a trade creates no sale. Earlier sales cannot be reconstructed retroactively. Configured shared economy deposits/withdrawals now use atomic SQL arithmetic and do not fall back to stale local balances during SQL outages.
**Verification limits:** automated SQL tests use H2 in PostgreSQL compatibility mode, and GUI tests use mocked Paper events. A live PostgreSQL + Paper/Velocity/Geyser staging run has not been performed. Queries are bounded and have five-second query/connect/socket timeouts but currently run on the server thread. Bukkit inventory/player-file writes and SQL commits are separate operations: abrupt process loss between them is not an exactly-once transfer guarantee. Keep normal backups and test staging before opening a public multi-backend economy. This change does not alter the wider Core profile/transfer synchronization system.
General gameplay/container changes outside these exchange transactions still rely on autosaves and unclean-session recovery. This is not an exactly-once guarantee for every Minecraft/plugin interaction. Ender chests remain local. SQL remains synchronous with bounded timeouts; profile capacity and staging tests are documented in the database guide.
## Website
## Account page and website
The website uses 40 clearly labelled fictional offers while the game-market gateway is unavailable. Demo offers never display purchase commands. When the configured gateway returns a valid live response, it switches to read-only live listings automatically on page load or Refresh; a valid empty live response remains an empty live market.
[control-panel-inventory](../control-panel-inventory/README.md) contains the account-page armor mannequin, saved inventory and **History of sales**, plus authenticated read-only API handlers, a private market listings bridge, integration instructions and a self-contained demo preview. The CP source is not in MC, so live wiring/deployment is a handoff task. Purchases remain in-game. Existing public website demo offers remain labelled until its operator enables the supplied live bridge.
The current gateway expects an HTTPS read-only bridge in `EXCHANGE_LISTINGS_URL`, authenticated server-to-server with `EXCHANGE_READ_TOKEN`. These are runtime secrets, never browser code. No bridge or production database is provisioned by this change. The response is `{ "listings": [{ "id": 1, "material": "IRON_INGOT", "category": "ores", "origin": "giedi_prime", "seller": "Trader", "quantity": 16, "price": 90 }] }`. Category and planet IDs must match the website's documented filter IDs. The bridge reads `dune_exchange_listings`; the website never executes a purchase or writes to SQL.
## Validation
## Checks
Run `gradle build` in DuneEss and `npm run build` / `npm test` in website. SQL coverage includes the final item, partial purchases, insufficient funds, rollback after debit, concurrent buyers, ownership, filters/pagination and validation. GUI coverage includes holder isolation, bottom-inventory transfers, drags, stale duplicate confirmation and admin permission enforcement.
Run `gradle build` in Core and DuneEss and `node --test tests/*.test.mjs` in control-panel-inventory. Core tests use mocked JDBC/Paper and exchange SQL tests use H2 PostgreSQL compatibility mode, including concurrency, rollback, sales ledger and externally owned transactions. Live PostgreSQL/Paper/Velocity/Bedrock validation is pending.

View file

@ -1,6 +1,6 @@
plugins { java }
group = "com.example"
version = "1.0.3"
version = "1.0.4"
repositories {
mavenCentral()
maven("https://repo.papermc.io/repository/maven-public/")
@ -16,7 +16,7 @@ dependencies {
testImplementation("com.h2database:h2:2.3.232")
testImplementation("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT")
testImplementation("org.mockito:mockito-core:5.15.2")
testRuntimeOnly("com.github.MilkBowl:VaultAPI:1.7") { exclude(group = "org.bukkit", module = "bukkit") }
testImplementation("com.github.MilkBowl:VaultAPI:1.7") { exclude(group = "org.bukkit", module = "bukkit") }
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
tasks.jar {

View file

@ -0,0 +1,73 @@
package com.example.duneess;
import com.google.gson.*;
import org.bukkit.Bukkit;
import org.bukkit.command.*;
import org.bukkit.entity.Player;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.net.URI;
import java.net.http.*;
import java.time.Duration;
import java.util.*;
/** Authenticated website bridge; rewards are always credited by the UUID/month ledger. */
final class CommunityCodes implements CommandExecutor,TabCompleter {
private final DuneEss plugin;
private final HttpClient http=HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).followRedirects(HttpClient.Redirect.NEVER).build();
private final Set<UUID> busy=new HashSet<>();
private final Map<UUID,Long> cooldown=new HashMap<>();
private final String endpoint,secret;
private boolean syncing;
CommunityCodes(DuneEss plugin){
this.plugin=plugin;
File file=new File(plugin.getDataFolder(),"website-bridge.yml");if(!file.exists())plugin.saveResource("website-bridge.yml",false);
YamlConfiguration settings=YamlConfiguration.loadConfiguration(file);endpoint=settings.getString("origin","https://cp.dunerealms.com");secret=settings.getString("secret","");
for(String name:List.of("communitycode","linkwebsite")){PluginCommand command=Objects.requireNonNull(plugin.getCommand(name));command.setExecutor(this);command.setTabCompleter(this);}
Bukkit.getScheduler().runTaskTimer(plugin,this::syncReceipts,200L,1200L);
}
private JsonObject post(String path,JsonObject body) throws Exception {
if(secret.length()<32||!endpoint.equals("https://cp.dunerealms.com"))throw new IllegalStateException("Website bridge is not configured");
HttpRequest request=HttpRequest.newBuilder(URI.create(endpoint+path)).timeout(Duration.ofSeconds(10)).header("Authorization","Bearer "+secret).header("Content-Type","application/json").POST(HttpRequest.BodyPublishers.ofString(body.toString())).build();
HttpResponse<String> response=http.send(request,HttpResponse.BodyHandlers.ofString());
if(response.body().length()>16384)throw new IllegalStateException("Unexpected bridge response");
JsonObject data=JsonParser.parseString(response.body()).getAsJsonObject();
if(response.statusCode()!=200)throw new IllegalStateException(data.has("message")?data.get("message").getAsString():"Website unavailable");return data;
}
@Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args){
if(!(sender instanceof Player player)){sender.sendMessage(com.example.dunegui.PublicNames.text("Players only."));return true;}
boolean linking=command.getName().equals("linkwebsite");
if(args.length!=1){player.sendMessage(com.example.dunegui.PublicNames.text(linking?"Generate a private link command at https://cp.dunerealms.com":"Public community codes: https://www.dunerealms.com/donate.html | Personal codes: https://cp.dunerealms.com | /communitycode CODE"));return true;}
String code=linking?args[0].toLowerCase(Locale.ROOT):args[0].toUpperCase(Locale.ROOT);
if(!(linking?code.matches("[a-f0-9]{32}"):code.matches("[A-Z0-9-]{4,48}"))){player.sendMessage(com.example.dunegui.PublicNames.text("Invalid code format."));return true;}
UUID uuid=player.getUniqueId();long now=System.currentTimeMillis();cooldown.entrySet().removeIf(entry->now-entry.getValue()>60000);
if(busy.contains(uuid)||now-cooldown.getOrDefault(uuid,0L)<3000){player.sendMessage(com.example.dunegui.PublicNames.text("Please wait a few seconds before trying again."));return true;}
cooldown.put(uuid,now);busy.add(uuid);
JsonObject body=new JsonObject();body.addProperty("uuid",uuid.toString());body.addProperty("name",player.getName());body.addProperty("code",code);
player.sendMessage(com.example.dunegui.PublicNames.text(linking?"Verifying website link…":"Checking community reward…"));
Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{try{
JsonObject response=post(linking?"/api/game-link/consume":"/api/community/game/prepare",body);
Bukkit.getScheduler().runTask(plugin,()->{try{
if(linking){player.sendMessage(com.example.dunegui.PublicNames.text("Website account linked to your Minecraft UUID. Refresh the account panel."));return;}
if(response.has("delivered")&&response.get("delivered").getAsBoolean()){player.sendMessage("This Minecraft UUID has already received that month's reward.");return;}
String month=response.get("month").getAsString(),receipt=response.get("receipt").getAsString();int amount=response.get("amount").getAsInt();
boolean granted=((DuneEconomy)plugin.economy()).grantCommunity(uuid,month,amount,receipt);
player.sendMessage(com.example.dunegui.PublicNames.text(granted?"Community reward credited: "+amount+" Dunemarks. Thank you, everyone!":"This UUID has already claimed that month's reward. No duplicate currency credited."));
syncReceipts();
}catch(Exception error){plugin.getLogger().warning("Community reward could not be committed: "+error.getClass().getSimpleName());player.sendMessage(com.example.dunegui.PublicNames.text("The reward could not be confirmed. Your code remains available; try again later."));}finally{busy.remove(uuid);}});
}catch(Exception error){Bukkit.getScheduler().runTask(plugin,()->{busy.remove(uuid);player.sendMessage(com.example.dunegui.PublicNames.text("Website request failed. Check the account panel or public code page and try again later."));});}});
return true;
}
private void syncReceipts(){
if(syncing||secret.length()<32)return;
Map<UUID,List<String>> pending;try{pending=((DuneEconomy)plugin.economy()).pendingCommunityReceipts();}catch(Exception error){return;}
if(pending.isEmpty())return;syncing=true;
Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{List<Map.Entry<UUID,String>> confirmed=new ArrayList<>();
try{for(var player:pending.entrySet())for(String receipt:player.getValue()){
JsonObject body=new JsonObject();body.addProperty("uuid",player.getKey().toString());body.addProperty("receipt",receipt);
try{post("/api/community/game/ack",body);confirmed.add(Map.entry(player.getKey(),receipt));}catch(Exception unavailable){return;}
}}finally{Bukkit.getScheduler().runTask(plugin,()->{try{for(var row:confirmed)((DuneEconomy)plugin.economy()).acknowledgeCommunity(row.getKey(),row.getValue());}catch(Exception error){plugin.getLogger().warning("Community receipts will retry on the next sync.");}finally{syncing=false;}});}
});
}
@Override public List<String> onTabComplete(CommandSender sender,Command command,String alias,String[] args){return List.of();}
}

View file

@ -33,14 +33,17 @@ final class DuneEconomy implements Economy {
private final String singular, plural;
private String jdbcUrl = "", dbUser = "", dbPassword = "";
private boolean databaseEnabled;
private boolean sharedDatabaseRequested;
DuneEconomy(DuneEss plugin) {
this.plugin = plugin;
this.file = new File(plugin.getDataFolder(), "balances.yml");
this.data = YamlConfiguration.loadConfiguration(file);
this.allowNegative = plugin.getConfig().getBoolean("currency.allow-negative-balances", true);
this.singular = plugin.getConfig().getString("currency.singular", "Solaris");
this.plural = plugin.getConfig().getString("currency.plural", "Solaris");
String configuredSingular = plugin.getConfig().getString("currency.singular", "Dunemark");
this.singular = configuredSingular.equalsIgnoreCase("Solaris") ? "Dunemark" : configuredSingular;
String configuredPlural = plugin.getConfig().getString("currency.plural", "Dunemarks");
this.plural = configuredPlural.equalsIgnoreCase("Solaris") ? "Dunemarks" : configuredPlural;
loadDatabaseSettings();
loadBalances();
}
@ -51,6 +54,7 @@ final class DuneEconomy implements Economy {
if (!coreConfig.isFile()) return;
YamlConfiguration core = YamlConfiguration.loadConfiguration(coreConfig);
if (!core.getBoolean("database.enabled", false)) return;
sharedDatabaseRequested = true;
jdbcUrl = core.getString("database.jdbc-url", "");
dbUser = core.getString("database.username", "");
dbPassword = core.getString("database.password", "");
@ -60,7 +64,10 @@ final class DuneEconomy implements Economy {
boolean sharedDatabaseReady() { return databaseEnabled; }
private Connection connect() throws SQLException {
return DriverManager.getConnection(jdbcUrl, dbUser, dbPassword);
java.util.Properties settings=new java.util.Properties();
settings.setProperty("user",dbUser);settings.setProperty("password",dbPassword);
settings.setProperty("connectTimeout","5");settings.setProperty("socketTimeout","10");
return DriverManager.getConnection(jdbcUrl,settings);
}
private void loadBalances() {
@ -85,8 +92,7 @@ final class DuneEconomy implements Economy {
while (rows.next()) balances.put(rows.getObject(1, UUID.class), money(rows.getDouble(2)));
}
} catch (SQLException ex) {
databaseEnabled = false;
plugin.getLogger().severe("Could not open the shared Solaris database; using the migrated local ledger: " + ex.getMessage());
plugin.getLogger().severe("Shared Solaris database unavailable; network transactions remain disabled until it recovers: " + ex.getMessage());
}
}
saveLocal();
@ -144,8 +150,8 @@ final class DuneEconomy implements Economy {
private synchronized void saveLocal() {
for (Map.Entry<UUID, Double> entry : balances.entrySet()) data.set(entry.getKey().toString(), entry.getValue());
try { data.save(file); }
catch (IOException ex) { plugin.getLogger().severe("Could not save Solaris balances: " + ex.getMessage()); }
try { writeCommunitySnapshot(data); }
catch (Exception ex) { plugin.getLogger().severe("Could not save Solaris balances: " + ex.getMessage()); }
}
private synchronized double balance(UUID id) {
@ -160,6 +166,7 @@ final class DuneEconomy implements Economy {
}
}
} catch (SQLException ex) { plugin.getLogger().warning("Solaris balance read failed: " + ex.getMessage()); }
return 0; // Never authorize a network payment against stale local cache.
}
return balances.getOrDefault(id, 0.0);
}
@ -176,23 +183,104 @@ final class DuneEconomy implements Economy {
saveLocal();
}
synchronized void add(UUID id, double amount) { set(id, balance(id) + amount); }
synchronized void subtract(UUID id, double amount) { set(id, balance(id) - amount); }
synchronized void add(UUID id, double amount) { change(id, amount); }
synchronized void subtract(UUID id, double amount) { change(id, -amount); }
private synchronized EconomyResponse change(UUID id, double delta) {
if (!Double.isFinite(delta)) return response(0, 0, EconomyResponse.ResponseType.FAILURE, "Invalid amount.");
if (sharedDatabaseRequested && !databaseEnabled) return response(Math.abs(delta),0,EconomyResponse.ResponseType.FAILURE,"Shared economy is unavailable.");
if (!databaseEnabled) {
double next=money(balance(id)+delta);
if (!allowNegative && next<0) return response(Math.abs(delta),balance(id),EconomyResponse.ResponseType.FAILURE,"Insufficient funds.");
set(id,next); return response(Math.abs(delta),next,EconomyResponse.ResponseType.SUCCESS,null);
}
try (Connection c=connect()) {
c.setAutoCommit(false);
try {
try (PreparedStatement create=c.prepareStatement("INSERT INTO dune_economy_balances(uuid,balance) VALUES (?,0) ON CONFLICT(uuid) DO NOTHING")) {
create.setObject(1,id);create.executeUpdate();
}
double updated;
try (PreparedStatement q=c.prepareStatement("UPDATE dune_economy_balances SET balance=balance+? WHERE uuid=? AND (? OR balance+?>=0) RETURNING balance")) {
BigDecimal amount=BigDecimal.valueOf(money(delta));
q.setBigDecimal(1,amount);q.setObject(2,id);q.setBoolean(3,allowNegative);q.setBigDecimal(4,amount);
try (ResultSet row=q.executeQuery()) {
if (!row.next()) {c.rollback();return response(Math.abs(delta),0,EconomyResponse.ResponseType.FAILURE,"Insufficient funds.");}
updated=row.getDouble(1);
}
}
c.commit();balances.put(id,updated);saveLocal();
return response(Math.abs(delta),updated,EconomyResponse.ResponseType.SUCCESS,null);
} catch(SQLException ex) {c.rollback();throw ex;}
} catch(SQLException ex) {
plugin.getLogger().warning("Shared Solaris transaction failed: "+ex.getSQLState());
return response(Math.abs(delta),0,EconomyResponse.ResponseType.FAILURE,"Shared economy is unavailable.");
}
}
/** One durable credit per UUID/month. A failed shared ledger never falls back to a second ledger. */
synchronized boolean grantCommunity(UUID id,String month,int amount,String receipt) throws Exception {
if(!month.matches("20\\d\\d-(0[1-9]|1[0-2])")||amount<1||amount>10000||!receipt.matches("[a-f0-9]{64}"))throw new IllegalArgumentException("Invalid community grant");
if(sharedDatabaseRequested&&!databaseEnabled)throw new IOException("Shared economy is unavailable");
String key="community-claims."+id+"."+month;
if(databaseEnabled){
try(Connection c=connect()){
try(Statement s=c.createStatement()){s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_community_claims (uuid UUID NOT NULL, month VARCHAR(7) NOT NULL, receipt VARCHAR(64) NOT NULL, amount INTEGER NOT NULL, acked BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY(uuid,month))");}
c.setAutoCommit(false);
try{
int inserted;
try(PreparedStatement s=c.prepareStatement("INSERT INTO dune_community_claims(uuid,month,receipt,amount) VALUES(?,?,?,?) ON CONFLICT(uuid,month) DO NOTHING")){s.setObject(1,id);s.setString(2,month);s.setString(3,receipt);s.setInt(4,amount);inserted=s.executeUpdate();}
if(inserted==0){try(PreparedStatement s=c.prepareStatement("SELECT receipt,amount FROM dune_community_claims WHERE uuid=? AND month=?")){s.setObject(1,id);s.setString(2,month);try(ResultSet r=s.executeQuery()){if(!r.next()||!receipt.equals(r.getString(1))||amount!=r.getInt(2))throw new IOException("Community receipt mismatch");}}c.commit();return false;}
double updated;
try(PreparedStatement s=c.prepareStatement("INSERT INTO dune_economy_balances(uuid,balance) VALUES(?,?) ON CONFLICT(uuid) DO UPDATE SET balance=dune_economy_balances.balance+EXCLUDED.balance RETURNING balance")){s.setObject(1,id);s.setBigDecimal(2,BigDecimal.valueOf(amount));try(ResultSet r=s.executeQuery()){r.next();updated=r.getDouble(1);}}
c.commit();balances.put(id,money(updated));saveLocal();return true;
}catch(Exception error){c.rollback();throw error;}
}
}
if(data.contains(key+".receipt")){if(!receipt.equals(data.getString(key+".receipt"))||amount!=data.getInt(key+".amount"))throw new IOException("Community receipt mismatch");return false;}
YamlConfiguration next=new YamlConfiguration();next.loadFromString(data.saveToString());
double updated=money(balances.getOrDefault(id,0.0)+amount);
next.set(id.toString(),updated);next.set(key+".receipt",receipt);next.set(key+".amount",amount);next.set(key+".acked",false);
writeCommunitySnapshot(next);balances.put(id,updated);return true;
}
private void writeCommunitySnapshot(YamlConfiguration next) throws Exception {
java.nio.file.Path target=file.toPath(),temporary=target.resolveSibling("balances.yml.community-tmp");
java.nio.file.Files.createDirectories(target.getParent());
byte[] bytes=next.saveToString().getBytes(java.nio.charset.StandardCharsets.UTF_8);
try(java.nio.channels.FileChannel channel=java.nio.channels.FileChannel.open(temporary,java.nio.file.StandardOpenOption.CREATE,java.nio.file.StandardOpenOption.TRUNCATE_EXISTING,java.nio.file.StandardOpenOption.WRITE)){java.nio.ByteBuffer buffer=java.nio.ByteBuffer.wrap(bytes);while(buffer.hasRemaining())channel.write(buffer);channel.force(true);}
java.nio.file.Files.move(temporary,target,java.nio.file.StandardCopyOption.ATOMIC_MOVE,java.nio.file.StandardCopyOption.REPLACE_EXISTING);
data.loadFromString(next.saveToString());
}
synchronized Map<UUID,List<String>> pendingCommunityReceipts() throws Exception {
Map<UUID,List<String>> pending=new HashMap<>();
if(sharedDatabaseRequested&&!databaseEnabled)return pending;
if(databaseEnabled){try(Connection c=connect();Statement s=c.createStatement()){
s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_community_claims (uuid UUID NOT NULL, month VARCHAR(7) NOT NULL, receipt VARCHAR(64) NOT NULL, amount INTEGER NOT NULL, acked BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY(uuid,month))");
try(ResultSet r=s.executeQuery("SELECT uuid,receipt FROM dune_community_claims WHERE acked=FALSE LIMIT 100")){while(r.next())pending.computeIfAbsent(r.getObject(1,UUID.class),ignored->new ArrayList<>()).add(r.getString(2));}
}return pending;}
var section=data.getConfigurationSection("community-claims");if(section==null)return pending;
for(String uuid:section.getKeys(false)){var months=section.getConfigurationSection(uuid);if(months==null)continue;for(String month:months.getKeys(false)){String key=uuid+"."+month;if(!section.getBoolean(key+".acked"))pending.computeIfAbsent(UUID.fromString(uuid),ignored->new ArrayList<>()).add(section.getString(key+".receipt"));}}
return pending;
}
synchronized void acknowledgeCommunity(UUID id,String receipt) throws Exception {
if(databaseEnabled){try(Connection c=connect();PreparedStatement s=c.prepareStatement("UPDATE dune_community_claims SET acked=TRUE WHERE uuid=? AND receipt=?")){s.setObject(1,id);s.setString(2,receipt);s.executeUpdate();}return;}
YamlConfiguration next=new YamlConfiguration();next.loadFromString(data.saveToString());var months=next.getConfigurationSection("community-claims."+id);if(months==null)return;
for(String month:months.getKeys(false))if(receipt.equals(months.getString(month+".receipt")))months.set(month+".acked",true);
writeCommunitySnapshot(next);
}
private EconomyResponse response(double amount, double balance, EconomyResponse.ResponseType type, String message) {
return new EconomyResponse(amount, balance, type, message);
}
private EconomyResponse deposit(OfflinePlayer player, double amount) {
if (amount < 0 || !Double.isFinite(amount)) return response(amount, getBalance(player), EconomyResponse.ResponseType.FAILURE, "Amount must be non-negative.");
set(player.getUniqueId(), getBalance(player) + amount);
return response(amount, getBalance(player), EconomyResponse.ResponseType.SUCCESS, null);
return change(player.getUniqueId(), amount);
}
private EconomyResponse withdraw(OfflinePlayer player, double amount) {
double current = getBalance(player);
if (amount < 0 || !Double.isFinite(amount)) return response(amount, current, EconomyResponse.ResponseType.FAILURE, "Amount must be non-negative.");
if (!allowNegative && current < amount) return response(amount, current, EconomyResponse.ResponseType.FAILURE, "Insufficient funds.");
set(player.getUniqueId(), current - amount);
return response(amount, getBalance(player), EconomyResponse.ResponseType.SUCCESS, null);
return change(player.getUniqueId(), -amount);
}
@Override public boolean isEnabled() { return plugin.isEnabled(); }
@ -237,6 +325,11 @@ final class DuneEconomy implements Economy {
@Override public boolean createPlayerAccount(String name) { return createPlayerAccount(Bukkit.getOfflinePlayer(name)); }
@Override public boolean createPlayerAccount(OfflinePlayer player) {
UUID id = player.getUniqueId();
if (databaseEnabled) {
try (Connection c=connect();PreparedStatement q=c.prepareStatement("INSERT INTO dune_economy_balances(uuid,balance) VALUES (?,?) ON CONFLICT(uuid) DO NOTHING")) {
q.setObject(1,id);q.setBigDecimal(2,BigDecimal.valueOf(money(plugin.getConfig().getDouble("currency.starting-balance",0))));q.executeUpdate();return true;
} catch(SQLException ex) {return false;}
}
if (!balances.containsKey(id)) set(id, money(plugin.getConfig().getDouble("currency.starting-balance", 0)));
return true;
}

View file

@ -32,6 +32,7 @@ import java.util.*;
public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCompleter, Listener {
private static final List<String> PLANETS = List.of("arrakis", "giedi_prime", "kaitain", "caladan", "sigma_draconis_iv", "spacing_guild");
private DuneEconomy economy;
String balanceLabel(Player player) { return economy.format(economy.getBalance(player)); }
private ExchangeMenu exchangeMenu;
private EssentialsBasics basics;
private String jdbcUrl = "", dbUser = "", dbPassword = "";
@ -43,28 +44,28 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom
private static final String HELP_TITLE = ChatColor.DARK_RED + "Dune Field Guide";
private static final List<List<HelpEntry>> HELP_PAGES = List.of(
List.of(
new HelpEntry("/duneess balance", "Check your Solaris wallet.", Material.GOLD_INGOT),
new HelpEntry("/duneess balance", "Check your Dunemarks wallet.", Material.GOLD_INGOT),
new HelpEntry("/duneess sell", "Sell all tagged spice in your inventory.", Material.ORANGE_DYE),
new HelpEntry("/duneess travel", "Open the Spacing Guild planet selector.", Material.ENDER_PEARL),
new HelpEntry("/duneess travel", "Open the Vaerkring planet selector.", Material.ENDER_PEARL),
new HelpEntry("/duneess travel arrakis", "Pay the fare and travel to Arrakis.", Material.MAP),
new HelpEntry("/dune", "Open the Dune Navigator menu.", Material.NETHER_STAR)
),
List.of(
new HelpEntry("/dune choose fremen", "Choose Fremen; replace 'fremen' with another house to choose it.", Material.WHITE_BANNER),
new HelpEntry("/dune choose fremen", "Choose Vrijduin; replace 'fremen' with another house to choose it.", Material.WHITE_BANNER),
new HelpEntry("/dune kit", "Receive your faction stillsuit and spice shovel.", Material.NETHERITE_SHOVEL),
new HelpEntry("/dune elytra", "Upgrade a worn stillsuit chestplate with an Elytra.", Material.ELYTRA),
new HelpEntry("/dune politics status", "View the Spacing Trust, leaders, and imperial appointments.", Material.WRITABLE_BOOK),
new HelpEntry("/dune politics status", "View the Vaerkring Trust, leaders, and Landsraad appointments.", Material.WRITABLE_BOOK),
new HelpEntry("/dune water status", "View your Arrakis water-trading career.", Material.WATER_BUCKET)
),
List.of(
new HelpEntry("/dune serverjobs", "Browse hourly CHOAM spice contracts.", Material.EMERALD),
new HelpEntry("/dune serverjobs", "Browse hourly Koopkring spice contracts.", Material.EMERALD),
new HelpEntry("/dune job", "Browse player-posted spice contracts.", Material.BOOK),
new HelpEntry("/dune job post 100", "Post a 100-spice contract; change the amount to suit your listing.", Material.PAPER),
new HelpEntry("/dune water sell", "Sell water collected on Arrakis.", Material.BUCKET),
new HelpEntry("/dune exchange", "Open the spice exchange menu.", Material.CHEST)
),
List.of(
new HelpEntry("/duneess admin solari player amount", "Grant Solaris to an online player.", Material.GOLD_INGOT),
new HelpEntry("/duneess admin solari player amount", "Grant Dunemarks to an online player.", Material.GOLD_INGOT),
new HelpEntry("/duneess admin teleport arrakis", "Force yourself to Arrakis spawn.", Material.COMPASS),
new HelpEntry("/duneess admin teleport sietch", "Teleport yourself to a generated sietch.", Material.CHEST),
new HelpEntry("/duneess admin teleport spiceblow", "Teleport yourself to a generated spice blow.", Material.MAGMA_BLOCK),
@ -82,6 +83,7 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom
helpPageKey = new NamespacedKey(this, "help_page");
helpActionKey = new NamespacedKey(this, "help_action");
economy = new DuneEconomy(this);
new CommunityCodes(this);
getServer().getServicesManager().register(Economy.class, economy, this, ServicePriority.Highest);
getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
PluginCommand command = Objects.requireNonNull(getCommand("duneess"));
@ -93,7 +95,7 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom
exchangeMenu = new ExchangeMenu(this);
exchangeMenu.register();
for (Player player : Bukkit.getOnlinePlayers()) economy.createPlayerAccount(player);
getLogger().info("DuneRealms Essentials enabled as the Solaris Vault provider.");
getLogger().info("DuneRealms Essentials enabled as the Dunemarks Vault provider.");
}
@Override public void onDisable() {
@ -201,7 +203,7 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom
}
sender.sendMessage(ChatColor.DARK_RED + "+" + "-".repeat(58) + "+");
sendBoxLine(sender, ChatColor.GRAY + "Use /duneess help menu for the visual guide.");
sendBoxLine(sender, ChatColor.GRAY + "DuneEss: Solaris and Guild travel");
sendBoxLine(sender, ChatColor.GRAY + "DuneEss: Dunemarks and Vaerkring travel");
sendBoxLine(sender, ChatColor.GRAY + "DuneCore: factions and Arrakis");
sender.sendMessage(ChatColor.DARK_RED + "+" + "-".repeat(58) + "+");
if (sender instanceof Player player) {
@ -341,7 +343,7 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom
ItemStack spice=new ItemStack(Material.ORANGE_DYE,quantity);ItemMeta sm=spice.getItemMeta();
sm.setDisplayName(ChatColor.GOLD+"Melange Spice");sm.getPersistentDataContainer().set(spiceKey,PersistentDataType.STRING,"spice");spice.setItemMeta(sm);
if(player.getInventory().firstEmpty()<0){player.sendMessage("Make an empty inventory slot first.");return;}
if(!economy.withdrawPlayer(player,price).transactionSuccess()){player.sendMessage("Not enough Solaris, or economy unavailable.");return;}
if(!economy.withdrawPlayer(player,price).transactionSuccess()){player.sendMessage("Not enough Dunemarks, or economy unavailable.");return;}
player.getInventory().addItem(spice);player.sendMessage(ChatColor.GOLD+"Bought 16 spice for "+economy.format(price)+".");
});
com.example.dunegui.NativeMenus.inventory(this,player,"Spice Seller · +35%",menu,actions);
@ -377,23 +379,23 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom
}
private void openTravelMenu(Player player) {
Inventory inventory = Bukkit.createInventory(null, 9, ChatColor.DARK_AQUA + "Spacing Guild Travel");
Inventory inventory = Bukkit.createInventory(null, 9, ChatColor.DARK_AQUA + "Vaerkring Travel");
for (int i = 0; i < PLANETS.size(); i++) {
String planet = PLANETS.get(i);
ItemStack item = new ItemStack(Material.ENDER_PEARL);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(ChatColor.GOLD + planet + " — " + getConfig().getInt("currency.travel-price", 100) + " Solaris");
meta.setDisplayName(ChatColor.GOLD + com.example.dunegui.PlanetSigils.label(planet) + " — " + getConfig().getInt("currency.travel-price", 100) + " Dunemarks");
meta.getPersistentDataContainer().set(new NamespacedKey(this, "planet"), PersistentDataType.STRING, planet);
item.setItemMeta(meta);
inventory.setItem(i, item);
inventory.setItem(i, com.example.dunegui.PlanetSigils.apply(item,planet));
}
java.util.Map<Integer,Runnable> actions=new java.util.HashMap<>();
for(int i=0;i<PLANETS.size();i++) { String planet=PLANETS.get(i); actions.put(i,()->travel(player,planet)); }
com.example.dunegui.NativeMenus.inventory(this,player,"Spacing Guild Travel",inventory,actions);
com.example.dunegui.NativeMenus.inventory(this,player,"Vaerkring Travel",inventory,actions);
}
@EventHandler public void onTravelMenuClick(InventoryClickEvent event) {
if (!(event.getWhoClicked() instanceof Player player) || !event.getView().getTitle().equals(ChatColor.DARK_AQUA + "Spacing Guild Travel")) return;
if (!(event.getWhoClicked() instanceof Player player) || !event.getView().getTitle().equals(ChatColor.DARK_AQUA + "Vaerkring Travel")) return;
event.setCancelled(true);
ItemStack item = event.getCurrentItem();
if (item == null || !item.hasItemMeta()) return;
@ -415,7 +417,7 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom
}
if (server.isBlank()) { player.sendMessage(ChatColor.RED + "The Guild server for " + planet + " is not configured."); return; }
int fare = travelFare(player, planet);
if (fare > 0 && !economy.has(player, fare)) { player.sendMessage(ChatColor.RED + "Not enough Solaris for the Guild fare."); return; }
if (fare > 0 && !economy.has(player, fare)) { player.sendMessage(ChatColor.RED + "Not enough Dunemarks for the Guild fare."); return; }
if (fare > 0) economy.withdrawPlayer(player, fare);
if (!sendToServer(player, server, planet) && fare > 0) economy.depositPlayer(player, fare);
return;
@ -423,13 +425,13 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom
World world = Bukkit.getWorld(planet);
if (world == null) { player.sendMessage(ChatColor.RED + "That planet is not loaded on this server."); return; }
int fare = travelFare(player, planet);
if (fare > 0 && !economy.has(player, fare)) { player.sendMessage(ChatColor.RED + "Not enough Solaris for the Guild fare."); return; }
if (fare > 0 && !economy.has(player, fare)) { player.sendMessage(ChatColor.RED + "Not enough Dunemarks for the Guild fare."); return; }
if (fare > 0) economy.withdrawPlayer(player, fare);
if (!player.teleport(world.getSpawnLocation())) {
if (fare > 0) economy.depositPlayer(player, fare);
player.sendMessage(ChatColor.RED + "Guild travel failed. Your fare was returned.");
player.sendMessage(ChatColor.RED + "Vaerkring travel failed. Your fare was returned.");
} else {
player.sendMessage(ChatColor.AQUA + "Spacing Guild arrival: " + planet);
player.sendMessage(ChatColor.AQUA + "Vaerkring arrival: " + planet);
if (planet.equals("arrakis")) callCoreArrakisArrival(player);
}
}
@ -440,7 +442,7 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom
DataOutputStream data = new DataOutputStream(bytes);
data.writeUTF("Connect"); data.writeUTF(server);
player.sendPluginMessage(this, "BungeeCord", bytes.toByteArray());
player.sendMessage(ChatColor.AQUA + "Spacing Guild transfer requested: " + planet);
player.sendMessage(ChatColor.AQUA + "Vaerkring transfer requested: " + planet);
return true;
} catch (Exception ex) {
player.sendMessage(ChatColor.RED + "Guild transfer failed. Your fare was returned.");
@ -488,7 +490,7 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom
economy.depositPlayer(target, amount);
sender.sendMessage(ChatColor.GREEN + "Added " + economy.format(amount) + " to " + target.getName() + ".");
target.sendMessage(ChatColor.GOLD + "An admin added " + economy.format(amount) + " to your balance.");
} catch (NumberFormatException ex) { sender.sendMessage(ChatColor.RED + "Enter a positive Solaris amount."); }
} catch (NumberFormatException ex) { sender.sendMessage(ChatColor.RED + "Enter a positive Dunemarks amount."); }
return true;
}
if (args[1].equalsIgnoreCase("spicebloom")) {

View file

@ -64,7 +64,7 @@ final class EssentialsBasics implements CommandExecutor, TabCompleter, Listener
choices.add(new NativeMenus.Choice("Spawn","Return to this world's spawn.",()->p.performCommand("spawn")));
choices.add(new NativeMenus.Choice("Guild servers","Travel using existing Solaris fares and permissions.",()->p.performCommand("duneess travel")));
choices.add(new NativeMenus.Choice("Solaris","Show your balance.",()->p.performCommand("duneess balance")));
choices.add(new NativeMenus.Choice("CHOAM Exchange","Buy, list and reclaim items.",()->p.performCommand("exchange")));
choices.add(new NativeMenus.Choice("Koopkring Exchange","Buy, list and reclaim items.",()->p.performCommand("exchange")));
choices.add(new NativeMenus.Choice("Help","Open the Dune Field Guide.",()->p.performCommand("duneess help menu")));
NativeMenus.show(plugin,p,"DuneRealms Essentials","Solaris: "+plugin.economy().format(plugin.economy().getBalance(p)),choices);
}
@ -98,7 +98,7 @@ final class EssentialsBasics implements CommandExecutor, TabCompleter, Listener
if(args.length!=1) throw new IllegalArgumentException("Usage: /tpa <online player>");
Player target=Bukkit.getPlayerExact(args[0]);
if(target==null || target.equals(p) || !p.canSee(target)) throw new IllegalArgumentException("Choose another online player on this server.");
if(!target.getWorld().equals(p.getWorld())) throw new IllegalArgumentException("Use Guild travel to reach that player's world first.");
if(!target.getWorld().equals(p.getWorld())) throw new IllegalArgumentException("Use Vaerkring travel to reach that player's world first.");
requests.put(target.getUniqueId(),new Request(p.getUniqueId(),System.nanoTime()+60_000_000_000L));
target.sendMessage(p.getName()+" requests to teleport to you. /tpaccept or /tpdeny (60 seconds).");
p.sendMessage("Teleport request sent.");

View file

@ -41,12 +41,12 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter {
command.setExecutor(this); command.setTabCompleter(this);
Bukkit.getPluginManager().registerEvents(this,plugin);
try { store.initialize(); ready=true; }
catch(SQLException ex) { plugin.getLogger().warning("CHOAM is offline until the shared PostgreSQL economy is connected."); }
catch(SQLException ex) { plugin.getLogger().warning("Koopkring is offline until the shared PostgreSQL economy is connected."); }
}
private boolean connected(Player p) {
// Retry after a transient startup outage; never trade against a fallback local wallet.
if(!ready) try { store.initialize(); ready=true; } catch(SQLException ignored) { }
if(!ready) p.sendMessage(ChatColor.YELLOW+"CHOAM is not connected. Ask an operator to configure DuneCore PostgreSQL and restart DuneEss. No items or Solaris were taken.");
if(!ready) p.sendMessage(ChatColor.YELLOW+"Koopkring is not connected. Ask an operator to configure DuneCore PostgreSQL and restart DuneEss. No items or Dunemarks were taken.");
return ready;
}
private String faction(Player p) {
@ -55,7 +55,7 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter {
String house=String.valueOf(core.getClass().getMethod("factionOf",Player.class).invoke(core,p));
if(List.of("Fremen","Atreides","Harkonnen","Corrino","Ordos").contains(house)) return house;
} catch(ReflectiveOperationException ignored) { }
return "Spacing Guild";
return "Vaerkring";
}
private ChatColor tint(Player p) {
return switch(faction(p)) {
@ -73,8 +73,8 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter {
}
private Screen screen(Player p,String title) {
Screen s=new Screen(p.getUniqueId());
s.title="CHOAM | "+title;
s.inventory=Bukkit.createInventory(s,54,tint(p)+"CHOAM | "+title);
s.title="Koopkring | "+title;
s.inventory=Bukkit.createInventory(s,54,tint(p)+"Koopkring | "+title);
Material glass=switch(faction(p)) {
case "Atreides" -> Material.CYAN_STAINED_GLASS_PANE;
case "Harkonnen" -> Material.RED_STAINED_GLASS_PANE;
@ -85,6 +85,7 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter {
};
for(int i=0;i<54;i++) if(i<9||i>=45||i%9==0||i%9==8)
s.inventory.setItem(i,icon(glass," "));
s.inventory.setItem(47,com.example.dunegui.DunemarkItems.icon(ChatColor.GOLD+"Dunemarks",List.of(ChatColor.GRAY+"Wallet: "+plugin.balanceLabel(p),ChatColor.GRAY+"Display icon only; balances stay in the ledger.")));
button(s,49,Material.BARRIER,"Back to Exchange",()->home(p)); return s;
}
private void button(Screen s,int slot,Material material,String title,Runnable action,String... lore) {
@ -96,7 +97,8 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter {
String category=CATEGORIES.get(i);
button(s,10+i,ICONS.get(i),category.toUpperCase(Locale.ROOT),()->browse(p,category,0,false,false));
}
button(s,29,Material.EMERALD,"Buy / All Items",()->browse(p,"all",0,false,false));
s.inventory.setItem(29,com.example.dunegui.DunemarkItems.icon(ChatColor.GOLD+"Buy / All Items",List.of(ChatColor.GRAY+"Pay with Dunemarks from your wallet.")));
s.actions.put(29,()->browse(p,"all",0,false,false));
button(s,31,Material.CHEST,"Sell Held Item",()->{
p.closeInventory(); p.sendMessage(ChatColor.YELLOW+"Hold the item to list, then /exchange sell <amount> <price-each>. Example: /exchange sell 16 25");
},"Tagged Dune items and their attributes are preserved.","Price is for ONE item.");
@ -123,7 +125,7 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter {
Screen s=screen(p,"Administration");
button(s,20,Material.BOOK,"All Listings",()->browse(p,"all",0,false,true),"All planets. Read-only inspection; normal ownership rules apply.");
button(s,24,Material.REDSTONE,"Check Database",()->{
if(connected(p)) p.sendMessage(ChatColor.GREEN+"Shared CHOAM database connected.");
if(connected(p)) p.sendMessage(ChatColor.GREEN+"Shared Koopkring database connected.");
});
com.example.dunegui.NativeMenus.inventory(plugin,p,s.title,s.inventory,s.actions);
}
@ -152,7 +154,7 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter {
try { item=decode(row); } catch(RuntimeException ex) { item=new ItemStack(Material.PAPER); }
ItemMeta meta=item.getItemMeta();
meta.setDisplayName(ChatColor.GOLD+"#"+row.id()+" "+(row.displayName()==null?row.material():row.displayName()));
meta.setLore(List.of("Quantity: "+row.quantity(),"Each: "+row.price()+" Solaris","Seller: "+row.sellerName(),"Planet: "+row.origin(),
meta.setLore(List.of("Quantity: "+row.quantity(),"Each: "+row.price()+" Dunemarks","Seller: "+row.sellerName(),"Planet: "+row.origin(),
row.seller().equals(p.getUniqueId())?"Click to reclaim unsold items":"Click to review purchase"));
item.setItemMeta(meta); s.inventory.setItem(slot,item);
s.actions.put(slot,()->confirm(p,row.id(),row.seller().equals(p.getUniqueId()))); slot++;
@ -169,7 +171,7 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter {
if(reclaim&&!row.seller().equals(p.getUniqueId())) throw new IllegalArgumentException("You can reclaim only your own listings.");
Screen s=screen(p,reclaim?"Reclaim Listing":"Confirm Purchase");
s.inventory.setItem(22,icon(decode(row).getType(),"#"+id+" "+(row.displayName()==null?row.material():row.displayName()),
"Seller: "+row.sellerName(),reclaim?"Return "+row.quantity()+" unsold items":"Buy ONE for "+row.price()+" Solaris"));
"Seller: "+row.sellerName(),reclaim?"Return "+row.quantity()+" unsold items":"Buy ONE for "+row.price()+" Dunemarks"));
button(s,30,Material.LIME_CONCRETE,reclaim?"Confirm Reclaim":"Confirm Purchase",()->{
p.closeInventory(); if(reclaim) cancel(p,id); else buy(p,id);
});
@ -189,8 +191,7 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter {
item.setAmount(amount);
Map<Integer,ItemStack> excess=p.getInventory().addItem(item);
// Capacity is checked immediately before the transaction on this same server thread.
for(ItemStack left:excess.values()) p.getWorld().dropItemNaturally(p.getLocation(),left);
p.saveData();
if (!excess.isEmpty()) throw new IllegalArgumentException("Inventory changed; the trade was rolled back. Make room and retry.");
}
private void sell(Player p,int amount,BigDecimal price) throws SQLException {
ExchangeStore.validate(amount,price);
@ -202,10 +203,13 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter {
ItemStack unit=held.clone(); unit.setAmount(1);
String name=unit.hasItemMeta()&&unit.getItemMeta().hasDisplayName()?ChatColor.stripColor(unit.getItemMeta().getDisplayName()):unit.getType().name();
if(name.length()>120) name=name.substring(0,120);
store.list(p.getUniqueId(),p.getName(),origin(p),category(unit),unit.getType().name(),amount,price,
Base64.getEncoder().encodeToString(unit.serializeAsBytes()),name);
held.setAmount(held.getAmount()-amount); p.saveData();
p.sendMessage(ChatColor.GREEN+"Listed "+amount+" "+name+" at "+price+" Solaris each.");
final String displayName=name;
atomic(p, scoped -> {
scoped.list(p.getUniqueId(),p.getName(),origin(p),category(unit),unit.getType().name(),amount,price,
Base64.getEncoder().encodeToString(unit.serializeAsBytes()),displayName);
held.setAmount(held.getAmount()-amount);
});
p.sendMessage(ChatColor.GREEN+"Listed "+amount+" "+name+" at "+price+" Dunemarks each.");
}
private String origin(Player p) {
String world=p.getWorld().getName().toLowerCase(Locale.ROOT).replace('-','_');
@ -228,8 +232,11 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter {
execute(p,()->{
ExchangeStore.Listing before=store.find(id); ItemStack item=decode(before);
if(!fits(p,item,1)) throw new IllegalArgumentException("Make room in your inventory first.");
ExchangeStore.Listing bought=store.buy(p.getUniqueId(),id);
deliver(p,item,1); p.sendMessage(ChatColor.GREEN+"Purchased one item for "+bought.price()+" Solaris.");
atomic(p, scoped -> {
scoped.buy(p.getUniqueId(),p.getName(),id);
deliver(p,item,1);
});
p.sendMessage(ChatColor.GREEN+"Purchased one item for "+before.price()+" Dunemarks.");
});
}
private void cancel(Player p,long id) {
@ -237,21 +244,42 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter {
execute(p,()->{
ExchangeStore.Listing before=store.find(id); ItemStack item=decode(before);
if(!fits(p,item,before.quantity())) throw new IllegalArgumentException("Make room for all "+before.quantity()+" items first.");
ExchangeStore.Listing cancelled=store.cancel(p.getUniqueId(),id);
deliver(p,item,cancelled.quantity()); p.sendMessage(ChatColor.GREEN+"Listing cancelled. Unsold items returned.");
atomic(p, scoped -> {
ExchangeStore.Listing cancelled=scoped.cancel(p.getUniqueId(),id);
deliver(p,item,cancelled.quantity());
});
p.sendMessage(ChatColor.GREEN+"Listing cancelled. Unsold items returned.");
});
}
private interface Trade { void run(ExchangeStore scoped) throws SQLException; }
private void atomic(Player p, Trade trade) throws SQLException {
Plugin core=Bukkit.getPluginManager().getPlugin("DuneCore");
if (core==null) throw new SQLException("DuneCore network profiles are required");
try {
java.util.function.Consumer<java.sql.Connection> work = connection -> {
try { trade.run(ExchangeStore.bound(connection)); }
catch (SQLException ex) { throw new java.util.concurrent.CompletionException(ex); }
};
core.getClass().getMethod("transactNetworkInventory",Player.class,java.util.function.Consumer.class).invoke(core,p,work);
} catch (ReflectiveOperationException ex) {
Throwable cause=ex instanceof java.lang.reflect.InvocationTargetException ? ex.getCause() : ex;
if (cause instanceof java.util.concurrent.CompletionException && cause.getCause()!=null) cause=cause.getCause();
if (cause instanceof IllegalArgumentException invalid) throw invalid;
if (cause instanceof SQLException sql) throw sql;
throw new SQLException("Network inventory transaction unavailable; install matching Core and Essentials",cause);
}
}
private interface Operation { void run() throws SQLException; }
private void execute(Player p,Operation action) {
try { action.run(); }
catch(IllegalArgumentException ex) { p.sendMessage(ChatColor.YELLOW+ex.getMessage()); }
catch(SQLException ex) {
ready=false; plugin.getLogger().warning("CHOAM SQL operation failed: "+ex.getSQLState());
ready=false; plugin.getLogger().warning("Koopkring SQL operation failed: "+ex.getSQLState());
p.sendMessage(ChatColor.RED+"The market database is unavailable. Please try again later.");
}
}
@Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args) {
if(!(sender instanceof Player p)) { sender.sendMessage("Open the CHOAM exchange in-game with /exchange."); return true; }
if(!(sender instanceof Player p)) { sender.sendMessage("Open the Koopkring exchange in-game with /exchange."); return true; }
if(args.length==0) { home(p); return true; }
String action=args[0].toLowerCase(Locale.ROOT);
if(action.equals("admin")) { if(p.hasPermission("dune.admin")) admin(p); else p.sendMessage(ChatColor.RED+"Operators only."); return true; }

View file

@ -11,12 +11,24 @@ final class ExchangeStore {
String material, int quantity, BigDecimal price, String payload, String displayName) {}
private final Connections connections;
ExchangeStore(Connections connections) { this.connections = connections; }
/** Reuse the Core profile transaction; only Core may commit, roll back or close it. */
static ExchangeStore bound(Connection connection) {
Connection scoped = (Connection) java.lang.reflect.Proxy.newProxyInstance(
ExchangeStore.class.getClassLoader(), new Class<?>[]{Connection.class}, (proxy, method, args) -> {
if (Set.of("close", "commit", "rollback", "setAutoCommit").contains(method.getName())) return null;
try { return method.invoke(connection, args); }
catch (java.lang.reflect.InvocationTargetException ex) { throw ex.getCause(); }
});
return new ExchangeStore(() -> scoped);
}
void initialize() throws SQLException {
try (Connection c = connections.open(); Statement s = c.createStatement()) {
s.setQueryTimeout(5);
s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_exchange_listings (id BIGSERIAL PRIMARY KEY, seller UUID NOT NULL, seller_name VARCHAR(32) NOT NULL, origin VARCHAR(48) NOT NULL, category VARCHAR(24) NOT NULL, material VARCHAR(80) NOT NULL, quantity INT NOT NULL CHECK(quantity>0), price NUMERIC(20,2) NOT NULL CHECK(price>0))");
s.executeUpdate("ALTER TABLE dune_exchange_listings ADD COLUMN IF NOT EXISTS payload TEXT");
s.executeUpdate("ALTER TABLE dune_exchange_listings ADD COLUMN IF NOT EXISTS display_name VARCHAR(120)");
s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_exchange_sales (id BIGSERIAL PRIMARY KEY, listing_id BIGINT NOT NULL, seller UUID NOT NULL, seller_name VARCHAR(32) NOT NULL, buyer UUID NOT NULL, buyer_name VARCHAR(32) NOT NULL, material VARCHAR(80) NOT NULL, display_name VARCHAR(120), quantity INTEGER NOT NULL CHECK(quantity>0), unit_price NUMERIC(20,2) NOT NULL CHECK(unit_price>0), total_price NUMERIC(20,2) NOT NULL CHECK(total_price>0), origin VARCHAR(48) NOT NULL, sold_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP)");
s.executeUpdate("CREATE INDEX IF NOT EXISTS dune_exchange_sales_seller_id ON dune_exchange_sales(seller,id DESC)");
}
}
private PreparedStatement prepare(Connection c, String sql) throws SQLException {
@ -68,7 +80,8 @@ final class ExchangeStore {
r.getBigDecimal("price"),r.getString("payload"),r.getString("display_name"));
}
/** On SQL failure, no wallet or listing changes survive. Never set quantity to zero under CHECK(quantity>0). */
Listing buy(UUID buyer, long id) throws SQLException {
Listing buy(UUID buyer, long id) throws SQLException { return buy(buyer, "Unknown", id); }
Listing buy(UUID buyer, String buyerName, long id) throws SQLException {
try(Connection c=connections.open()) {
c.setAutoCommit(false);
try(PreparedStatement q=prepare(c,"SELECT * FROM dune_exchange_listings WHERE id=? FOR UPDATE")) {
@ -85,6 +98,13 @@ final class ExchangeStore {
credit.setBigDecimal(1,offer.price()); credit.setObject(2,offer.seller());
if(credit.executeUpdate()!=1) throw new IllegalArgumentException("Seller wallet unavailable; no payment taken.");
stock.setLong(1,id); if(stock.executeUpdate()!=1) throw new SQLException("Listing changed.");
try (PreparedStatement sale = prepare(c, "INSERT INTO dune_exchange_sales(listing_id,seller,seller_name,buyer,buyer_name,material,display_name,quantity,unit_price,total_price,origin) VALUES(?,?,?,?,?,?,?,1,?,?,?)")) {
sale.setLong(1, id); sale.setObject(2, offer.seller()); sale.setString(3, offer.sellerName());
sale.setObject(4, buyer); sale.setString(5, buyerName);
sale.setString(6, offer.material()); sale.setString(7, offer.displayName());
sale.setBigDecimal(8, offer.price()); sale.setBigDecimal(9, offer.price()); sale.setString(10, offer.origin());
sale.executeUpdate();
}
c.commit(); return offer;
}
}

View file

@ -1,6 +1,6 @@
currency:
singular: Solaris
plural: Solaris
singular: Dunemark
plural: Dunemarks
spice-price: 15
travel-price: 100
starting-balance: 0

View file

@ -1,12 +1,18 @@
name: DuneEss
version: 1.0.3
version: 1.0.4
main: com.example.duneess.DuneEss
api-version: '1.21.8'
depend: [Vault]
softdepend: [floodgate, ViaVersion, DuneCore, DuneTerrain]
prefix: DuneRealms Essentials
description: DuneRealms Essentials - Dune Solaris economy, Vault provider, spice sales, and Arrakis travel
description: DuneRealms Essentials - Dunemarks economy, Vault provider, spice sales, and Arrakduin travel
commands:
communitycode:
description: Claim one community currency reward per UUID and monthly goal
usage: /communitycode <code>
linkwebsite:
description: Verify your Minecraft UUID for a website account
usage: /linkwebsite <private-code>
exchange:
description: CHOAM interplanetary player marketplace
usage: /exchange

View file

@ -0,0 +1,3 @@
origin: https://cp.dunerealms.com
# Operator secret shared with the account panel. Never publish or put it in command arguments.
secret: ''

View file

@ -0,0 +1,37 @@
package com.example.duneess;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.file.YamlConfiguration;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.*;
import java.util.*;
import java.util.logging.Logger;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
class CommunityLedgerTest {
@TempDir Path directory;
DuneEss plugin(){DuneEss plugin=mock(DuneEss.class);when(plugin.getDataFolder()).thenReturn(directory.resolve("DuneEss").toFile());when(plugin.getConfig()).thenReturn(new YamlConfiguration());when(plugin.getLogger()).thenReturn(Logger.getAnonymousLogger());return plugin;}
@Test void creditsOnceAcrossRestartAndRetainsReceiptUntilAcknowledged() throws Exception {
DuneEss plugin=plugin();UUID uuid=UUID.randomUUID();OfflinePlayer player=mock(OfflinePlayer.class);when(player.getUniqueId()).thenReturn(uuid);String receipt="a".repeat(64);
DuneEconomy first=new DuneEconomy(plugin);assertTrue(first.grantCommunity(uuid,"2026-10",50,receipt));assertEquals(50,first.getBalance(player));
first.add(uuid,10);assertEquals(60,first.getBalance(player));
DuneEconomy restarted=new DuneEconomy(plugin);assertFalse(restarted.grantCommunity(uuid,"2026-10",50,receipt));assertEquals(60,restarted.getBalance(player));assertEquals(List.of(receipt),restarted.pendingCommunityReceipts().get(uuid));
assertThrows(Exception.class,()->restarted.grantCommunity(uuid,"2026-10",50,"b".repeat(64)));
restarted.acknowledgeCommunity(uuid,receipt);assertTrue(new DuneEconomy(plugin).pendingCommunityReceipts().isEmpty());
assertTrue(restarted.grantCommunity(uuid,"2026-11",50,"c".repeat(64)));assertEquals(110,restarted.getBalance(player));
}
@Test void failedDurableWriteDoesNotCreditOrConsumeTheReward() throws Exception {
DuneEss plugin=plugin();DuneEconomy ledger=new DuneEconomy(plugin);UUID uuid=UUID.randomUUID();OfflinePlayer player=mock(OfflinePlayer.class);when(player.getUniqueId()).thenReturn(uuid);
Path blocker=directory.resolve("DuneEss/balances.yml.community-tmp");Files.createDirectory(blocker);
assertThrows(Exception.class,()->ledger.grantCommunity(uuid,"2026-10",50,"a".repeat(64)));assertEquals(0,ledger.getBalance(player));assertTrue(ledger.pendingCommunityReceipts().isEmpty());
Files.delete(blocker);assertTrue(ledger.grantCommunity(uuid,"2026-10",50,"a".repeat(64)));assertEquals(50,ledger.getBalance(player));
}
@Test void incompleteSharedConfigurationCannotCreateASecondLocalWallet() throws Exception {
Files.createDirectories(directory.resolve("DuneCore"));YamlConfiguration core=new YamlConfiguration();core.set("database.enabled",true);core.set("database.jdbc-url","");core.save(directory.resolve("DuneCore/config.yml").toFile());
DuneEconomy ledger=new DuneEconomy(plugin());UUID uuid=UUID.randomUUID();OfflinePlayer player=mock(OfflinePlayer.class);when(player.getUniqueId()).thenReturn(uuid);
assertFalse(ledger.depositPlayer(player,50).transactionSuccess());assertEquals(0,ledger.getBalance(player));
assertThrows(Exception.class,()->ledger.grantCommunity(uuid,"2026-10",50,"a".repeat(64)));
}
}

View file

@ -0,0 +1,12 @@
package com.example.duneess;
import com.example.dunegui.DunemarkItems;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class DunemarkDenominationsTest {
@Test void walletArtSelectsOnlySupportedDenominationsWithoutRoundingUp(){
assertEquals(1,DunemarkItems.denomination(0)); assertEquals(1,DunemarkItems.denomination(4.99));
assertEquals(5,DunemarkItems.denomination(5)); assertEquals(5,DunemarkItems.denomination(99.99));
assertEquals(100,DunemarkItems.denomination(100));assertEquals(1000,DunemarkItems.denomination(4999.99));
assertEquals(5000,DunemarkItems.denomination(5000));
}
}

View file

@ -98,4 +98,28 @@ class ExchangeStoreTest {
assertThrows(IllegalArgumentException.class,()->listing(0,"1"));
assertThrows(IllegalArgumentException.class,()->listing(65,"1"));
}
@Test void committedSaleRecordsBuyerItemAndExactPaymentButFailuresDoNot() throws Exception {
long id=listing(2,"12.50");store.buy(buyer,"BuyerName",id);
try(Connection c=DriverManager.getConnection(url);Statement q=c.createStatement();ResultSet r=q.executeQuery("SELECT * FROM dune_exchange_sales")) {
assertTrue(r.next());assertEquals(seller,r.getObject("seller",UUID.class));
assertEquals(buyer,r.getObject("buyer",UUID.class));assertEquals("BuyerName",r.getString("buyer_name"));
assertEquals(1,r.getInt("quantity"));assertEquals(new BigDecimal("12.50"),r.getBigDecimal("total_price"));assertFalse(r.next());
}
assertThrows(IllegalArgumentException.class,()->store.buy(seller,id));store.cancel(seller,id);
try(Connection c=DriverManager.getConnection(url);Statement q=c.createStatement();ResultSet r=q.executeQuery("SELECT COUNT(*) FROM dune_exchange_sales")) {
assertTrue(r.next());assertEquals(1,r.getInt(1));
}
}
@Test void externallyOwnedTransactionRollsBackStockWalletsAndHistoryTogether() throws Exception {
long id=listing(1,"25");
try(Connection c=DriverManager.getConnection(url)) {
c.setAutoCommit(false);ExchangeStore.bound(c).buy(buyer,"Buyer",id);
assertFalse(c.isClosed());c.rollback();
}
assertEquals(1,store.find(id).quantity());assertEquals(new BigDecimal("100.00"),balance(buyer));
assertEquals(new BigDecimal("0.00"),balance(seller));
try(Connection c=DriverManager.getConnection(url);Statement q=c.createStatement();ResultSet r=q.executeQuery("SELECT COUNT(*) FROM dune_exchange_sales")) {
assertTrue(r.next());assertEquals(0,r.getInt(1));
}
}
}

View file

@ -0,0 +1,15 @@
package com.example.duneess;
import com.example.dunegui.PlanetSigils;
import com.example.dunegui.PublicNames;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class PlanetNamesTest {
@Test void newDisplayNamesRetainSavedIdentifiersAndFullCapitalization(){
assertEquals("Arrakduin",PlanetSigils.label("arrakis"));assertEquals("Kaladam",PlanetSigils.label("caladan"));
assertEquals("Giedermark",PlanetSigils.label("giedi_prime"));assertEquals("Kaiterhof",PlanetSigils.label("kaitain"));
assertEquals("Sigmadraken IV",PlanetSigils.label("sigma_draconis_iv"));
assertEquals("arrakis_world_id",PublicNames.text("arrakis_world_id"));
assertEquals("/duneess travel arrakis",PublicNames.text("/duneess travel arrakis"));
assertEquals("Arrakduin and Kaladam",PublicNames.text("Serevan and Pelareth"));
}
}

View file

@ -1,4 +1,4 @@
# Spacing Guild lobby world
# Vaerkring lobby world
A separate **Minecraft Java / Paper 1.21.4 / Java 21** End-dimension lobby. The rebuilt 1.1.0 world is already built and saved in [`../worlds/Dune-Guild-Lobby-1.1.0.zip`](../worlds/Dune-Guild-Lobby-1.1.0.zip); the deterministic builder and runtime companion are here. It does not replace a planet world.

View file

@ -9,4 +9,4 @@
Final ImageGen prompt (reference image was the preceding five-room starport concept):
> Update this Minecraft Dune Spacing Guild lobby rendering with a SIXTH room, a shady SMUGGLER EXCHANGE. Preserve every existing room: central spawn with amber Guild Navigator tank, Dune II-inspired STARPORT / TELEPORT upper left with square landing and launch pads and block-built frigate, official EXCHANGE left, NEWS upper right, RULES right, purple End atmosphere and gold/blackstone architecture. Widen framing or pull back as needed to show all six distinct connected rooms clearly. Add the new smugglers' den as a substantial enclosed annex in the lower foreground below the official Exchange, attached via a narrow dim side corridor branching off the official Exchange. It must be visibly different: lower vaulted ceiling (removed for cutaway), dark worn stone, rusty copper pipes, patchwork brown cloth awnings/screens, stacked barrels and crates, low amber lanterns, discreet violet accents. TWO separate Minecraft villager seller NPCs behind separate screened market counters: WATER SELLER next to blue glass water vessels and a cauldron, SPICE SELLER beside orange spice samples and sacks represented by brown blocks and barrels. Small clear labels over counters 'WATER' and 'SPICE'. Shady illicit back-room atmosphere but navigable and readable. Clearly label the new annex 'SMUGGLER EXCHANGE' with matching clean external architectural callout. Keep five other callouts correctly pointing to their rooms. Floor of annex is fully supported and bounded, no unsafe holes; visible corridor connection. High-quality architectural Minecraft shader concept overview, block-built geometry and pixel textures, no photoreal smooth creatures. Retain wall artwork in framed maps. One wide coherent elevated isometric roofless cutaway, clean presentation, no HUD or watermark.
> Update this Minecraft Dune Vaerkring lobby rendering with a SIXTH room, a shady SMUGGLER EXCHANGE. Preserve every existing room: central spawn with amber Guild Navigator tank, Dune II-inspired STARPORT / TELEPORT upper left with square landing and launch pads and block-built frigate, official EXCHANGE left, NEWS upper right, RULES right, purple End atmosphere and gold/blackstone architecture. Widen framing or pull back as needed to show all six distinct connected rooms clearly. Add the new smugglers' den as a substantial enclosed annex in the lower foreground below the official Exchange, attached via a narrow dim side corridor branching off the official Exchange. It must be visibly different: lower vaulted ceiling (removed for cutaway), dark worn stone, rusty copper pipes, patchwork brown cloth awnings/screens, stacked barrels and crates, low amber lanterns, discreet violet accents. TWO separate Minecraft villager seller NPCs behind separate screened market counters: WATER SELLER next to blue glass water vessels and a cauldron, SPICE SELLER beside orange spice samples and sacks represented by brown blocks and barrels. Small clear labels over counters 'WATER' and 'SPICE'. Shady illicit back-room atmosphere but navigable and readable. Clearly label the new annex 'SMUGGLER EXCHANGE' with matching clean external architectural callout. Keep five other callouts correctly pointing to their rooms. Floor of annex is fully supported and bounded, no unsafe holes; visible corridor connection. High-quality architectural Minecraft shader concept overview, block-built geometry and pixel textures, no photoreal smooth creatures. Retain wall artwork in framed maps. One wide coherent elevated isometric roofless cutaway, clean presentation, no HUD or watermark.

View file

@ -86,9 +86,9 @@ public final class DuneLobby extends JavaPlugin implements Listener, CommandExec
private boolean inLobby(World world) { return lobby!=null && world.equals(lobby); }
private void ensureNpcs() {
for(int x=-8;x<=6;x++) for(int z=-6;z<=8;z++) lobby.getChunkAt(x,z).load();
npc("liaison","Guild Navigator Liaison",13,87,-11,Villager.Profession.CLERIC);
npc("exchange","CHOAM Exchange Broker",-82,81,23,Villager.Profession.LIBRARIAN);
npc("water","Discreet Water Seller",-78,81,110,Villager.Profession.FISHERMAN);
npc("liaison","Vaerkring Routekeeper Liaison",13,87,-11,Villager.Profession.CLERIC);
npc("exchange","Koopkring Exchange Broker",-82,81,23,Villager.Profession.LIBRARIAN);
npc("water","Discreet Welvaarder",-78,81,110,Villager.Profession.FISHERMAN);
npc("spice","Discreet Spice Seller",-54,81,110,Villager.Profession.LEATHERWORKER);
}
private void npc(String role,String name,int x,int y,int z,Villager.Profession profession) {
@ -180,7 +180,7 @@ public final class DuneLobby extends JavaPlugin implements Listener, CommandExec
if(role==null) return; e.setCancelled(true); if(e.getHand()!=EquipmentSlot.HAND) return;
switch(role) {
case "liaison" -> { if(Bukkit.getPluginCommand("duneess")!=null) e.getPlayer().performCommand("duneess travel"); else departure(e.getPlayer(),"arrakis"); }
case "exchange" -> { if(Bukkit.getPluginCommand("dune")!=null) e.getPlayer().performCommand("dune exchange"); else e.getPlayer().sendMessage(ChatColor.GOLD+"CHOAM market integration requires DuneCore on this backend."); }
case "exchange" -> { if(Bukkit.getPluginCommand("dune")!=null) e.getPlayer().performCommand("dune exchange"); else e.getPlayer().sendMessage(ChatColor.GOLD+"Koopkring market integration requires DuneCore on this backend."); }
case "water","spice" -> trade(e.getPlayer(),role);
}
}
@ -193,7 +193,7 @@ public final class DuneLobby extends JavaPlugin implements Listener, CommandExec
result.setItemMeta(meta);
int price=Math.max(1,Math.min(64,getConfig().getInt(water?"water-price-emeralds":"spice-price-emeralds",water?4:8)));
MerchantRecipe recipe=new MerchantRecipe(result,0,999,false,0,0f); recipe.addIngredient(new ItemStack(Material.EMERALD,price));
Merchant merchant=Bukkit.createMerchant(water?"Discreet Water Seller":"Discreet Spice Seller"); merchant.setRecipes(List.of(recipe)); player.openMerchant(merchant,true);
Merchant merchant=Bukkit.createMerchant(water?"Discreet Welvaarder":"Discreet Spice Seller"); merchant.setRecipes(List.of(recipe)); player.openMerchant(merchant,true);
}
@EventHandler public void interact(PlayerInteractEvent e) {
if(!inLobby(e.getPlayer().getWorld()) || e.getClickedBlock()==null || e.getAction()!=Action.RIGHT_CLICK_BLOCK) return;

Some files were not shown because too many files have changed in this diff Show more