Add Wild Update quest journal and verified open Guild travel

This commit is contained in:
unimatrixgit 2026-12-03 21:44:51 +01:00
commit 8404c61329
10 changed files with 834 additions and 29 deletions

View file

@ -7,6 +7,11 @@ import {gameAuthorized,validUuid,json} from './game-link.mjs';
import {boardingOpen} from './game-organisation-policy.mjs';
import {createPostbankAuthority} from './postbank-authority.mjs';
import {createGuildPassageLedger} from './guild-passage-ledger.mjs';
import {paidTariff,effectiveTrips,classifyRoute,BOUNTY_MULTIPLIER} from './travel-tariff.mjs';
import {createNativeHoldingCheck} from './travel-holdings.mjs';
import {createTravelBountyClaims,TRAVEL_BOUNTY_CLAIM_SCHEMA} from './travel-bounty-claims.mjs';
export {TRAVEL_BOUNTY_CLAIM_SCHEMA};
export const TRAVEL_OPEN_PASSAGE_SCHEMA="CREATE TABLE IF NOT EXISTS pb_guild_open_passages(id CHAR(36) PRIMARY KEY,source_world VARCHAR(32) NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
import {createOwnedSmugglerRoutes} from './owned-smuggler-routes.mjs';
import {createOwnedSmugglerPassages} from './owned-smuggler-passages.mjs';
import {validOwnedSmugglerRequest} from './owned-smuggler-request.mjs';
@ -22,15 +27,46 @@ export const GUILD_SCHEMA=`CREATE TABLE IF NOT EXISTS pb_guild_passages(id CHAR(
export const SMUGGLER_PASSAGE_SCHEMA="CREATE TABLE IF NOT EXISTS pb_smuggler_passages(id CHAR(36) PRIMARY KEY,permit_key CHAR(36) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
const routes={atreides:'caladan',harkonnen:'giedi_prime',corrino:'kaitain',ordos:'sigma_draconis_iv',fremen:'arrakis'};
const fail=(message,status=409)=>{throw new BankError(message,status);};
export function createGuildService(bank,{authority,resolve,allowArrakis=async()=>false,recordArrival=async()=>{},allowJourney=async()=>true,clock=Date.now,fareMinor=10000,surcharge=async()=>0,discount=async()=>0,allowSmuggling=null,smugglerFareMinor=fareMinor,prologueReady=async()=>true,subsidies=null,routeBindings=false,homeRoutes=null,authorityForStore=null}={}){
export const TRAVEL_LADDER_SCHEMA="CREATE TABLE IF NOT EXISTS pb_travel_ladder(actor_id CHAR(36) PRIMARY KEY,trips INT NOT NULL,last_paid_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
export const TRAVEL_BOUNTY_SCHEMA="CREATE TABLE IF NOT EXISTS pb_travel_bounties(id CHAR(36) PRIMARY KEY,actor_id CHAR(36) NOT NULL,minecraft_uuid CHAR(36) NOT NULL,traveller VARCHAR(64) NOT NULL,world VARCHAR(32) NOT NULL,fare_minor BIGINT NOT NULL,amount_minor BIGINT NOT NULL,state VARCHAR(12) NOT NULL,created_at BIGINT NOT NULL,claimed_by CHAR(36) NULL,claimed_at BIGINT NULL,claim_request CHAR(36) NULL UNIQUE,INDEX travel_bounty_open(minecraft_uuid,state,created_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
export function createGuildService(bank,{authority,resolve,allowArrakis=async()=>false,recordArrival=async()=>{},allowJourney=async()=>true,clock=Date.now,fareMinor=10000,surcharge=async()=>0,discount=async()=>0,openTravel=false,holdingOnWorld=async()=>false,allowSmuggling=null,smugglerFareMinor=fareMinor,prologueReady=async()=>true,subsidies=null,routeBindings=false,homeRoutes=null,authorityForStore=null}={}){
if(!Number.isSafeInteger(fareMinor)||fareMinor<1||fareMinor>100000000||!Number.isSafeInteger(smugglerFareMinor)||smugglerFareMinor<1||smugglerFareMinor>100000000)throw Error('Invalid Guild fare');
const ledger=createGuildPassageLedger(bank,{authority,clock,subsidies}),{funds,release,reserve,settle}=ledger;
const ledger=createGuildPassageLedger(bank,{authority,clock,subsidies}),{funds,release,reserve,settle,payout}=ledger;
async function quotedFare(user,store=bank,lock=false){const percent=await surcharge(clock()),reduction=await discount(user.faction,clock());const normal=standardGuildFare(fareMinor,percent,reduction);if(normal===null)fail('The Guild tariff requires review.',503);const offer=subsidies?await subsidies.quote(store,normal,reduction,lock):null;return {price:offer?.price??normal,offer};}
const view=r=>({requestId:r.id,destination:r.destination,state:r.state,fareMinor:Number(r.fare_minor),expiresAt:Number(r.expires_at)});
const readyForTravel=async(user,uuid,store=bank)=>await prologueReady(user,uuid)||!!await store.first("SELECT id FROM pb_guild_passages WHERE actor_id=? AND minecraft_uuid=? AND state='arrived' LIMIT 1",[user.id,uuid]);
const allowed=async(user,destination)=>!!routes[user?.faction]&&(destination===routes[user.faction]||destination==='arrakis'&&await allowArrakis(user.faction,user));
const allowed=async(user,destination)=>!!routes[user?.faction]&&(openTravel?Object.values(routes).includes(destination):destination===routes[user.faction]||destination==='arrakis'&&await allowArrakis(user.faction,user));
async function expire(){const expired=await bank.transaction(async tx=>{const rows=await tx.query("SELECT * FROM pb_guild_passages WHERE state='pending' AND expires_at<=? ORDER BY id LIMIT 25 FOR UPDATE",[clock()]);for(const r of rows)await release(tx,r);return rows.length;});if(subsidies)await subsidies.expire();return expired;}
// ---- Open travel: race world and Lobby are free, every other world is paid and carries a bounty ----
async function tariff(user,uuid,destination,store,lock=false){
const decree=destination==='arrakis'&&await allowArrakis(user.faction,user),route=classifyRoute({destination,raceWorld:routes[user.faction],decree});
if(route.free)return{free:true,reason:route.reason,fareMinor:0,bountyMinor:0};
const row=await store.first('SELECT trips,last_paid_at FROM pb_travel_ladder WHERE actor_id=?'+(lock?' FOR UPDATE':''),[user.id]);
const trips=effectiveTrips(row?.trips??0,row?.last_paid_at??null,clock());
return{free:false,reason:'paid',...paidTariff({trips,reduced:await holdingOnWorld(user,uuid,destination,{fresh:lock})})};
}
async function recordTrip(tx,r,user){
const fare=Number(r.fare_minor);if(fare<1)return; // a free passage carries no bounty and does not move the ladder
const now=clock(),row=await tx.first('SELECT trips,last_paid_at FROM pb_travel_ladder WHERE actor_id=? FOR UPDATE',[user.id]),trips=effectiveTrips(row?.trips??0,row?.last_paid_at??null,now)+1;
if(row)await tx.query('UPDATE pb_travel_ladder SET trips=?,last_paid_at=? WHERE actor_id=?',[trips,now,user.id]);else await tx.query('INSERT INTO pb_travel_ladder(actor_id,trips,last_paid_at) VALUES(?,?,?)',[user.id,trips,now]);
await tx.query("INSERT INTO pb_travel_bounties(id,actor_id,minecraft_uuid,traveller,world,fare_minor,amount_minor,state,created_at) VALUES(?,?,?,?,?,?,?,'open',?)",[r.id,user.id,r.minecraft_uuid,String(user.username).slice(0,64),r.destination,fare,fare*BOUNTY_MULTIPLIER,now]);
}
async function quoteOpen(uuid,sourceWorld){
await expire();const user=await resolve(uuid);if(!user||!routes[user.faction])fail('Link your active website account and choose your House first.',403);
const ready=await readyForTravel(user,uuid),open=[],catalog=[];
for(const world of TRADE_WORLDS){
const t=await tariff(user,uuid,world.id,bank),journey=await allowJourney(sourceWorld,world.id,bank,false),source=ready&&journey&&t.fareMinor>0?await funds(bank,user,t.fareMinor):null;
const reason=!ready?'Complete your House Prologue first.':world.id===tradeWorld(sourceWorld)?'Already on this world.':tradeWorld(sourceWorld)!=='lobby'?'Board ordinary passages from the Guild Lobby.':!journey?'The Spacing Guild has embargoed this route.':!boardingOpen(clock())?'Boarding opens at :00, :20 and :40 for five minutes.':t.fareMinor>0&&!source?'Not enough available Dunemarks.':'';
if(!reason)open.push(world.id);
catalog.push({server:world.id,name:world.name,available:!reason,reason,fareMinor:t.fareMinor,free:t.free,...(t.free?{freeReason:t.reason}:{bountyMinor:t.bountyMinor,reduced:t.reduced,trip:t.trip})});
}
const home=catalog.find(r=>r.server===routes[user.faction]);
return{ok:true,openTravel:true,destination:routes[user.faction],destinations:open,routes:catalog,fareMinor:home?.fareMinor??0,affordable:open.length>0,...(!ready?{prologueRequired:true}:{})};
}
const bountyClaim=createTravelBountyClaims(bank,{resolve,clock,payout,enabled:()=>openTravel});
async function quote(uuid,sourceWorld='lobby'){
if(openTravel)return quoteOpen(uuid,sourceWorld);
await expire();const user=await resolve(uuid);if(!user||!routes[user.faction])fail('Link your active website account and choose your House first.',403);
const ready=await readyForTravel(user,uuid),{price,offer}=await quotedFare(user),source=ready?await funds(bank,user,price):null,open=[],catalog=[];
for(const world of TRADE_WORLDS){const lawful=await allowed(user,world.id),journey=lawful&&await allowJourney(sourceWorld,world.id,bank,false);if(ready&&journey)open.push(world.id);
@ -53,16 +89,18 @@ export function createGuildService(bank,{authority,resolve,allowArrakis=async()=
const legacy=catalog.find(r=>r.server==='arrakis');return {ok:true,eligible:legacy.eligible,allowed:legacy.allowed,permitExpiresAt:legacy.permitExpiresAt,fareMinor:smugglerFareMinor,affordable:legacy.affordable,keyId:user.keyId,version:user.version,routes:catalog};
}
async function board(input,smuggler=false){await expire();const user=await resolve(input.uuid);if(!user||!routes[user.faction]||user.keyId!==input.keyId||user.version!==input.version)fail('Your House key changed. Reopen the Guild menu.',403);
if(!await readyForTravel(user,input.uuid))fail('Complete your House Prologue before first passage.',403);if(!Number.isSafeInteger(input.fareMinor)||input.fareMinor<1||input.fareMinor>100000000)fail('Invalid Guild fare.',400);const destination=input.destination??routes[user.faction];if(smuggler?!Object.values(routes).includes(destination)||!tradeWorld(input.sourceWorld)||destination===tradeWorld(input.sourceWorld)||!routeBindings&&(destination!=='arrakis'||input.sourceWorld!=='lobby'):!await allowed(user,destination))fail(smuggler?'A current smuggler passage is required.':'Your House has no Imperial passage for this destination.',403);const legacyFingerprint=createHash('sha256').update(JSON.stringify([input.uuid,user.id,input.keyId,input.version,destination,input.fareMinor,...(smuggler?["smuggler"]:[])])).digest('hex'),fingerprint=smuggler&&routeBindings?createHash('sha256').update(JSON.stringify([legacyFingerprint,input.sourceWorld])).digest('hex'):legacyFingerprint;
if(!await readyForTravel(user,input.uuid))fail('Complete your House Prologue before first passage.',403);if(!Number.isSafeInteger(input.fareMinor)||input.fareMinor<(openTravel&&!smuggler?0:1)||input.fareMinor>100000000)fail('Invalid Guild fare.',400);const destination=input.destination??routes[user.faction];if(smuggler?!Object.values(routes).includes(destination)||!tradeWorld(input.sourceWorld)||destination===tradeWorld(input.sourceWorld)||!routeBindings&&(destination!=='arrakis'||input.sourceWorld!=='lobby'):!await allowed(user,destination))fail(smuggler?'A current smuggler passage is required.':'Your House has no Imperial passage for this destination.',403);const legacyFingerprint=createHash('sha256').update(JSON.stringify([input.uuid,user.id,input.keyId,input.version,destination,input.fareMinor,...(smuggler?["smuggler"]:[])])).digest('hex'),fingerprint=smuggler&&routeBindings?createHash('sha256').update(JSON.stringify([legacyFingerprint,input.sourceWorld])).digest('hex'):legacyFingerprint;
if(openTravel&&!smuggler&&tradeWorld(input.sourceWorld||'lobby')!=='lobby')fail('Board ordinary Guild passages from the Guild Lobby.',403);
return bank.transaction(async tx=>{
const prior=await tx.first('SELECT * FROM pb_guild_passages WHERE id=? FOR UPDATE',[input.requestId]);if(prior){const legacy=smuggler&&routeBindings&&destination==='arrakis'&&input.sourceWorld==='lobby'&&prior.fingerprint===legacyFingerprint&&!await tx.first('SELECT id FROM pb_guild_route_bindings WHERE id=?',[prior.id]);if(prior.actor_id!==user.id||prior.fingerprint!==fingerprint&&!legacy)fail('This passage reference was already used.');return{ok:true,...view(prior),...(smuggler?{smuggler:true}:{}),replayed:true};}
const {price,offer}=smuggler?{price:smugglerFareMinor,offer:null}:await quotedFare(user,tx,true);if(input.fareMinor!==price)fail('The Guild fare changed. Reopen the passage menu.');
const openRoute=openTravel&&!smuggler?await tariff(user,input.uuid,destination,tx,true):null,{price,offer}=smuggler?{price:smugglerFareMinor,offer:null}:openRoute?{price:openRoute.fareMinor,offer:null}:await quotedFare(user,tx,true);if(input.fareMinor!==price)fail('The Guild fare changed. Reopen the passage menu.');
if(!smuggler&&!await allowJourney(input.sourceWorld||'lobby',destination,tx,true))fail('The Spacing Guild has embargoed this world. Smuggler routes remain available.',403);
if(!smuggler&&!boardingOpen(clock()))fail('Boarding opens at :00, :20 and :40 for five minutes.');
const fresh=await resolve(input.uuid);if(!fresh||fresh.id!==user.id||fresh.keyId!==input.keyId||fresh.version!==input.version||!await readyForTravel(fresh,input.uuid,tx)||!smuggler&&!await allowed(fresh,destination))fail('Your House key or Imperial passage changed.',403);
const permit=smuggler?await smugglerPermit(fresh,input.uuid,input.sourceWorld,tx,true,destination):null;if(smuggler&&!permit)fail("Meet Esmar Tuek for a current personal smuggler permission.",403);
// Lock this customer's accounts before checking their other in-flight passage.
const now=clock(),r=await reserve(tx,input,user,{price,fingerprint,destination,expiresAt:smuggler?Math.min(now+120000,permit.expiresAt):now+120000,permitKey:permit?.keyId||null,offer});
if(openRoute)await tx.query('INSERT INTO pb_guild_open_passages(id,source_world,created_at) VALUES(?,?,?)',[r.id,'lobby',now]);
if(smuggler&&routeBindings)await tx.query("INSERT INTO pb_guild_route_bindings(id,route_kind,source_world,created_at) VALUES(?,'esmar',?,?)",[r.id,input.sourceWorld,now]);return{ok:true,...view(r),...(smuggler?{smuggler:true}:{})};
});
}
@ -73,14 +111,14 @@ export function createGuildService(bank,{authority,resolve,allowArrakis=async()=
const marker=allowSmuggling?await tx.first('SELECT permit_key FROM pb_smuggler_passages WHERE id=? FOR UPDATE',[r.id]):null;r.smuggler=!!marker;if(r.state==='arrived')return r;
if(Number(r.expires_at)<=clock()){await release(tx,r);return null;}
if(user.keyId!==r.house_key||user.version!==Number(r.house_version)||!await readyForTravel(user,uuid,tx)||(marker?(await allowSmuggling(user,uuid,clock()))?.keyId!==marker.permit_key:!await allowed(user,r.destination)||!await allowJourney('lobby',r.destination,tx,true))){await release(tx,r);return null;}
await settle(tx,r,user,!!marker);return r;
await settle(tx,r,user,!!marker);if(openTravel&&!marker&&await tx.first('SELECT id FROM pb_guild_open_passages WHERE id=?',[r.id]))await recordTrip(tx,r,user);return r;
});
if(row){if(!row.smuggler)await recordArrival(user,row);await bank.query("UPDATE pb_guild_passages SET reported_at=? WHERE id=? AND state='arrived'",[clock(),row.id]);}return{ok:true,passage:row?{...view(row),...(row.smuggler?{smuggler:true}:{})}:null};
if(row){if(!row.smuggler)await recordArrival(user,row);await bank.query("UPDATE pb_guild_passages SET reported_at=? WHERE id=? AND state='arrived'",[clock(),row.id]);}let bounty=null;if(row&&openTravel&&!row.smuggler&&Number(row.fare_minor)>0){const b=await bank.first('SELECT * FROM pb_travel_bounties WHERE id=?',[row.id]);if(b)bounty={requestId:b.id,traveller:b.traveller,world:b.world,amountMinor:Number(b.amount_minor),state:b.state};}return{ok:true,passage:row?{...view(row),...(row.smuggler?{smuggler:true}:{})}:null,...(bounty?{bounty}:{})};
}
async function checkTravel(uuid,source,destination){if(!await resolve(uuid))fail('A linked account is required.',403);return bank.transaction(async tx=>{if(!await allowJourney(source,destination,tx,true))fail('The Spacing Guild has embargoed journeys to and from this world. Smuggler routes remain available.',403);return{ok:true,source,destination,expiresAt:clock()+5000};});}
async function smugglerReturn(uuid,source){const user=await resolve(uuid);if(!user||!Object.values(routes).includes(source)||!routeBindings&&source!=='arrakis'||!allowSmuggling)fail('Meet Esmar Tuek on the arrival world.',403);const r=await bank.first("SELECT p.id,s.permit_key"+(routeBindings?',b.source_world,b.route_kind':'')+" FROM pb_guild_passages p LEFT JOIN pb_smuggler_passages s ON s.id=p.id"+(routeBindings?' LEFT JOIN pb_guild_route_bindings b ON b.id=p.id':'')+" WHERE p.actor_id=? AND p.minecraft_uuid=? AND p.destination=? AND p.state='arrived'"+" ORDER BY p.arrived_at DESC,p.id DESC LIMIT 1",[user.id,uuid,source]);if(!r?.permit_key||r.route_kind==='owned-home')fail('No confirmed personal smuggler arrival is available for return.',403);const destination=tradeWorld(r.source_world||'lobby');if(!destination||destination===source)fail('The recorded return route requires review.');return{ok:true,source,destination,expiresAt:clock()+5000,smuggler:true};}
const owned=routeBindings&&homeRoutes?createOwnedSmugglerPassages(bank,homeRoutes,{resolve,clock,price:smugglerFareMinor,ledger,expire,readyForTravel,authorityForStore}):{};
return{quote,quoteSmuggler,board,arrive,expire,checkTravel,smugglerReturn,...owned};
return{quote,quoteSmuggler,board,arrive,expire,checkTravel,smugglerReturn,bountyClaim,openTravel,...owned};
}
export function createGuildQuestReceipts(db,bank,keys,{clock=Date.now}={}){
const authorize=metric=>async(_actor,p)=>{const row=await bank.first("SELECT * FROM pb_guild_passages WHERE id=? AND state='arrived' AND NOT EXISTS(SELECT 1 FROM pb_smuggler_passages s WHERE s.id=pb_guild_passages.id)",[p.eventId]);return !!row&&row.actor_id===p.accountId&&row.minecraft_uuid===p.minecraftUuid&&p.metric===metric&&p.quantity===1&&p.occurredAt===Number(row.arrived_at)&&p.reference===(metric==='guild-travel'?'guild:':'guild-route:')+row.id;};
@ -91,7 +129,7 @@ export function createGameGuildAPI(db,bank,keys,settings={},dependencies={}){
const resolve=dependencies.resolve||(async(uuid,store=db)=>{const rows=await store.query("SELECT a.id,a.username,a.role,c.faction,c.version,h.key_id keyId FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id JOIN site_character_choices c ON c.user_id=a.id AND c.minecraft_uuid=l.minecraft_uuid JOIN jarvis_house_selections h ON h.account_id=a.id AND h.minecraft_uuid=l.minecraft_uuid AND h.version=c.version AND h.faction=c.faction JOIN organisation_keys k ON k.id=h.key_id AND k.revoked_at IS NULL AND (k.expires_at IS NULL OR k.expires_at>UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000) WHERE LOWER(l.minecraft_uuid)=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('system_account','official_account','memorial')",[uuid]);return rows.length===1?{...rows[0],version:Number(rows[0].version)}:null;});
const tradePolicy=db?.worldTradeEnabled&&bank?createBankTradePolicy(db,bank):null;
const allowJourney=async(source,destination,tx,lock)=>{if(!tradePolicy)return true;const policy=await tradePolicy(tx,Date.now(),lock);return ![source,destination].some(w=>policy[tradeWorld(w)]?.embargoUntil>Date.now());};
const service=dependencies.service||(bank?createGuildService(bank,{resolve,allowJourney,clock:dependencies.clock||Date.now,routeBindings:bank.guildRouteBindingsEnabled===true,authorityForStore:reader=>createPostbankAuthority(reader,{bank}),homeRoutes:db?.transaction?createOwnedSmugglerRoutes(db,{resolve,clock:dependencies.clock||Date.now}):null,surcharge:now=>currentGuildSurcharge(db,now),discount:(house,now)=>currentGuildDiscount(db,house,now),allowArrakis:async(house,user)=>await hasImperialPassage(db,house)||await hasOrganisationPassage(db,user),authority:createPostbankAuthority(db,{bank}),fareMinor:Number(settings.GUILD_FARE_MINOR||10000),recordArrival:createGuildQuestReceipts(db,bank,keys),allowSmuggling:(user,uuid,now)=>activeSmugglerPermit(db,keys,user,uuid,now),smugglerFareMinor:Number(settings.SMUGGLER_FARE_MINOR||settings.GUILD_FARE_MINOR||10000),prologueReady:async(user,uuid)=>(await housePrologueState(db,keys,user,uuid)).ready,subsidies:db?.guildSubsidyEnabled?createGuildSubsidies(bank,{verify:(pool,now)=>verifyGuildSubsidy(db,pool,now)}):null}):null);
const service=dependencies.service||(bank?createGuildService(bank,{resolve,allowJourney,clock:dependencies.clock||Date.now,routeBindings:bank.guildRouteBindingsEnabled===true,authorityForStore:reader=>createPostbankAuthority(reader,{bank}),homeRoutes:db?.transaction?createOwnedSmugglerRoutes(db,{resolve,clock:dependencies.clock||Date.now}):null,surcharge:now=>currentGuildSurcharge(db,now),discount:(house,now)=>currentGuildDiscount(db,house,now),allowArrakis:async(house,user)=>await hasImperialPassage(db,house)||await hasOrganisationPassage(db,user),authority:createPostbankAuthority(db,{bank}),fareMinor:Number(settings.GUILD_FARE_MINOR||10000),openTravel:settings.GUILD_OPEN_TRAVEL==='true',holdingOnWorld:createNativeHoldingCheck(db),recordArrival:createGuildQuestReceipts(db,bank,keys),allowSmuggling:(user,uuid,now)=>activeSmugglerPermit(db,keys,user,uuid,now),smugglerFareMinor:Number(settings.SMUGGLER_FARE_MINOR||settings.GUILD_FARE_MINOR||10000),prologueReady:async(user,uuid)=>(await housePrologueState(db,keys,user,uuid)).ready,subsidies:db?.guildSubsidyEnabled?createGuildSubsidies(bank,{verify:(pool,now)=>verifyGuildSubsidy(db,pool,now)}):null}):null);
return async request=>{
if(!gameAuthorized(request,settings))return json({message:'Unauthorized'},401);
if(request.method!=='POST'||new URL(request.url).search||!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return json({message:'A JSON Guild action is required.'},400);
@ -101,9 +139,9 @@ export function createGameGuildAPI(db,bank,keys,settings={},dependencies={}){
if(!service||typeof service[b.action]!=='function')return json({message:'Home Block navigation is unavailable.'},503);
try{const result=await service[b.action](b);return json(result,result.needsReview?409:200);}catch(error){return json({message:error instanceof BankError?error.message:'The passage could not be confirmed. Retry the original reference.'},error instanceof BankError?error.status||409:503);}
}
const fields={smuggler_return:['action','uuid','sourceWorld'],smuggler_quote:['action','uuid','sourceWorld'],smuggler_board:['action','uuid','requestId','keyId','version','fareMinor','sourceWorld','destination'],travel_check:['action','uuid','sourceWorld','destination'],quote:['action','uuid',...(Object.hasOwn(b||{},'sourceWorld')?['sourceWorld']:[])],board:['action','uuid','requestId','keyId','version','fareMinor',...(Object.hasOwn(b||{},'sourceWorld')?['sourceWorld']:[]),...(Object.hasOwn(b||{},'destination')?['destination']:[])],arrive:['action','uuid','server'],expire:['action']}[b?.action];
if((Object.hasOwn(b||{},'sourceWorld')&&!tradeWorld(b.sourceWorld))||b?.action==='travel_check'&&b.destination!=='lobby'||!fields||Object.keys(b).length!==fields.length||fields.some(f=>!Object.hasOwn(b,f))||b.action!=='expire'&&!validUuid(b.uuid)||['board','smuggler_board'].includes(b.action)&&(!validUuid(b.requestId)||!validUuid(b.keyId)||!Number.isSafeInteger(b.version)||b.version<1||!Number.isSafeInteger(b.fareMinor)||b.fareMinor<1||Object.hasOwn(b,'destination')&&!Object.values(routes).includes(b.destination))||b.action==='arrive'&&!Object.values(routes).includes(b.server))return json({message:'Invalid Guild fields'},400);
const fields={smuggler_return:['action','uuid','sourceWorld'],smuggler_quote:['action','uuid','sourceWorld'],smuggler_board:['action','uuid','requestId','keyId','version','fareMinor','sourceWorld','destination'],travel_check:['action','uuid','sourceWorld','destination'],quote:['action','uuid',...(Object.hasOwn(b||{},'sourceWorld')?['sourceWorld']:[])],board:['action','uuid','requestId','keyId','version','fareMinor',...(Object.hasOwn(b||{},'sourceWorld')?['sourceWorld']:[]),...(Object.hasOwn(b||{},'destination')?['destination']:[])],arrive:['action','uuid','server'],bounty_claim:['action','uuid','victim','requestId','server'],expire:['action']}[b?.action];
if((Object.hasOwn(b||{},'sourceWorld')&&!tradeWorld(b.sourceWorld))||b?.action==='travel_check'&&b.destination!=='lobby'||!fields||Object.keys(b).length!==fields.length||fields.some(f=>!Object.hasOwn(b,f))||b.action!=='expire'&&!validUuid(b.uuid)||['board','smuggler_board'].includes(b.action)&&(!validUuid(b.requestId)||!validUuid(b.keyId)||!Number.isSafeInteger(b.version)||b.version<1||!Number.isSafeInteger(b.fareMinor)||b.fareMinor<(b.action==='board'&&service?.openTravel?0:1)||Object.hasOwn(b,'destination')&&!Object.values(routes).includes(b.destination))||b.action==='arrive'&&!Object.values(routes).includes(b.server)||b.action==='bounty_claim'&&(!validUuid(b.victim)||!validUuid(b.requestId)||b.victim===b.uuid||!Object.values(routes).includes(b.server)))return json({message:'Invalid Guild fields'},400);
if(!service)return json({message:'The central bank is unavailable.'},503);
try{return json(b.action==='smuggler_return'?await service.smugglerReturn(b.uuid,b.sourceWorld):b.action==='smuggler_quote'?await service.quoteSmuggler(b.uuid,b.sourceWorld):b.action==='smuggler_board'?await service.board(b,true):b.action==='quote'?await service.quote(b.uuid,b.sourceWorld):b.action==='travel_check'?await service.checkTravel(b.uuid,b.sourceWorld,b.destination):b.action==='board'?await service.board(b):b.action==='arrive'?await service.arrive(b.uuid,b.server):{ok:true,expired:await service.expire()});}catch(e){return json({message:e instanceof BankError?e.message:'The Guild could not confirm this passage. Retry the same reference.'},e instanceof BankError?e.status||409:503);}
try{return json(b.action==='smuggler_return'?await service.smugglerReturn(b.uuid,b.sourceWorld):b.action==='smuggler_quote'?await service.quoteSmuggler(b.uuid,b.sourceWorld):b.action==='smuggler_board'?await service.board(b,true):b.action==='quote'?await service.quote(b.uuid,b.sourceWorld):b.action==='travel_check'?await service.checkTravel(b.uuid,b.sourceWorld,b.destination):b.action==='board'?await service.board(b):b.action==='arrive'?await service.arrive(b.uuid,b.server):b.action==='bounty_claim'?await service.bountyClaim({killer:b.uuid,victim:b.victim,requestId:b.requestId,server:b.server}):{ok:true,expired:await service.expire()});}catch(e){return json({message:e instanceof BankError?e.message:'The Guild could not confirm this passage. Retry the same reference.'},e instanceof BankError?e.status||409:503);}
};
}

View file

@ -27,6 +27,18 @@ export function createGameQuestsAPI(db,settings,{personal=null,pol=null,starter=
let input;
try{const chunks=[];let size=0;while(true){const {done,value}=await reader.read();if(done)break;size+=value.byteLength;if(size>4096){await reader.cancel();return json({message:'Quest request too large.'},413);}chunks.push(value);}input=JSON.parse(Buffer.concat(chunks).toString('utf8'));}
catch{return json({message:'Invalid quest action.'},400);}finally{reader.releaseLock();}
if(input?.action==='login_settle'){
if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).some(k=>!['action','uuid'].includes(k))||!validUuid(input.uuid))return json({message:'A player UUID is required.'},400);
try{
const user=await resolve(input.uuid);if(!user)return json({message:'Link an active personal Minecraft account first.'},403);
const actor={...user,revalidate:()=>resolve(input.uuid)},settled=[];let failed=0;
for(const [kind,runtime] of [['personal',personal],['pol',pol]]){
if(!runtime?.quests?.settleCompleted)continue;
try{await runtime.collect?.(actor);const result=await runtime.quests.settleCompleted(actor);for(const row of result.settled)settled.push({...row,kind});failed+=result.failed;if(result.settled.length)await runtime.quests.processCompletions?.({accountId:actor.id});}catch{failed++;}
}
return json({ok:true,settled,failed});
}catch{return json({message:'The quest payout was not confirmed. It will be retried on your next login.'},503);}
}
const refine=input?.action==='prepare_refine';
const equipment=input?.action==='prepare_starter';
const meatTurnin=input?.action==='prepare_husbandry_turnin',supply=input?.action==='prepare_pol_supply',dossier=input?.action==='dossier_step',cargoAction=input?.action==='prepare_pol_cargo',cargoPartner=input?.action==='cargo_partner';

View file

@ -2,6 +2,8 @@ import {PostbankPayments} from './postbank-payments.mjs';
import {BankError} from './postbank-service.mjs';
import {canDebitAccount} from './postbank-authorisations.mjs';
import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs';
import {creditID} from './postbank-credit-ledger.mjs';
import {postPayrollIssue} from './postbank-payroll-issuer.mjs';
const accountSQL=`SELECT a.*,c.entity_id,e.external_key,e.active entity_active,p.state package_state FROM pb_accounts a LEFT JOIN pb_clients c ON c.client_number=a.client_number LEFT JOIN pb_entities e ON e.id=c.entity_id LEFT JOIN pb_packages p ON p.id=a.package_id`;
const fail=(message,status=409)=>{throw new BankError(message,status);};
// Shared by ordinary Guild, Esmar and owned-home routes. One reservation and ledger.
@ -10,15 +12,17 @@ export function createGuildPassageLedger(bank,{authority,clock=Date.now,subsidie
async function funds(tx,user,amount,lock=false,authorise=authority){const context=await authorise(user,{bank:tx});return(await tx.query(accountSQL+" WHERE e.kind='person' AND e.external_key=? AND a.system_key IS NULL ORDER BY a.id"+(lock?' FOR UPDATE':''),[user.id])).find(a=>ordinaryPaymentAccount(a)&&canDebitAccount(context,a.entity_id,a.id)&&BigInt(a.balance_minor)-BigInt(a.reserved_minor)>=BigInt(amount));}
async function release(tx,r){if(r.state!=='pending')return;const a=await tx.first('SELECT id,reserved_minor FROM pb_accounts WHERE id=? FOR UPDATE',[r.source_id]);if(!a||BigInt(a.reserved_minor)<BigInt(r.fare_minor))throw Error('Guild reservation requires reconciliation');await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor-? WHERE id=?',[r.fare_minor,r.source_id]);if(subsidies)await subsidies.release(tx,r.id);await tx.query("UPDATE pb_guild_passages SET state='expired' WHERE id=?",[r.id]);r.state='expired';}
async function reserve(tx,input,user,{price,fingerprint,destination,expiresAt,permitKey=null,offer=null,authorise=authority}){
const source=await funds(tx,user,price,true,authorise);if(!source)fail('Not enough available Dunemarks in your central personal bank account.');
// A zero fare (race world, Lobby, decree) reserves nothing and never touches a personal account.
const free=BigInt(price)===0n,source=free?await tx.first("SELECT * FROM pb_accounts WHERE system_key='sys_game_treasury' FOR UPDATE"):await funds(tx,user,price,true,authorise);if(!source)fail(free?'The Guild receiving account is unavailable.':'Not enough available Dunemarks in your central personal bank account.',free?503:409);
if(await tx.first("SELECT id FROM pb_guild_passages WHERE minecraft_uuid=? AND state='pending' FOR UPDATE",[input.uuid]))fail('Your previous passage is still awaiting arrival.');
const target=await tx.first("SELECT * FROM pb_accounts WHERE system_key='sys_game_treasury' FOR UPDATE");if(!target||target.state!=='active')fail('The Guild receiving account is unavailable.',503);
const r={id:input.requestId,actor_id:user.id,minecraft_uuid:input.uuid,house_key:input.keyId,house_version:input.version,destination,fare_minor:price,source_id:source.id,target_id:target.id,fingerprint,state:'pending',created_at:clock(),expires_at:expiresAt};
await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor+? WHERE id=?',[price,source.id]);
if(!free)await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor+? WHERE id=?',[price,source.id]);
await tx.query('INSERT INTO pb_guild_passages(id,actor_id,minecraft_uuid,house_key,house_version,destination,fare_minor,source_id,target_id,fingerprint,state,created_at,expires_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)',Object.values(r));
if(permitKey)await tx.query('INSERT INTO pb_smuggler_passages(id,permit_key) VALUES(?,?)',[r.id,permitKey]);if(offer)await subsidies.reserve(tx,r.id,offer);return r;
}
async function settle(tx,r,user,smuggler=false,authorise=authority){
if(BigInt(r.fare_minor)===0n){r.state='arrived';r.arrived_at=clock();await tx.query("UPDATE pb_guild_passages SET state='arrived',arrived_at=? WHERE id=?",[r.arrived_at,r.id]);return r;}
const accounts=await tx.query(accountSQL+' WHERE a.id IN (?,?) ORDER BY a.id FOR UPDATE',[r.source_id,r.target_id]),source=accounts.find(a=>String(a.id)===String(r.source_id)),target=accounts.find(a=>String(a.id)===String(r.target_id));
if(!ordinaryPaymentAccount(source)||!target||target.system_key!=='sys_game_treasury'||target.state!=='active'||BigInt(source.reserved_minor)<BigInt(r.fare_minor))fail('The passage payment needs review.');
if(!canDebitAccount(await authorise(user,{bank:tx}),source.entity_id,source.id))fail('Your bank account authority changed.',403);
@ -26,5 +30,14 @@ export function createGuildPassageLedger(bank,{authority,clock=Date.now,subsidie
await payments.post(tx,{id:r.id,actor_id:user.id,amount_minor:String(r.fare_minor)},source,target,true);if(subsidies)await subsidies.settle(tx,r.id,r.target_id);
r.state='arrived';r.arrived_at=clock();await tx.query("UPDATE pb_guild_passages SET state='arrived',arrived_at=? WHERE id=?",[r.arrived_at,r.id]);return r;
}
return {funds,release,reserve,settle};
// Pays a verified travel bounty using the existing fixed P&O issuance path.
async function payout(tx,{id,hunter,amountMinor,memo}){
const amount=BigInt(amountMinor);if(amount<1n||amount>2500000n)fail('Invalid bounty amount.',400);
const source=(await tx.query(accountSQL+" WHERE a.system_key='sys_payroll_po' FOR UPDATE"))[0];if(!source||source.type_code!=='979'||source.state!=='active')fail('The P&O issuer is unavailable.',503);
const target=(await tx.query(accountSQL+" WHERE e.kind='person' AND e.external_key=? AND a.system_key IS NULL ORDER BY a.id FOR UPDATE",[hunter.id])).find(ordinaryPaymentAccount);if(!target)fail('The hunter needs an active central bank account to receive a bounty.');
const orderId=creditID('travel-bounty:'+id),fingerprint=(await import('node:crypto')).createHash('sha256').update(JSON.stringify(['travel-bounty',id,hunter.id,String(amount),String(target.id)])).digest('hex');
await tx.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'guild','queued',?)",[orderId,hunter.id,source.id,target.id,fingerprint,String(amount),memo.slice(0,140),clock()]);
await postPayrollIssue(tx,{id:orderId,actor_id:hunter.id,amount_minor:String(amount)},source,target,{now:clock()});
}
return {funds,release,reserve,settle,payout};
}

View file

@ -6,7 +6,7 @@ import {WAR_EXCHANGE_SCHEMA} from './war-exchange.mjs';
import {EXCHANGE_INCENTIVE_SCHEMA} from './exchange-incentive.mjs';
import {GUILD_SUBSIDY_SCHEMA} from './guild-subsidy.mjs';
import {GUILD_ROUTE_SCHEMA} from './guild-route-bindings.mjs';
import {GUILD_SCHEMA,SMUGGLER_PASSAGE_SCHEMA} from './game-guild.mjs';
import {GUILD_SCHEMA,SMUGGLER_PASSAGE_SCHEMA,TRAVEL_LADDER_SCHEMA,TRAVEL_BOUNTY_SCHEMA,TRAVEL_BOUNTY_CLAIM_SCHEMA,TRAVEL_OPEN_PASSAGE_SCHEMA} from './game-guild.mjs';
import {HOME_SCHEMA} from './game-home.mjs';
import {DEED_PURCHASE_SCHEMA} from './deed-purchases.mjs';
import {ESTATE_SCHEMA} from './postbank-estates.mjs';
@ -31,7 +31,7 @@ export async function openPostbankDatabase(settings){
const pool=mysql.createPool({host:settings.BANK_DB_HOST||'127.0.0.1',port:Number(settings.BANK_DB_PORT||3306),database:name,user:settings.BANK_DB_USER,password:settings.BANK_DB_PASSWORD,connectionLimit:4,supportBigNumbers:true,bigNumberStrings:true,charset:'utf8mb4',connectTimeout:8000});
const api=c=>({async query(sql,args=[]){return(await c.execute(sql,args))[0];},async first(sql,args=[]){return(await c.execute(sql,args))[0][0]||null;}});
const db={async query(sql,args=[]){return(await pool.execute(sql,args))[0];},async first(sql,args=[]){return(await pool.execute(sql,args))[0][0]||null;},async transaction(work){const c=await pool.getConnection();try{await c.beginTransaction();const result=await work(api(c));await c.commit();return result;}catch(error){await c.rollback();throw error;}finally{c.release();}},async close(){await pool.end();}};
try{for(const sql of(await readFile(new URL('./postbank-schema.sql',import.meta.url),'utf8')).split(';').map(s=>s.trim()).filter(Boolean))await db.query(sql);for(const sql of [...CLAIM_PRODUCT_SCHEMA,CLAIM_RESET_SCHEMA])await db.query(sql+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(NETWORTH_SCHEMA);for(const sql of [...RIHLA_SCHEMA,...RIHLA_CASH_SCHEMA,...EVENT_SCHEMA,...WAR_EXCHANGE_SCHEMA,...WAR_MUSTER_SCHEMA,WAR_CAMPAIGN_SCHEMA,WAR_SETTLEMENT_JOB_SCHEMA,...CAMPAIGN_SCHEMA])await db.query(sql);await initializeJarvisListings(db);await db.query(DEED_PURCHASE_SCHEMA);await db.query(ESTATE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(PROMOTION_DELIVERY_SCHEMA);for(const sql of POLITICAL_JOB_BANK_SCHEMA)await db.query(sql);await db.query(JARVIS_CHARGE_SCHEMA);await db.query(GUILD_SCHEMA);for(const sql of [...GUILD_SUBSIDY_SCHEMA,...EXCHANGE_INCENTIVE_SCHEMA])await db.query(sql);await db.query(SMUGGLER_PASSAGE_SCHEMA);await db.query(GUILD_ROUTE_SCHEMA);db.guildRouteBindingsEnabled=true;await db.query(HOME_SCHEMA);await ensureClaimBatchColumns(db);await ensureCreditColumns(db);await ensurePostbankIndexes(db);await db.query(ECONOMY_OPERATION_SCHEMA);}catch(error){await pool.end();throw error;}
try{for(const sql of(await readFile(new URL('./postbank-schema.sql',import.meta.url),'utf8')).split(';').map(s=>s.trim()).filter(Boolean))await db.query(sql);for(const sql of [...CLAIM_PRODUCT_SCHEMA,CLAIM_RESET_SCHEMA])await db.query(sql+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(NETWORTH_SCHEMA);for(const sql of [...RIHLA_SCHEMA,...RIHLA_CASH_SCHEMA,...EVENT_SCHEMA,...WAR_EXCHANGE_SCHEMA,...WAR_MUSTER_SCHEMA,WAR_CAMPAIGN_SCHEMA,WAR_SETTLEMENT_JOB_SCHEMA,...CAMPAIGN_SCHEMA])await db.query(sql);await initializeJarvisListings(db);await db.query(DEED_PURCHASE_SCHEMA);await db.query(ESTATE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(PROMOTION_DELIVERY_SCHEMA);for(const sql of POLITICAL_JOB_BANK_SCHEMA)await db.query(sql);await db.query(JARVIS_CHARGE_SCHEMA);await db.query(GUILD_SCHEMA);for(const sql of [...GUILD_SUBSIDY_SCHEMA,...EXCHANGE_INCENTIVE_SCHEMA])await db.query(sql);await db.query(SMUGGLER_PASSAGE_SCHEMA);await db.query(TRAVEL_LADDER_SCHEMA);await db.query(TRAVEL_BOUNTY_SCHEMA);await db.query(TRAVEL_BOUNTY_CLAIM_SCHEMA);await db.query(TRAVEL_OPEN_PASSAGE_SCHEMA);await db.query(GUILD_ROUTE_SCHEMA);db.guildRouteBindingsEnabled=true;await db.query(HOME_SCHEMA);await ensureClaimBatchColumns(db);await ensureCreditColumns(db);await ensurePostbankIndexes(db);await db.query(ECONOMY_OPERATION_SCHEMA);}catch(error){await pool.end();throw error;}
return db;
}

View file

@ -9,7 +9,7 @@ export function createProgressionAPI(db,{quests,xp,collect=async()=>{},authentic
if(!quests)return reply({message:'The quest service is not available.'},503);
try{
if(request.method==='GET'){
if(path==='/api/progression'&&!url.search){const sources=await collect(actor);return reply({...await quests.list(actor),player:{username:user.username,name:user.display_name||user.username},sources});}
if(path==='/api/progression'&&!url.search){const sources=await collect(actor);let settled={settled:[],failed:0};try{settled=await quests.settleCompleted?.(actor)||settled;}catch{settled={settled:[],failed:1};}return reply({...await quests.list(actor),player:{username:user.username,name:user.display_name||user.username},sources,settled:settled.settled});}
if(path==='/api/progression/history'){
if([...url.searchParams.keys()].some(k=>k!=='page')||url.searchParams.getAll('page').length>1||!/^\d{1,4}$/.test(url.searchParams.get('page')||'1'))return reply({message:'Choose a valid history page.'},400);
const page=Number(url.searchParams.get('page')||1);if(page<1)return reply({message:'Choose a valid history page.'},400);

View file

@ -26,7 +26,7 @@ export const QUEST_DEFINITIONS=Object.freeze([...MISSION_BRANCHES.filter(b=>b.id
requiresAny:[],season:'S01',xp:defaultQuestXP({branch:'acquisitions',metric:`acquired-${kind}`},index),reward:null,revision:1
})))]);
export const QUEST_METRICS=Object.freeze([...new Set(QUEST_DEFINITIONS.map(d=>d.metric))]);
export const XP_POLICY=Object.freeze({version:1,base:25,seasonCap:70,season:'S01',months:6});
export const XP_POLICY=Object.freeze({version:1,base:25,seasonCap:100,season:'S01',months:6});
export function xpAtLevel(level,base=XP_POLICY.base){if(!Number.isSafeInteger(level)||level<1||level>1000||!Number.isSafeInteger(base)||base<1||base>100000)throw TypeError('Invalid XP curve');return base*level*(level-1)/2;}
export function levelForXP(xp,{base=XP_POLICY.base,cap=XP_POLICY.seasonCap}={}){if(cap===null)return unlimitedLevelForXP(xp,base);if(!Number.isSafeInteger(xp)||xp<0||!Number.isSafeInteger(cap)||cap<1||cap>1000)throw TypeError('Invalid XP state');let level=1;while(level<cap&&xp>=xpAtLevel(level+1,base))level++;return level;}
export function questPrerequisites(definition,claimed){return definition.requires.every(id=>claimed.has(id))&&(!definition.requiresAny.length||definition.requiresAny.some(id=>claimed.has(id)));}

View file

@ -155,6 +155,23 @@ export function createQuestProgression(db,keys,{definitions=QUEST_DEFINITIONS,au
await service.claim(actor,{definitionId:q.id,revision:q.revision,requestId:deterministicId('branch:'+actor.id+':'+view.season.id+':'+q.id)});completed++;
}return {completed};
},
/** Pays every quest whose verified objective is already met, including ones finished while offline.
* Only real progress counts: the XP-cap bypass that marks unfinished mandatory quests as claimable never triggers this.
* Request ids are derived from the player and quest, so a repeated sweep replays instead of paying twice. Repeatable quests stay manual. */
async settleCompleted(actor,{maxPasses=6}={}){
await player(actor);const settled=[];let failed=0;
for(let pass=0;pass<maxPasses;pass++){
const view=await service.list(actor);if(view.state!=='active')break;
const due=view.quests.filter(q=>q.state==='completed'&&q.canClaim&&q.rewardConfigured&&Number.isSafeInteger(q.revision)&&q.target>0&&q.progress>=q.target&&!types.get(q.id)?.repeatable&&!settled.some(s=>s.id===q.id));
if(!due.length)break;let paid=0;
for(const q of due)try{
await service.claim(actor,{definitionId:q.id,revision:q.revision,requestId:deterministicId('login:'+actor.id+':'+view.season.id+':'+q.id)});
settled.push({id:q.id,title:q.title,xp:q.xp,branch:q.branch});paid++;
}catch{failed++;}
if(!paid)break;
}
return {settled,failed};
},
async processCompletions({accountId=null}={}){
if(accountId!==null&&!uuid(accountId))throw TypeError('Invalid completion account');
const jobs=await db.query("SELECT * FROM jarvis_progression_outbox WHERE purpose='mandatory-completion' AND state='queued'"+(accountId?' AND account_id=?':'')+' ORDER BY created_at,id LIMIT 20',accountId?[accountId]:[]);let completed=0,failed=0;

View file

@ -0,0 +1,37 @@
import {createHash} from 'node:crypto';
import {BankError} from './postbank-service.mjs';
import {validUuid} from './game-link.mjs';
export const TRAVEL_BOUNTY_CLAIM_SCHEMA="CREATE TABLE IF NOT EXISTS pb_travel_bounty_claims(id CHAR(36) PRIMARY KEY,fingerprint CHAR(64) NOT NULL,actor_id CHAR(36) NOT NULL,killer_uuid CHAR(36) NOT NULL,victim_uuid CHAR(36) NOT NULL,server VARCHAR(32) NOT NULL,bounty_id CHAR(36) NULL,amount_minor BIGINT NOT NULL,state VARCHAR(16) NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
const worlds=new Set(['arrakis','caladan','giedi_prime','kaitain','sigma_draconis_iv']);
const fail=(message,status=409)=>{throw new BankError(message,status);};
// Native death reports retain one reference, including when there was no bounty.
// A retry cannot change its victim/world or claim a bounty created after that kill.
export function createTravelBountyClaims(bank,{resolve,clock,payout,enabled}){
return async function bountyClaim({killer,victim,requestId,server}){
if(!enabled())return{ok:true,claimed:false,disabled:true};
if(!validUuid(killer)||!validUuid(victim)||!validUuid(requestId)||!worlds.has(server))fail('Invalid travel bounty report.',400);
const hunter=await resolve(killer);if(!hunter)fail('A linked account is required to claim a bounty.',403);
const fingerprint=createHash('sha256').update(JSON.stringify([killer,victim,server])).digest('hex');
return bank.transaction(async tx=>{
const prior=await tx.first('SELECT * FROM pb_travel_bounty_claims WHERE id=? FOR UPDATE',[requestId]);
if(prior){
if(prior.actor_id!==hunter.id||prior.fingerprint!==fingerprint)fail('This kill reference was already used.');
if(prior.state==='no_bounty')return{ok:true,claimed:false,replayed:true};
const bounty=await tx.first('SELECT * FROM pb_travel_bounties WHERE id=?',[prior.bounty_id]);
if(prior.state!=='paid'||!bounty||bounty.state!=='claimed'||bounty.claim_request!==requestId||bounty.claimed_by!==hunter.id||bounty.world!==server||bounty.minecraft_uuid!==victim||Number(bounty.amount_minor)!==Number(prior.amount_minor))fail('This bounty receipt requires review.');
return{ok:true,claimed:true,replayed:true,amountMinor:Number(prior.amount_minor),traveller:bounty.traveller,world:bounty.world};
}
const bounty=killer===victim?null:await tx.first("SELECT * FROM pb_travel_bounties WHERE minecraft_uuid=? AND world=? AND state='open' AND actor_id<>? ORDER BY created_at,id LIMIT 1 FOR UPDATE",[victim,server,hunter.id]);
if(!bounty){
await tx.query("INSERT INTO pb_travel_bounty_claims(id,fingerprint,actor_id,killer_uuid,victim_uuid,server,bounty_id,amount_minor,state,created_at) VALUES(?,?,?,?,?,?,NULL,0,'no_bounty',?)",[requestId,fingerprint,hunter.id,killer,victim,server,clock()]);
return{ok:true,claimed:false};
}
await payout(tx,{id:bounty.id,hunter,amountMinor:bounty.amount_minor,memo:'Travel bounty · '+bounty.traveller});
await tx.query("UPDATE pb_travel_bounties SET state='claimed',claimed_by=?,claimed_at=?,claim_request=? WHERE id=?",[hunter.id,clock(),requestId,bounty.id]);
await tx.query("INSERT INTO pb_travel_bounty_claims(id,fingerprint,actor_id,killer_uuid,victim_uuid,server,bounty_id,amount_minor,state,created_at) VALUES(?,?,?,?,?,?,?,?,'paid',?)",[requestId,fingerprint,hunter.id,killer,victim,server,bounty.id,bounty.amount_minor,clock()]);
return{ok:true,claimed:true,amountMinor:Number(bounty.amount_minor),traveller:bounty.traveller,world:bounty.world};
});
};
}

View file

@ -0,0 +1,22 @@
// Does a traveller have a clan or company registered (Home Block) on a world? Reads the same central
// native state JARVIS projects, so the answer matches what players see in game.
const norm=value=>typeof value==='string'?value.toLowerCase().replaceAll('-','_'):'';
/** Pure matcher over a native-state snapshot. Hidden, retired and office records never count. */
export function holdsOnWorld(state,uuid,world){
const target=norm(world),who=String(uuid||'').toLowerCase();if(!target||!who)return false;
for(const group of [state?.clans,state?.companies])for(const record of group||[]){
const home=record.homeBlock;
if(record.lifecycle!=='active'||record.hidden||norm(record.homeServer)!==target||home?.source!=='minecraft'||!Number.isSafeInteger(home.revision)||home.revision<1||norm(home.worldName)!==target)continue;
if((record.members||[]).some(m=>String(m.uuid||'').toLowerCase()===who))return true;
}
return false;
}
export function createNativeHoldingCheck(db,{ttlMs=60000,clock=Date.now,read=null}={}){
let cache=null;
async function load(fresh){
const now=clock();if(!fresh&&cache&&now-cache.at<ttlMs)return cache.state;
const state=read?await read():await(await import('./game-native-state.mjs')).readGameNativeState(db);
cache={at:now,state};return state;
}
return async(_user,uuid,world,{fresh=false}={})=>holdsOnWorld(await load(fresh),uuid,world);
}

View file

@ -0,0 +1,47 @@
// Open-travel tariff. All amounts are minor units (1 DM = 100). Pure functions, no I/O.
// Race world and Lobby are free. Any other world costs 150 DM for the first trip and 10% more
// (compounding) for each later paid trip, capped at 5000 DM. The counter resets after 30 days
// without a paid trip. A clan or company registered on the destination world halves the fare.
// The bounty placed on an unsanctioned arrival is five times the fare actually paid.
export const TRAVEL_BASE_MINOR=15000;
export const TRAVEL_CAP_MINOR=500000;
export const TRAVEL_STEP_PERCENT=10;
export const TRAVEL_RESET_MS=30*24*60*60*1000;
export const BOUNTY_MULTIPLIER=5;
export const FREE_WORLDS=Object.freeze(['lobby']);
const whole=(value,max)=>Number.isSafeInteger(value)&&value>=0&&value<=max;
/** Fare in minor units for the trip number `trips` (0 = first paid trip), before any reduction. */
export function ladderFare(trips){
if(!whole(trips,1e9))throw RangeError('Invalid trip count');
let fare=TRAVEL_BASE_MINOR;
for(let i=0;i<trips&&fare<TRAVEL_CAP_MINOR;i++)fare=Math.min(TRAVEL_CAP_MINOR,Math.ceil(fare*(100+TRAVEL_STEP_PERCENT)/100));
return fare;
}
/** The counter that applies now: it falls back to zero after 30 days without a paid trip. */
export function effectiveTrips(count,lastPaidAt,now){
if(!whole(Number(count),1e9)||!Number.isSafeInteger(now))throw RangeError('Invalid travel history');
return lastPaidAt!=null&&now-Number(lastPaidAt)<TRAVEL_RESET_MS?Number(count):0;
}
/** Half price, rounded up to a whole minor unit so a fare is never rounded to zero. */
export const reducedFare=fare=>Math.ceil(fare/2);
/** Fare and bounty for a paid route. `reduced` is true when the traveller has a clan or company on that world. */
export function paidTariff({trips,reduced}){
const base=ladderFare(trips),fare=reduced?reducedFare(base):base;
return{fareMinor:fare,bountyMinor:fare*BOUNTY_MULTIPLIER,reduced:!!reduced,trip:trips+1};
}
/**
* Classifies a destination for a traveller. Free routes carry no fare and no bounty:
* Lobby, the traveller's own race world, and a destination covered by an Emperor free-passage decree.
*/
export function classifyRoute({destination,raceWorld,decree=false}){
if(FREE_WORLDS.includes(destination))return{free:true,reason:'lobby'};
if(destination===raceWorld)return{free:true,reason:'race-world'};
if(decree)return{free:true,reason:'decree'};
return{free:false,reason:'paid'};
}