MC/website/tests/game-exchange-service.test.mjs
2026-11-27 23:43:05 +00:00

43 lines
9.5 KiB
JavaScript

import {originPayload} from './native-origin-fixture.mjs';
import {entityId} from '../node/postbank-authority.mjs';
import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';import {readFileSync} from 'node:fs';
import {BankFixture} from './postbank-fixture.mjs';import {PostbankService} from '../node/postbank-service.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs';
import {createGameExchangeService} from '../node/game-exchange-service.mjs';
async function fixture(tradePolicy){
const db=new BankFixture(),users=[0,1,2].map(i=>({id:randomUUID(),username:'player_'+i,uuid:randomUUID()})),entities=users.map(u=>({id:randomUUID(),kind:'person',key:u.id,name:u.username}));let revoked=false;
const authority=async actor=>({entities:entities.map(e=>({...e,canView:e.key===actor.id,canActivate:e.key===actor.id,canPay:e.key===actor.id&&!revoked}))});
const bank=new PostbankService(db,authority);for(let i=0;i<users.length;i++)await bank.activate(users[i],{entityId:entities[i].id,packageKey:'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});
const rows=await db.query("SELECT a.id,c.entity_id FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number WHERE a.type_code='102'"),account=i=>rows.find(r=>r.entity_id===entities[i].id).id;
for(const i of[0,2])await db.query('UPDATE pb_accounts SET balance_minor=10000 WHERE id=?',[account(i)]);
db.sqlite.exec("ATTACH DATABASE ':memory:' AS dunegameplay;CREATE TABLE dunegameplay.dune_exchange_listings(id INTEGER PRIMARY KEY,seller TEXT,seller_name TEXT,origin TEXT,category TEXT,material TEXT,quantity INT,price TEXT,payload TEXT,display_name TEXT);CREATE TABLE dunegameplay.dune_exchange_sales(id INTEGER PRIMARY KEY,listing_id INT,seller TEXT,seller_name TEXT,buyer TEXT,buyer_name TEXT,material TEXT,display_name TEXT,quantity INT,unit_price TEXT,total_price TEXT,origin TEXT);");
const schema=readFileSync(new URL('../integrations/game-exchange-schema.sql',import.meta.url),'utf8').replace(/--[^\n]*\n/g,'').replaceAll('CREATE TABLE IF NOT EXISTS dune_','CREATE TABLE IF NOT EXISTS dunegameplay.dune_').replace(/,\s*INDEX exchange_delivery_pending\([^)]*\)/g,'').replaceAll(' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4','');db.sqlite.exec(schema);
await db.query('INSERT INTO dunegameplay.dune_exchange_listings VALUES(1,?,?,?,?,?,?,?,?,?)',[users[1].uuid,users[1].username,'arrakis','ores','DIAMOND',3,'21.01',null,'Diamond']);
const service=createGameExchangeService(db,{gameSchema:'dunegameplay',tradePolicy,authority,resolveSeller:async uuid=>users.find(u=>u.uuid===uuid),revalidate:async actor=>revoked?null:actor,clock:()=>1000});
return {db,users,service,account,revoke:()=>revoked=true,input:(extra={})=>({requestId:randomUUID(),listingId:'1',amount:1,priceMinor:2101,...extra})};
}
test('purchase atomically posts balanced bank entries, consumes stock and queues the exact native item once',async()=>{
const f=await fixture();try{const input=f.input(),r=await f.service.buy(f.users[0],f.users[0].uuid,input);assert.equal(r.state,'queued');assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.account(0)])).balance_minor,7899);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.account(1)])).balance_minor,2101);assert.equal((await f.db.first('SELECT SUM(amount_minor) total FROM pb_entries WHERE order_id=?',[input.requestId])).total,0);assert.equal((await f.db.first('SELECT quantity FROM dunegameplay.dune_exchange_listings WHERE id=1')).quantity,2);assert.equal((await f.service.buy(f.users[0],f.users[0].uuid,input)).replayed,true);assert.equal((await f.db.first('SELECT COUNT(*) n FROM dunegameplay.dune_exchange_deliveries')).n,1);assert.equal((await f.service.pending(f.users[0],f.users[0].uuid)).pending[0],input.requestId);await assert.rejects(f.service.buy(f.users[0],f.users[0].uuid,{...input,amount:2}),/already used/);}finally{f.db.close();}
});
test('ledger/history faults roll back payment, stock and delivery together; insufficient funds and revoked rights consume nothing',async()=>{
const f=await fixture();try{f.db.sqlite.exec("CREATE TRIGGER dunegameplay.fail_sale BEFORE INSERT ON dune_exchange_sales BEGIN SELECT RAISE(ABORT,'history fault');END;");await assert.rejects(f.service.buy(f.users[0],f.users[0].uuid,f.input()),/history fault/);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.account(0)])).balance_minor,10000);assert.equal((await f.db.first('SELECT quantity FROM dunegameplay.dune_exchange_listings')).quantity,3);assert.equal((await f.db.first('SELECT COUNT(*) n FROM dunegameplay.dune_exchange_deliveries')).n,0);f.db.sqlite.exec('DROP TRIGGER dunegameplay.fail_sale');await f.db.query('UPDATE pb_accounts SET reserved_minor=10000 WHERE id=?',[f.account(0)]);await assert.rejects(f.service.buy(f.users[0],f.users[0].uuid,f.input()),/funds/);f.revoke();await assert.rejects(f.service.buy(f.users[2],f.users[2].uuid,f.input()),/authority/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders WHERE mode=?',['exchange'])).n,0);}finally{f.db.close();}
});
test('only one buyer receives the last unit and sellers cannot buy their own stock',async()=>{
const f=await fixture();try{await assert.rejects(f.service.buy(f.users[1],f.users[1].uuid,f.input()),/own listing/);await f.db.query('UPDATE dunegameplay.dune_exchange_listings SET quantity=1');const results=await Promise.allSettled([f.service.buy(f.users[0],f.users[0].uuid,f.input()),f.service.buy(f.users[2],f.users[2].uuid,f.input())]);assert.equal(results.filter(r=>r.status==='fulfilled').length,1);assert.equal((await f.db.first('SELECT COUNT(*) n FROM dunegameplay.dune_exchange_deliveries')).n,1);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.account(1)])).balance_minor,2101);}finally{f.db.close();}
});
test('House levy debits seller proceeds exactly once on the creation world; failed journal restores bank, stock and delivery',async()=>{
const policy={caladan:{world:'caladan',house:'atreides',percent:5,taxRequestId:randomUUID()}},f=await fixture(async()=>policy);try{
const entity={id:entityId('office','leader:atreides'),kind:'office',key:'leader:atreides',name:'House',canView:true,canPay:true,canActivate:true};await new PostbankService(f.db,async()=>({entities:[entity]})).activate(f.users[0],{entityId:entity.id,packageKey:'pb_civic',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});const house=await f.db.first('SELECT a.id FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number WHERE c.entity_id=? AND a.type_code=?',[entity.id,'107']);
await f.db.query('UPDATE dunegameplay.dune_exchange_listings SET payload=?',[originPayload('caladan')]);
f.db.sqlite.exec("CREATE TRIGGER levy_failure BEFORE INSERT ON pb_exchange_levies BEGIN SELECT RAISE(ABORT,'levy journal failed');END");const input=f.input();await assert.rejects(f.service.buy(f.users[0],f.users[0].uuid,input),/levy journal failed/);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.account(0)])).balance_minor,10000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);assert.equal((await f.db.first('SELECT quantity FROM dunegameplay.dune_exchange_listings')).quantity,3);f.db.sqlite.exec('DROP TRIGGER levy_failure');
const r=await f.service.buy(f.users[0],f.users[0].uuid,input);assert.equal(r.totalMinor,2101);assert.equal(r.taxMinor,105);assert.equal(r.sellerNetMinor,1996);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[house.id])).balance_minor,105);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.account(1)])).balance_minor,1996);assert.equal((await f.db.first('SELECT SUM(amount_minor) total FROM pb_entries')).total,0);
policy.caladan.percent=1;assert.equal((await f.service.buy(f.users[0],f.users[0].uuid,input)).taxMinor,105);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_exchange_levies')).n,1);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,4);
}finally{f.db.close();}
});
test('embargo applies before pagination and purchase but preserves owner withdrawal and already paid delivery replay',async()=>{
let blocked=false;const f=await fixture(async()=>({caladan:{world:'caladan',house:'atreides',percent:0,embargoUntil:blocked?100000:0}}));try{
await f.db.query('UPDATE dunegameplay.dune_exchange_listings SET payload=?',[originPayload('caladan')]);const input=f.input();await f.service.buy(f.users[0],f.users[0].uuid,input);blocked=true;
assert.equal((await f.service.list(f.users[0],f.users[0].uuid)).listings.length,0);assert.equal((await f.service.list(f.users[1],f.users[1].uuid,{mine:true})).listings.length,1);await assert.rejects(f.service.buy(f.users[2],f.users[2].uuid,f.input()),/suspended/);assert.equal((await f.service.buy(f.users[0],f.users[0].uuid,input)).replayed,true);assert.equal((await f.service.pending(f.users[0],f.users[0].uuid)).pending.length,1);
for(let id=2;id<145;id++)await f.db.query('INSERT INTO dunegameplay.dune_exchange_listings VALUES(?,?,?,?,?,?,?,?,?,?)',[id,f.users[1].uuid,'Seller','arrakis','ores','DIAMOND',1,'1.00',originPayload('caladan'),'Diamond']);await f.db.query('UPDATE dunegameplay.dune_exchange_listings SET payload=NULL WHERE id IN (1,2,3,4,5,6,7,8,9,10,11,12,13)');const page=await f.service.list(f.users[0],f.users[0].uuid);assert.equal(page.listings.length,12);assert.equal(page.hasNext,true);assert.equal((await f.service.list(f.users[0],f.users[0].uuid,{page:1})).listings.length,1);
}finally{f.db.close();}
});