web/website/tests/game-spice.test.mjs
2026-11-27 23:43:05 +00:00

38 lines
9.7 KiB
JavaScript

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({readOnlyReceipts=false,recordSale}={}){
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,quest_reported_at INT,quote_json TEXT);");
const db={query:async(sql,args)=>args[0]===uuid?[user]:[]},secret='spice-api-test-secret-123456789012345';
const receiptReader={query:bank.query.bind(bank),first:bank.first.bind(bank),transaction:work=>bank.transaction(tx=>work({...tx,first(sql,args){if(sql.includes('dune_exchange_inventory_ops')&&/FOR\s+(UPDATE|SHARE)|LOCK\s+IN/i.test(sql))throw Error('Inventory receipts are read-only');return tx.first(sql,args);}}))};
const api=createGameSpiceAPI(db,readOnlyReceipts?receiptReader:bank,null,{GAME_LINK_SECRET:secret},{verifyStorage:async()=> 'game',clock:()=>now,recordSale,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('prepared sale keeps its accepted price after a Federal Reserve repricing',async()=>{
const f=await fixture();try{const input=f.prepare(),accepted=await f.call(input);assert.equal(accepted.status,200);
await f.bank.query('INSERT INTO pb_financial_policies(policy_key,policy_json,version,updated_by,updated_at) VALUES(?,?,1,?,1)',['federal_reserve',JSON.stringify({enabled:true,lastDay:'2026-11-25',prices:{'spice.guild':2094,'spice.smuggler':1575}}),f.user.id]);
assert.equal((await f.call(input)).body.netMinor,accepted.body.netMinor);await f.receipt(input);const paid=await f.call({action:'settle',requestId:input.requestId});assert.equal(paid.status,200);assert.equal(Number((await f.bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor),spiceQuote('guild',64).netMinor);
}finally{f.bank.close();}
});
test('quotes are bounded and Smuggler access requires an actually active quest',()=>{assert.throws(()=>spiceQuote('guild',0));assert.throws(()=>spiceQuote('guild',21313));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('an expired committed sale settles once with read-only inventory access',async()=>{const f=await fixture({readOnlyReceipts:true});try{const input=f.prepare();assert.equal((await f.call(input)).status,200);await f.receipt(input);f.expire();assert.equal((await f.call({action:'settle',requestId:input.requestId})).status,200);assert.equal((await f.call({action:'settle',requestId:input.requestId})).body.replayed,true);assert.equal(Number((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n),2);}finally{f.bank.close();}});
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();}});
test('paid spice is reported to quests only after the ledger commits and only once',async()=>{
let reports=0,f;f=await fixture({recordSale:async(user,input)=>{reports++;assert.equal(user.id,f.user.id);assert.equal((await f.bank.first('SELECT state FROM pb_orders WHERE id=?',[input.requestId])).state,'posted');}});
try{const input=f.prepare();await f.call(input);assert.equal((await f.call({action:'settle',requestId:input.requestId})).status,409);assert.equal(reports,0);await f.receipt(input);assert.equal((await f.call({action:'settle',requestId:input.requestId})).status,200);await f.call({action:'settle',requestId:input.requestId});assert.equal(reports,1);assert.deepEqual((await f.call({action:'pending'})).body.pending,[]);}finally{f.bank.close();}
});
test('quest reporting failure preserves the payment and reconnect retries evidence without paying again',async()=>{
let fail=true,reports=0;const f=await fixture({recordSale:async()=>{reports++;if(fail)throw Error('Quest store unavailable');}});
try{const input=f.prepare();await f.call(input);await f.receipt(input);const paid=await f.call({action:'settle',requestId:input.requestId});assert.equal(paid.status,200);assert.equal(paid.body.questProgressPending,true);assert.deepEqual((await f.call({action:'pending'})).body.pending,[input.requestId]);const balance=(await f.bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor;fail=false;const recovered=await f.call({action:'settle',requestId:input.requestId});assert.equal(recovered.body.replayed,true);assert.equal(reports,2);assert.equal((await f.bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,balance);assert.deepEqual((await f.call({action:'pending'})).body.pending,[]);assert.equal(Number((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n),2);}finally{f.bank.close();}
});