web/website/node/imperial-raid-commerce.mjs

121 lines
14 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {createHash} from 'node:crypto';
import {atomicBankAccess} from './atomic-bank-access.mjs';
import {boardReadStore} from './board-deed-source.mjs';
import {clanWarAuthority} from './clan-deeds.mjs';
import {readGameNativeState} from './game-native-state.mjs';
import {clanWarBranch,buildClanCampaignSnapshot} from './war-rosters.mjs';
import {createPostbankAuthority,entityId} from './postbank-authority.mjs';
import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs';
import {canDebitAccount} from './postbank-authorisations.mjs';
import {PostbankPayments} from './postbank-payments.mjs';
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
import {lockWarCalendar} from './war-muster.mjs';
import {paxBlocksWar} from './imperial-pax.mjs';
const fail=(message,status=409)=>{throw Object.assign(Error(message),{status});};
const accountsSQL='SELECT a.*,c.entity_id,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 tables=['jarvis_imperial_raid_guard','jarvis_imperial_raid_orders','jarvis_imperial_raid_clans','jarvis_imperial_raid_events','jarvis_imperial_raid_jobs','organisation_keys','organisation_key_events','codex_instance_editions','site_accounts','site_game_links','site_clans','site_clan_deeds','site_clan_charters','site_clan_members','site_claim_registry','jarvis_pol_progression_seasons'];
export function raidRecoveryId(orderId){const h=createHash('sha256').update('imperial-raid-refund:'+orderId).digest('hex');return h.slice(0,8)+'-'+h.slice(8,12)+'-5'+h.slice(13,16)+'-8'+h.slice(17,20)+'-'+h.slice(20,32);}
export function createImperialRaidCommerce(raw,bank,keys,{clock=Date.now,verifyStorage,readState=readGameNativeState,warAuthority=clanWarAuthority,bankAuthority=createPostbankAuthority,verifyCampaigns=true}={}){
const db=boardReadStore(raw,raw),banking=atomicBankAccess(db,bank,{verifyStorage,centralTables:tables,bankTables:verifyCampaigns?['jarvis_war_campaigns','jarvis_war_calendar_guard','jarvis_war_proposals','jarvis_war_slots']:[]});
const reader=tx=>{const r=boardReadStore(tx,raw);r.readSnapshot=undefined;return r;};
async function resolveActor(tx,uuid,{lock=false}={}){
const rows=await tx.query('SELECT a.id,a.username,a.role,a.password_hash FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE l.minecraft_uuid=?'+(lock?' FOR UPDATE':''),[uuid]);
if(rows.length!==1||String(rows[0].password_hash).startsWith('!')||['system_account','official','official_account','memorial'].includes(rows[0].role))fail('Link an active personal Minecraft account first.',403);
return rows[0];
}
async function funding(tx,actor,clanId){
const r=reader(tx),b=banking.view(r),rights=await bankAuthority(r,{bank:b,clock})(actor,{bank:b});
return (await b.query(accountsSQL+' WHERE c.entity_id=? AND a.system_key IS NULL ORDER BY a.id',[entityId('clan',clanId)])).filter(a=>ordinaryPaymentAccount(a)&&canDebitAccount(rights,a.entity_id,a.id));
}
async function resolveContext(tx,input,{lock=false}={}){
const actor=await resolveActor(tx,input.uuid,{lock});
if(lock){
const ids=[input.orderingClanId,input.targetClanId].sort();
await tx.query('SELECT id FROM site_clans WHERE id IN (?,?) ORDER BY id FOR UPDATE',ids);
await tx.query('SELECT clan_id FROM site_clan_deeds WHERE clan_id IN (?,?) ORDER BY clan_id FOR UPDATE',ids);
await tx.query('SELECT clan_id FROM site_clan_charters WHERE clan_id IN (?,?) ORDER BY clan_id FOR UPDATE',ids);
await tx.query('SELECT user_id FROM site_clan_members WHERE clan_id IN (?,?) ORDER BY clan_id,user_id FOR UPDATE',ids);
await tx.query("SELECT organisation_id FROM site_claim_registry WHERE organisation_kind='clan' AND organisation_id IN (?,?) ORDER BY organisation_id FOR UPDATE",ids);
}
const r=reader(tx),rights=await warAuthority(r,actor.id,input.orderingClanId);
if(!rights.canManageWar)fail('Current clan war authority is required.',403);
const state=await readState(r,{clock}),a=state.clans.find(c=>c.id===input.orderingClanId),b=state.clans.find(c=>c.id===input.targetClanId);
if(!a||!b||a.lifecycle!=='active'||b.lifecycle!=='active'||a.protected||b.protected||a.hidden||b.hidden)fail('Choose two active unprotected rival clans.');
const branchA=new Set(clanWarBranch(state.clans,a.id).map(c=>c.id)),branchB=new Set(clanWarBranch(state.clans,b.id).map(c=>c.id));
if([...branchA].some(id=>branchB.has(id)))fail('Members of the same clan hierarchy cannot order raids against each other.');
if(b.homeServer!==input.server||!b.homeBlock||b.homeBlock.source!=='minecraft')fail('Travel to the target clan’s registered world before ordering this raid.');
if((state.wars||[]).some(w=>(w.active||w.reserved)&&[w.attackerId,w.defenderId].some(id=>branchA.has(id)||branchB.has(id))))fail('A participating clan already has a scheduled or active war.');
if(verifyCampaigns){
const campaigns=await banking.view(r).query('SELECT snapshot_json FROM jarvis_war_campaigns WHERE ends_at>? ORDER BY starts_at,id LIMIT 501',[clock()]);
if(campaigns.length>500)fail('The war register requires reconciliation.');
for(const row of campaigns){const c=JSON.parse(row.snapshot_json);if(c.cancelledAt==null&&!c.winnerSideId&&c.teams.some(t=>(t.clanIds||[t.id]).some(id=>branchA.has(id)||branchB.has(id))))fail('A participating clan already has a scheduled or active campaign.');}
}
const accounts=await funding(r,actor,a.id);
if(!accounts.length)fail('This clan needs a current authorised clan bank account. Personal accounts cannot fund Imperial raids.',403);
const charters=await r.query('SELECT clan_id,key_id FROM site_clan_charters WHERE clan_id IN (?,?) ORDER BY clan_id',[a.id,b.id]);
if(charters.length!==2)fail('Both current clan charters are required.');
const seasons=await r.query("SELECT season_id FROM jarvis_pol_progression_seasons WHERE state='active' AND starts_at<=? AND ends_at>?",[clock(),clock()]);
if(seasons.length!==1)fail('A single active Reputation season is required before accepting a raid.');
const seasonId=seasons[0].season_id;
return {seasonId,orderingClanName:a.name,targetClanName:b.name,home:{worldUuid:b.homeBlock.worldUuid.toLowerCase(),position:structuredClone(b.homeBlock.position),claimRevision:b.claimRevision},authority:{actorId:actor.id,orderingVersion:a.version,targetVersion:b.version,orderingOwnerUuid:a.ownerUuid,targetOwnerUuid:b.ownerUuid,charters,seasonId},accounts:accounts.map(a=>({id:String(a.id),name:a.display_name,availableMinor:String(BigInt(a.balance_minor)-BigInt(a.reserved_minor))}))};
}
async function issue(tx,scopeId,authorize){
if(!keys)fail('JARVIS raid receipts are unavailable.',503);
const existing=await tx.first("SELECT id FROM organisation_keys WHERE account_id=? AND key_type='entity-state' AND scope_id=? FOR UPDATE",[STAFF_OFFICE_ACCOUNT_ID,scopeId]);
if(existing)fail('The original raid receipt requires reconciliation.');
return keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId,transactionStore:reader(tx),authorize});
}
async function charge(tx,p){
const r=reader(tx),b=banking.view(r),actor=await resolveActor(r,p.actorUuid,{lock:true});
if(actor.id!==p.actorId)fail('The original raid actor changed.',403);
if(verifyCampaigns){
// The ORIGINAL war booking lock also serializes this paid acceptance. Repeat
// the campaign/slot check with current locking reads after obtaining it.
await lockWarCalendar(b);
const state=await readState(r,{clock}),clans=new Set([p.orderingClanId,p.targetClanId].flatMap(id=>clanWarBranch(state.clans,id).map(c=>c.id)));
const campaigns=await b.query('SELECT snapshot_json FROM jarvis_war_campaigns WHERE ends_at>? ORDER BY starts_at,id LIMIT 501 FOR UPDATE',[clock()]);if(campaigns.length>500)fail('The war register requires reconciliation.');
for(const row of campaigns){const c=JSON.parse(row.snapshot_json);if(c.cancelledAt==null&&!c.winnerSideId&&c.teams.some(t=>(t.clanIds||[t.id]).some(id=>clans.has(id))))fail('A participating clan already has a scheduled or active campaign.');}
const slots=await b.query("SELECT p.parties_json FROM jarvis_war_proposals p JOIN jarvis_war_slots s ON s.proposal_id=p.id WHERE p.state='scheduled' AND s.ends_at>? ORDER BY p.id,s.party_key LIMIT 501 FOR UPDATE",[clock()]);if(slots.length>500)fail('The war calendar requires reconciliation.');
if(slots.some(row=>JSON.parse(row.parties_json).some(party=>party.kind==='clan'&&clanWarBranch(state.clans,party.id).some(c=>clans.has(c.id)))))fail('A participating clan already has a scheduled war.');
if(p.retaliationLevel===3){
const parties=[p.orderingClanId,p.targetClanId].map(id=>({kind:'clan',id})),earliest=clock()+600000;
if(await paxBlocksWar(r,parties,{startsAt:earliest,endsAt:earliest+3600000},clock()))fail('The original war peace rules currently protect this escalation.');
const charters=await r.query('SELECT clan_id,key_id FROM site_clan_charters ORDER BY clan_id LIMIT 501');if(charters.length>500)fail('The charter register requires reconciliation.');
// Verify both COMPLETE rosters and registered provinces before accepting the
// escalation fee. The real paid marker is issued only by the commit below.
buildClanCampaignSnapshot(state,parties,charters,{}, {},[],{raidEscalation:{orderId:p.id,chainId:p.chainId,receiptKeyId:p.preflightNonce}});
}
}
const tax=await b.first("SELECT id FROM pb_accounts WHERE system_key='sys_tax_treasury'");if(!tax)fail('The existing Tax treasury is unavailable.',503);
const meta=await b.first(accountsSQL+' WHERE a.id=?',[p.sourceAccountId]);if(meta?.entity_id!==entityId('clan',p.orderingClanId))fail('The original clan bank account is required.',403);
await b.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[meta.entity_id]);
await b.query('SELECT id FROM pb_accounts WHERE id IN (?,?) ORDER BY id FOR UPDATE',[p.sourceAccountId,tax.id]);
await b.query('SELECT id FROM pb_account_authorisations WHERE account_id=? ORDER BY id FOR UPDATE',[p.sourceAccountId]);
const source=(await funding(r,actor,p.orderingClanId)).find(a=>String(a.id)===p.sourceAccountId),target=await b.first('SELECT * FROM pb_accounts WHERE id=?',[tax.id]),amount=BigInt(p.feeMinor);
if(!source||!target||target.state!=='active'||target.system_key!=='sys_tax_treasury'||BigInt(source.balance_minor)-BigInt(source.reserved_minor)<amount||BigInt(target.balance_minor)+amount>9223372036854775807n)fail('Insufficient authorised clan funds or unavailable Tax treasury.');
if(await b.first('SELECT id FROM pb_orders WHERE id=? FOR UPDATE',[p.id]))fail('This bank reference already belongs to another operation.');
const key=await issue(r,'state:imperial-raid:'+p.id,async(_tx,{keyId})=>{
await b.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'system','queued',?)",[p.id,actor.id,source.id,target.id,p.inputHash,p.feeMinor,'Imperial raid '+p.id,clock()]);
await new PostbankPayments(bank,null,{clock}).post(b,{id:p.id,actor_id:actor.id,amount_minor:p.feeMinor},source,target,false);
});
return {receiptKeyId:key.id,bankOrderId:p.id};
}
async function refund(rawTx,row){
const tx=reader(rawTx),b=banking.view(tx),p=JSON.parse(row.accepted_json),outcome=JSON.parse(row.outcome_json),refundId=raidRecoveryId(row.id),scope='state:imperial-raid-refund:'+row.id;
if(row.state!=='neutral'||row.war_campaign_id||!['spawn_failed','interrupted','cancelled'].includes(outcome.outcome)||p.bankOrderId!==row.id)fail('A bound refundable neutral paid raid is required.');
const original=await b.first('SELECT * FROM pb_orders WHERE id=? FOR UPDATE',[p.bankOrderId]);
if(!original||original.state!=='posted'||String(original.source_id)!==p.sourceAccountId||String(original.amount_minor)!==p.feeMinor||original.fingerprint!==p.inputHash||original.actor_id!==row.actor_id)fail('The original posted raid payment requires reconciliation.');
const previous=await b.first('SELECT * FROM pb_orders WHERE id=? FOR UPDATE',[refundId]),priorKey=await tx.first("SELECT id FROM organisation_keys WHERE account_id=? AND key_type='entity-state' AND scope_id=? AND revoked_at IS NULL",[STAFF_OFFICE_ACCOUNT_ID,scope]);
const fingerprint=createHash('sha256').update(JSON.stringify([row.id,row.terminal_event_id,p.bankOrderId,p.feeMinor,'neutral-refund'])).digest('hex');
if(previous){if(!priorKey||previous.state!=='posted'||String(previous.source_id)!==String(original.target_id)||String(previous.target_id)!==String(original.source_id)||String(previous.amount_minor)!==p.feeMinor||previous.fingerprint!==fingerprint)fail('The original raid refund requires reconciliation.');return {refundState:'posted',refundOrderId:refundId,receiptKeyId:priorKey.id};}
await b.query('SELECT id FROM pb_accounts WHERE id IN (?,?) ORDER BY id FOR UPDATE',[original.source_id,original.target_id]);
const rows=await b.query(accountsSQL+' WHERE a.id IN (?,?) ORDER BY a.id',[original.source_id,original.target_id]),source=rows.find(a=>String(a.id)===String(original.target_id)),target=rows.find(a=>String(a.id)===String(original.source_id)),amount=BigInt(p.feeMinor);
if(!source||source.system_key!=='sys_tax_treasury'||source.state!=='active'||!target||target.state!=='active'||target.entity_id!==entityId('clan',p.orderingClanId)||BigInt(source.balance_minor)-BigInt(source.reserved_minor)<amount||BigInt(target.balance_minor)+amount>9223372036854775807n)fail('Original raid refund remains queued; the original accounts cannot settle safely.');
const key=await issue(tx,scope,async()=>{
await b.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'system','queued',?)",[refundId,STAFF_OFFICE_ACCOUNT_ID,source.id,target.id,fingerprint,p.feeMinor,'Imperial raid refund '+row.id,clock()]);
await new PostbankPayments(bank,null,{clock}).post(b,{id:refundId,actor_id:STAFF_OFFICE_ACCOUNT_ID,amount_minor:p.feeMinor},{...source,entity_id:source.entity_id??null},target,false);
});
return {refundState:'posted',refundOrderId:refundId,receiptKeyId:key.id};
}
return {ready:banking.ready,resolveActor,resolveContext,charge,refund,bankView:banking.view};
}