Merge pull request 'Pay Arrakis spice sales from P&O after native inventory receipt' (#534) from release/arrakis-spice-po-20261123 into main
All checks were successful
DuneRealms Web CI / web (push) Successful in 3m11s
All checks were successful
DuneRealms Web CI / web (push) Successful in 3m11s
This commit is contained in:
commit
265c77a8b5
5 changed files with 146 additions and 1 deletions
|
|
@ -35,6 +35,7 @@ export const MASTER_KEY_TEMPLATES=[
|
|||
action('progression.pol-funded-rewards','Funded Reputation reward delivery','quest',[],{webIssue:false,recordOnly:true,domainAdapter:'createPOLFundedRewards',executionStatus:'consumed-quest-outbox-only',effect:'Pay only explicitly configured and verified claim rewards from existing website treasury funds to the bound ordinary player bank account. Original QST identity prevents duplicate ledger entries; unfunded or invalid rewards remain queued.'}),
|
||||
action('progression.flight-policy','Elytra Reputation quest policy','progression-policy',[],{version:4,webIssue:false,recordOnly:true,domainAdapter:'ensureElytraQuestPolicy',executionStatus:'recorded-system-policy',effect:'Install the twelve Elytra quest reward configurations through their own policy:POL:S01:v4 instrument. Preserve existing quest settings, season dates and the separate v3 Mentat bonus instrument.'}),
|
||||
action('progression.game-observation','Native quest observation','quest-milestone',[field('eventId','Original native event UUID'),field('uuid','Linked Minecraft UUID'),field('kind','Fixed observation kind'),field('server','Native server'),field('occurredAt','Original event time','number',{min:1}),field('quantity','Native produced quantity','number',{min:1,max:64,required:false}),field('dimension','Native dimension','text',{required:false}),field('source','Fixed Elytra acquisition source','text',{required:false})],{version:4,webIssue:false,recordOnly:true,domainAdapter:'createGameQuestEventsAPI',executionStatus:'authenticated-game-service',effect:'Record confirmed Citizen briefing acknowledgements, real Arrakis visits, active survival minutes, durability-consuming equipment use and native spice drops from successful mining. Spice feeds the existing Personal and repeatable Reputation QSM adapters. Fixed world/dimension flight observations feed the Reputation Elytra branch. A committed paid delivery or natural End-ship acquisition completes only this branch, awarding its remaining rewards once. Preserve source UUID on retries. Creative/spectator gameplay and AFK/lobby movement supply no progress. A deliberate Citizen briefing acknowledgement is allowed in the lobby; other menu clicks never assert gameplay completion.'}),
|
||||
action('commerce.spice-sale','Arrakis spice sale','entity-state',[field('uuid','Linked Minecraft UUID'),field('requestId','Original sale UUID'),field('channel','Buyer','select',{options:['guild','smuggler']}),field('amount','Surrendered spice','number',{min:1,max:2368})],{webIssue:false,recordOnly:true,domainAdapter:'createGameSpiceAPI + ExchangeInventory.sellSpice',executionStatus:'authenticated-arrakis-inventory-receipt',effect:'Arrakis only. Guild and Smuggler have separate server prices; Smuggler requires an active Smuggler quest. Native Core checkpoints all surrendered raw Melange Spice before the central bank pays its personal recipient from fixed P&O, with the existing Trust levy. Original request UUID binds quote, inventory receipt and balanced bank entries. Retry and reconnect recover an unpaid receipt without taking spice or paying twice. No Vault wallet or Exchange listing.'}),
|
||||
action('progression.spice-refining','NPC spice refinement','quest-milestone',[field('uuid','Linked player UUID'),field('requestId','Original turn-in UUID'),field('definitionId','Fixed refining quest'),field('npcUuid','Nearby Arrakis Smuggler UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createGameQuestsAPI.prepare_refine + SpiceRefiner + ExchangeInventory.refine',executionStatus:'authenticated-native-npc-turn-in',effect:'Revalidate the current player and quest prerequisites, then require the physical Arrakis NPC again before consuming two real raw spice, or two refined spice and two scraps. Core checkpoints inputs, two EI outputs and a recoverable receipt atomically. Existing QSM observations award no reward until verified by the Reputation quest engine.'}),
|
||||
action('progression.earned-dm','Verified earned DM','quest-milestone',[],{webIssue:false,recordOnly:true,domainAdapter:'bankQuestIncome + progressionRuntime.collect',executionStatus:'committed-central-bank-source',effect:'Count posted wages, Exchange sale income, incoming bank transfers and verified quest treasury credits across the player’s personal central-bank accounts during the active season. Count each bank order once and preserve cumulative earnings after spending. Exclude own-account transfers, refunds, pending payments, unrelated system grants and organisation income; never use a legacy game wallet or current balance as an earnings counter.'}),
|
||||
action('progression.exchange-purchase','Committed Exchange quest evidence','quest-milestone',[],{webIssue:false,recordOnly:true,domainAdapter:'createBankQuestActivities',executionStatus:'committed-central-bank-source',effect:'Read the first settled Exchange purchase in the current season into existing Personal activity keys. Pending orders, self transfers, another customer and legacy wallets never count. Reuse the original order UUID without issuing a reward from the reader.'}),
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import {createGameSpiceAPI} from '../node/game-spice.mjs';
|
||||
import {POLITICAL_DECISION_SCHEMA,createPoliticalDecisions,createPoliticalDecisionAPI} from '../node/political-decisions.mjs';
|
||||
import {createKitsetCommerce} from '../node/kitset-commerce.mjs';
|
||||
import {createKitsetPurchaseAPI} from './kitset-purchase-api.mjs';
|
||||
|
|
@ -296,6 +297,7 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
const exchange=createExchange(db,pool);
|
||||
const kitsetCommerce=dependencies.kitsetCommerce||(dependencies.bankDatabase&&settings.DB_NAME&&settings.DUNE_INVENTORY_DATABASE_URL?createKitsetCommerce(db,dependencies.bankDatabase,settings,{gamePool:pool}):null);
|
||||
const kitsetPurchase=createKitsetPurchaseAPI(db,kitsetCommerce,settings);
|
||||
const gameSpice=createGameSpiceAPI(db,dependencies.bankDatabase||null,pool,settings,{pol:polRuntime});
|
||||
const gameExchange=createGameExchangeAPI(db,dependencies.bankDatabase||null,pool,settings,{kitsetCommerce});
|
||||
const gameKitGrants=createGameKitGrantsAPI(db,settings,{pool,commerce:kitsetCommerce,starter:gameStarter});
|
||||
let clans,companyRecruitment;const jarvis=createJarvisServices(db,dependencies.bankDatabase||null,settings,{...dependencies.jarvis,organisationKeys:dependencies.organisationKeys,deedPurchases:dependencies.deedPurchases,promotionChannels:dependencies.promotionDelivery?.channels||[],invokeClans:request=>clans(request),invokeCompany:request=>companyRecruitment(request)});companyRecruitment=createCompanyRecruitment(db,{origin,requestIntegration:jarvis.companyRequests});clans=createClans(db,{origin,onClanCreated:async({id})=>{await dependencies.boardRuntime?.boards.refresh('clan',id).catch(()=>console.error('Clan board key remains pending reconciliation'));await syncClanMailRegistry(db);},onClanDeleted:()=>syncClanMailRegistry(db),requestIntegration:jarvis.requests});const gameTickets=createGameTickets(db,settings);
|
||||
|
|
@ -361,6 +363,7 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
if(path==='/internal/game/home-relocation')return homeRelocation.cleanupAPI(request);
|
||||
if(path==='/internal/game/guild')return gameGuild(request);
|
||||
if(path==='/internal/game/home')return gameHome(request);
|
||||
if(path==='/internal/game/spice')return gameSpice(request);
|
||||
if(path==='/internal/game/exchange')return gameExchange(request);
|
||||
if(path==='/internal/game/kit-grants')return gameKitGrants(request);
|
||||
if(path==='/api/organisation-keys')return clanKeyReceipts(request);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"schemaVersion": 1,
|
||||
"sourceHash": "2e47d7c7b5acd0445c3257b5866ad9fdbbb2c6e6ee53f917f1f11aaae6d2dc3c",
|
||||
"sourceHash": "8bf70a731d1d5400867f6c5c173913b7baf5ee596bd014295589354c52df055b",
|
||||
"actions": [
|
||||
{
|
||||
"id": "clan.clear-protected-rosters",
|
||||
|
|
@ -1303,6 +1303,55 @@
|
|||
"webIssue": false,
|
||||
"recordOnly": true
|
||||
},
|
||||
{
|
||||
"id": "commerce.spice-sale",
|
||||
"label": "Progression & XP · Arrakis spice sale",
|
||||
"version": 1,
|
||||
"keyType": "entity-state",
|
||||
"fields": [
|
||||
{
|
||||
"name": "ticketId",
|
||||
"label": "Ban / support ticket ID",
|
||||
"type": "text",
|
||||
"required": true,
|
||||
"maxLength": 80
|
||||
},
|
||||
{
|
||||
"name": "uuid",
|
||||
"label": "Linked Minecraft UUID",
|
||||
"type": "text",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "requestId",
|
||||
"label": "Original sale UUID",
|
||||
"type": "text",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "channel",
|
||||
"label": "Buyer",
|
||||
"type": "select",
|
||||
"required": true,
|
||||
"options": [
|
||||
"guild",
|
||||
"smuggler"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "amount",
|
||||
"label": "Surrendered spice",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"min": 1,
|
||||
"max": 2368
|
||||
}
|
||||
],
|
||||
"effect": "Arrakis only. Guild and Smuggler have separate server prices; Smuggler requires an active Smuggler quest. Native Core checkpoints all surrendered raw Melange Spice before the central bank pays its personal recipient from fixed P&O, with the existing Trust levy. Original request UUID binds quote, inventory receipt and balanced bank entries. Retry and reconnect recover an unpaid receipt without taking spice or paying twice. No Vault wallet or Exchange listing.",
|
||||
"fixedTargets": [],
|
||||
"webIssue": false,
|
||||
"recordOnly": true
|
||||
},
|
||||
{
|
||||
"id": "progression.spice-refining",
|
||||
"label": "Progression & XP · NPC spice refinement",
|
||||
|
|
|
|||
71
website/node/game-spice.mjs
Normal file
71
website/node/game-spice.mjs
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
import {createHash} from 'node:crypto';
|
||||
import {gameAuthorized,validUuid,json} from './game-link.mjs';
|
||||
import {postPayrollIssue} from './postbank-payroll-issuer.mjs';
|
||||
import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs';
|
||||
|
||||
// Preserve the existing 15 DM commodity price and sanctioned Guild +33%.
|
||||
// A quote is not payment: only Core's committed inventory receipt earns DM.
|
||||
export const SPICE_POLICY=Object.freeze({version:1,guild:1995,smuggler:1500,levyBasisPoints:121});
|
||||
export const spiceFingerprint=(uuid,channel,amount)=>createHash('sha256').update(`spice-sale-v1\n${uuid}\n${channel}\n${amount}`).digest('hex');
|
||||
export function spiceQuote(channel,amount){
|
||||
if(!['guild','smuggler'].includes(channel)||!Number.isInteger(amount)||amount<1||amount>2368)throw Error('Choose between 1 and 2368 spice.');
|
||||
const gross=SPICE_POLICY[channel]*amount,tax=Math.round(gross*SPICE_POLICY.levyBasisPoints/10000);
|
||||
return {channel,amount,unitMinor:SPICE_POLICY[channel],grossMinor:gross,taxMinor:tax,netMinor:gross-tax};
|
||||
}
|
||||
export const activeSmugglerQuest=journal=>!!journal?.quests?.some(q=>q.state==='active'&&(q.branch==='smugglers'||q.id?.startsWith('RPT-CARGO-')));
|
||||
const accounts=`SELECT a.*,e.active entity_active,p.state package_state FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id JOIN pb_packages p ON p.id=a.package_id WHERE e.kind='person' AND e.external_key=? AND a.type_code IN ('102','103','104','108') ORDER BY CASE WHEN a.type_code='102' THEN 0 ELSE 1 END,a.id`;
|
||||
export function createGameSpiceAPI(db,bank,pool,settings,{pol,clock=Date.now,verifyStorage}={}){
|
||||
let storage,schema;
|
||||
const first=(s,q,a=[])=>s.first?s.first(q,a):s.query(q,a).then(rows=>rows[0]);
|
||||
async function ready(){if(!storage)storage=(async()=>{
|
||||
if(verifyStorage){schema=await verifyStorage();return;}
|
||||
const url=new URL(settings.DUNE_INVENTORY_DATABASE_URL||'');schema=url.pathname.slice(1);
|
||||
if(!bank||pool?.dialect!=='mysql'||url.protocol!=='mysql:'||!/^[a-z][a-z0-9_]{2,63}$/.test(schema))throw Error('Spice banking unavailable.');
|
||||
const q='SELECT @@hostname host,@@port port,@@server_id server_id',b=await bank.first(q),g=(await pool.query(q)).rows[0];
|
||||
if(!g||['host','port','server_id'].some(k=>String(b[k])!==String(g[k])))throw Error('Spice banking unavailable.');
|
||||
const engine=await bank.first('SELECT ENGINE engine FROM information_schema.TABLES WHERE TABLE_SCHEMA=? AND TABLE_NAME=?',[schema,'dune_exchange_inventory_ops']);
|
||||
if(engine?.engine!=='InnoDB')throw Error('Spice inventory checkpoint unavailable.');
|
||||
await bank.query(`CREATE TABLE IF NOT EXISTS pb_spice_sales (id CHAR(36) PRIMARY KEY,actor_id CHAR(36) NOT NULL,player_uuid CHAR(36) NOT NULL,channel VARCHAR(16) NOT NULL,quantity INT NOT NULL,fingerprint CHAR(64) NOT NULL,created_at BIGINT NOT NULL,expires_at BIGINT NOT NULL,INDEX(player_uuid,created_at)) ENGINE=InnoDB`);
|
||||
})().catch(e=>{storage=null;throw e;});return storage;}
|
||||
async function actor(uuid){const rows=await db.query("SELECT a.id,a.username,a.role FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id 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]:null;}
|
||||
async function smuggler(user){if(!pol?.quests)return false;return activeSmugglerQuest(await pol.quests.list({...user,revalidate:async()=>user}));}
|
||||
async function recipient(store,user){return (await store.query(accounts,[user.id])).find(ordinaryPaymentAccount);}
|
||||
return async request=>{
|
||||
if(!gameAuthorized(request,settings))return json({message:'Unauthorized'},401);
|
||||
const url=new URL(request.url);if(request.method!=='POST'||url.pathname!=='/internal/game/spice'||url.search)return json({message:'Spice route unavailable.'},404);
|
||||
if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return json({message:'JSON required.'},415);
|
||||
let input;try{const reader=request.body?.getReader();if(!reader)throw Error();let size=0,parts=[];try{for(;;){const {done,value}=await reader.read();if(done)break;size+=value.byteLength;if(size>2048){await reader.cancel();throw Error();}parts.push(value);}}finally{reader.releaseLock();}input=JSON.parse(Buffer.concat(parts).toString());}catch{return json({message:'Invalid spice request.'},400);}
|
||||
const fields={read:['action','uuid','server'],pending:['action','uuid','server'],prepare:['action','uuid','server','requestId','channel','amount','confirmed'],settle:['action','uuid','server','requestId']}[input?.action];
|
||||
if(!fields||Object.keys(input).length!==fields.length||!fields.every(k=>Object.hasOwn(input,k))||!validUuid(input.uuid)||input.server!=='arrakis'||!['read','pending'].includes(input.action)&&!validUuid(input.requestId))return json({message:'Spice sales are available on Arrakis only.'},400);
|
||||
try{
|
||||
await ready();const user=await actor(input.uuid);if(!user)return json({message:'Link your personal account first.'},403);
|
||||
if(input.action==='read')return json({ok:true,playerUuid:input.uuid,policy:SPICE_POLICY,smugglerEnabled:await smuggler(user),hasAccount:!!await recipient(bank,user)});
|
||||
if(input.action==='pending'){const rows=await bank.query('SELECT s.id FROM pb_spice_sales s JOIN `'+schema+'`.dune_exchange_inventory_ops r ON r.id=s.id LEFT JOIN pb_orders o ON o.id=s.id WHERE s.player_uuid=? AND s.actor_id=? AND o.id IS NULL ORDER BY s.created_at LIMIT 16',[input.uuid,user.id]);return json({ok:true,pending:rows.map(r=>r.id)});}
|
||||
if(input.action==='prepare'){
|
||||
if(input.confirmed!==true)throw Error('Confirm the sale first.');const quote=spiceQuote(input.channel,input.amount);
|
||||
if(input.channel==='smuggler'&&!await smuggler(user))return json({message:'Start a Smuggler quest before selling to Esmar Tuek.'},403);
|
||||
if(!await recipient(bank,user))throw Error('An active personal bank account is required.');
|
||||
const fingerprint=spiceFingerprint(input.uuid,input.channel,input.amount),now=clock();
|
||||
const row=await bank.transaction(async tx=>{const prior=await tx.first('SELECT * FROM pb_spice_sales WHERE id=? FOR UPDATE',[input.requestId]);if(prior){if(prior.actor_id!==user.id||prior.player_uuid!==input.uuid||prior.fingerprint!==fingerprint)throw Error('Sale reference conflict.');return prior;}await tx.query('INSERT INTO pb_spice_sales(id,actor_id,player_uuid,channel,quantity,fingerprint,created_at,expires_at) VALUES(?,?,?,?,?,?,?,?)',[input.requestId,user.id,input.uuid,input.channel,input.amount,fingerprint,now,now+30000]);return {expires_at:now+30000};});
|
||||
return json({ok:true,allowed:true,action:'prepare_spice',playerUuid:input.uuid,requestId:input.requestId,fingerprint,expiresAt:Number(row.expires_at),...quote});
|
||||
}
|
||||
return json(await bank.transaction(async tx=>{
|
||||
const sale=await tx.first('SELECT * FROM pb_spice_sales WHERE id=? FOR UPDATE',[input.requestId]);if(!sale||sale.actor_id!==user.id||sale.player_uuid!==input.uuid)throw Error('Spice receipt unavailable.');
|
||||
const quote=spiceQuote(sale.channel,Number(sale.quantity));
|
||||
const receipt=await tx.first('SELECT * FROM `'+schema+'`.dune_exchange_inventory_ops WHERE id=? FOR UPDATE',[sale.id]);
|
||||
if(!receipt||receipt.actor_uuid!==input.uuid||receipt.kind!=='spice-'+sale.channel||Number(receipt.listing_id)!==quote.amount||receipt.fingerprint!==sale.fingerprint||Number(receipt.created_at)<Number(sale.created_at)-5000||Number(receipt.created_at)>Number(sale.expires_at))throw Error('Spice has not been surrendered to the inventory checkpoint.');
|
||||
const previous=await tx.first('SELECT * FROM pb_orders WHERE id=? FOR UPDATE',[sale.id]);
|
||||
if(previous){if(previous.state!=='posted'||previous.actor_id!==user.id||previous.fingerprint!==sale.fingerprint||BigInt(previous.amount_minor)!==BigInt(quote.netMinor))throw Error('Spice payment requires review.');return {ok:true,replayed:true,...quote};}
|
||||
// Lock all three accounts in stable order before any double-entry posting.
|
||||
const target=await recipient(tx,user);if(!target)throw Error('Your bank account is unavailable. Spice payment remains owed.');
|
||||
const rows=await tx.query("SELECT * FROM pb_accounts WHERE system_key IN ('sys_payroll_po','sys_tax_treasury') OR id=? ORDER BY id FOR UPDATE",[target.id]);
|
||||
const po=rows.find(a=>a.system_key==='sys_payroll_po'),tax=rows.find(a=>a.system_key==='sys_tax_treasury'),destination=rows.find(a=>String(a.id)===String(target.id));
|
||||
if(!po||!tax||!destination)throw Error('P&O payout accounts unavailable.');
|
||||
const post=async(id,to,amount,fingerprint,memo)=>{await tx.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'spice','queued',?)",[id,user.id,po.id,to.id,fingerprint,String(amount),memo,clock()]);await postPayrollIssue(tx,{id,actor_id:user.id,amount_minor:String(amount)},po,to,{now:clock()});po.balance_minor=String(BigInt(po.balance_minor)-BigInt(amount));};
|
||||
await post(sale.id,destination,quote.netMinor,sale.fingerprint,'Spice sale · '+sale.channel+' · '+quote.amount);
|
||||
if(quote.taxMinor){const h=createHash('sha256').update('spice-tax:'+sale.id).digest('hex'),id=h.slice(0,8)+'-'+h.slice(8,12)+'-5'+h.slice(13,16)+'-a'+h.slice(17,20)+'-'+h.slice(20,32);await post(id,tax,quote.taxMinor,sale.fingerprint,'Spice sale · Trust levy');}
|
||||
return {ok:true,replayed:false,...quote};
|
||||
}));
|
||||
}catch(error){return json({message:/^(Choose|Confirm|Start|An active|Your bank|Spice |Sale reference|P&O)/.test(error.message||'')?error.message:'Spice banking is temporarily unavailable. Committed sales remain payable.'},409);}
|
||||
};
|
||||
}
|
||||
21
website/tests/game-spice.test.mjs
Normal file
21
website/tests/game-spice.test.mjs
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';
|
||||
import {BankFixture} from './postbank-fixture.mjs';import {PostbankService} from '../node/postbank-service.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs';
|
||||
import {createGameSpiceAPI,spiceFingerprint,spiceQuote,activeSmugglerQuest} from '../node/game-spice.mjs';
|
||||
async function fixture(){
|
||||
const bank=new BankFixture(),user={id:randomUUID(),username:'Miner'},uuid=randomUUID(),entity={id:randomUUID(),kind:'person',key:user.id,name:user.username};let active=false,now=100000;
|
||||
await new PostbankService(bank,async()=>({entities:[{...entity,canView:true,canActivate:true,canPay:true}]})).activate(user,{entityId:entity.id,packageKey:'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});
|
||||
const target=await bank.first("SELECT * FROM pb_accounts WHERE type_code='102'");
|
||||
for(const key of ['sys_payroll_po','sys_tax_treasury'])await bank.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,state,created_at) VALUES(?,'979',?,0,'active',1)",[key,key]);
|
||||
bank.sqlite.exec("ATTACH DATABASE ':memory:' AS game;CREATE TABLE game.dune_exchange_inventory_ops(id TEXT PRIMARY KEY,actor_uuid TEXT,kind TEXT,fingerprint TEXT,listing_id INT,created_at INT);CREATE TABLE pb_spice_sales(id TEXT PRIMARY KEY,actor_id TEXT,player_uuid TEXT,channel TEXT,quantity INT,fingerprint TEXT,created_at INT,expires_at INT);");
|
||||
const db={query:async(sql,args)=>args[0]===uuid?[user]:[]},secret='spice-api-test-secret-123456789012345';
|
||||
const api=createGameSpiceAPI(db,bank,null,{GAME_LINK_SECRET:secret},{verifyStorage:async()=> 'game',clock:()=>now,pol:{quests:{list:async()=>({quests:[{id:'POL-SMUGGLERS-02',branch:'smugglers',state:active?'active':'claimed'}]})}}});
|
||||
const call=async(input,token=secret)=>{const response=await api(new Request('https://cp.dunerealms.com/internal/game/spice',{method:'POST',headers:{authorization:'Bearer '+token,'content-type':'application/json'},body:JSON.stringify({uuid,server:'arrakis',...input})}));return {status:response.status,body:await response.json()};};
|
||||
const prepare=(channel='guild')=>({action:'prepare',requestId:randomUUID(),channel,amount:64,confirmed:true});
|
||||
async function receipt(input){await bank.query('INSERT INTO game.dune_exchange_inventory_ops VALUES(?,?,?,?,?,?)',[input.requestId,uuid,'spice-'+input.channel,spiceFingerprint(uuid,input.channel,input.amount),input.amount,now+100]);}
|
||||
return {bank,user,uuid,target,call,prepare,receipt,active:()=>{active=true;},expire:()=>{now+=60000;}};
|
||||
}
|
||||
test('quotes are bounded and Smuggler access requires an actually active quest',()=>{assert.throws(()=>spiceQuote('guild',0));assert.throws(()=>spiceQuote('guild',2369));assert.throws(()=>spiceQuote('exchange',1));assert.notEqual(spiceQuote('guild',64).netMinor,spiceQuote('smuggler',64).netMinor);assert.equal(activeSmugglerQuest({quests:[{branch:'smugglers',state:'available'}]}),false);assert.equal(activeSmugglerQuest({quests:[{branch:'smugglers',state:'claimed'}]}),false);assert.equal(activeSmugglerQuest({quests:[{branch:'smugglers',state:'active'}]}),true);});
|
||||
test('Arrakis-only and authenticated; locked Smuggler cannot prepare and quotes do not pay',async()=>{const f=await fixture();try{assert.equal((await f.call({action:'read'},'bad')).status,401);assert.equal((await f.call({action:'read',server:'caladan'})).status,400);assert.equal((await f.call(f.prepare('smuggler'))).status,403);f.active();assert.equal((await f.call(f.prepare('smuggler'))).status,200);assert.equal((await f.bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,0);}finally{f.bank.close();}});
|
||||
test('only a committed exact inventory receipt pays; retry posts once with balanced P&O and tax entries',async()=>{const f=await fixture();try{const input=f.prepare();assert.equal((await f.call(input)).status,200);assert.equal((await f.call({action:'settle',requestId:input.requestId})).status,409);await f.receipt(input);const paid=await f.call({action:'settle',requestId:input.requestId});assert.equal(paid.status,200,JSON.stringify(paid.body));assert.equal((await f.call({action:'settle',requestId:input.requestId})).body.replayed,true);assert.equal(Number((await f.bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor),spiceQuote('guild',64).netMinor);assert.equal(Number((await f.bank.first('SELECT SUM(amount_minor) n FROM pb_entries')).n),0);assert.equal(Number((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n),2);}finally{f.bank.close();}});
|
||||
test('recoverable receipt remains payable after quote expiry; forged quantity or actor earns nothing',async()=>{const f=await fixture();try{const input=f.prepare();await f.call(input);await f.receipt(input);f.expire();assert.deepEqual((await f.call({action:'pending'})).body.pending,[input.requestId]);assert.equal((await f.call({action:'settle',requestId:input.requestId,uuid:randomUUID()})).status,403);await f.bank.query('UPDATE game.dune_exchange_inventory_ops SET listing_id=65');assert.equal((await f.call({action:'settle',requestId:input.requestId})).status,409);await f.bank.query('UPDATE game.dune_exchange_inventory_ops SET listing_id=64');assert.equal((await f.call({action:'settle',requestId:input.requestId})).status,200);}finally{f.bank.close();}});
|
||||
test('a ledger failure rolls back the whole payout and remains recoverable',async()=>{const f=await fixture();try{const input=f.prepare();await f.call(input);await f.receipt(input);f.bank.sqlite.exec("CREATE TRIGGER fail_tax BEFORE INSERT ON pb_orders WHEN NEW.memo='Spice sale · Trust levy' BEGIN SELECT RAISE(ABORT,'tax fault');END;");assert.equal((await f.call({action:'settle',requestId:input.requestId})).status,409);assert.equal(Number((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n),0);assert.equal(Number((await f.bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor),0);f.bank.sqlite.exec('DROP TRIGGER fail_tax');assert.equal((await f.call({action:'settle',requestId:input.requestId})).status,200);}finally{f.bank.close();}});
|
||||
Loading…
Reference in a new issue

Staff