import {randomUUID,randomInt,createHash} from 'node:crypto'; import {JarvisError} from './jarvis-listings.mjs'; export const OFFICE_AUCTION_RULES=Object.freeze({durationMs:3*3600000,startMinor:10000,incrementMinor:1000,recipient:'sys_tax_treasury'}); export const OFFICE_AUCTION_SCHEMA=[ `CREATE TABLE IF NOT EXISTS jarvis_office_auctions(id CHAR(36) PRIMARY KEY,source_id CHAR(36) NOT NULL UNIQUE,office_key VARCHAR(32) NOT NULL,candidate_ids TEXT NOT NULL,lottery_order TEXT NOT NULL,opens_at BIGINT NOT NULL,closes_at BIGINT NOT NULL,state VARCHAR(16) NOT NULL,revision INT NOT NULL,highest_minor BIGINT NOT NULL DEFAULT 0,highest_user_id CHAR(36) NULL,hold_id CHAR(36) NULL,winner_id CHAR(36) NULL,settled_at BIGINT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`, `CREATE TABLE IF NOT EXISTS jarvis_office_bids(id CHAR(36) PRIMARY KEY,request_id CHAR(36) NOT NULL UNIQUE,auction_id CHAR(36) NOT NULL,user_id CHAR(36) NOT NULL,amount_minor BIGINT NOT NULL,fingerprint CHAR(64) NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`, `CREATE TABLE IF NOT EXISTS jarvis_office_auction_events(id CHAR(36) PRIMARY KEY,auction_id CHAR(36) NOT NULL,event_type VARCHAR(32) NOT NULL,payload TEXT NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4` ]; const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v); const failure=(message,status=409)=>{throw new JarvisError(message,status);}; const ids=row=>JSON.parse(row.candidate_ids); const publicRow=row=>({id:row.id,type:'auction',auctionType:'office',officeKey:row.office_key,opensAt:Number(row.opens_at),closesAt:Number(row.closes_at),state:row.state,revision:Number(row.revision),highestMinor:Number(row.highest_minor),minimumBidMinor:Number(row.highest_minor)?Number(row.highest_minor)+OFFICE_AUCTION_RULES.incrementMinor:OFFICE_AUCTION_RULES.startMinor}); // All adapters write through the same transaction. Office transfers across databases // must enqueue a durable deed-transfer command here, never make an external call. // No public news is emitted; events remain in the private audit ledger. export function createOfficeAuctions(store,{eligible,reserve,release,settlePayment,award,clock=Date.now,draw=randomInt}){ if(![eligible,reserve,release,settlePayment,award].every(fn=>typeof fn==='function'))throw TypeError('Office auction adapters required'); const event=(tx,id,type,payload)=>tx.query('INSERT INTO jarvis_office_auction_events(id,auction_id,event_type,payload,created_at) VALUES(?,?,?,?,?)',[randomUUID(),id,type,JSON.stringify(payload),clock()]); return Object.freeze({ async open({sourceId,officeKey,candidateIds,opensAt}){ if(!uuid(sourceId)||!Array.isArray(candidateIds)||candidateIds.length<1||candidateIds.length>1000||candidateIds.some(id=>!uuid(id))||new Set(candidateIds).size!==candidateIds.length||!/^[a-z_]{1,32}$/.test(officeKey||'')||!Number.isSafeInteger(opensAt)||opensAt<0||!Number.isSafeInteger(opensAt+OFFICE_AUCTION_RULES.durationMs))failure('Invalid office auction.',400); const candidates=[...candidateIds].sort(); return store.transaction(async tx=>{ // source_id serialises duplicate deliveries from election reconciliation. const id=randomUUID(),lottery=[...candidates];for(let i=lottery.length-1;i>0;i--){const j=draw(i+1);if(!Number.isInteger(j)||j<0||j>i)throw Error('Invalid lottery draw');[lottery[i],lottery[j]]=[lottery[j],lottery[i]];}await tx.query("INSERT INTO jarvis_office_auctions(id,source_id,office_key,candidate_ids,lottery_order,opens_at,closes_at,state,revision) VALUES(?,?,?,?,?,?,?,'open',1) ON DUPLICATE KEY UPDATE source_id=VALUES(source_id)",[id,sourceId,officeKey,JSON.stringify(candidates),JSON.stringify(lottery),opensAt,opensAt+OFFICE_AUCTION_RULES.durationMs]); const row=await tx.first('SELECT * FROM jarvis_office_auctions WHERE source_id=? FOR UPDATE',[sourceId]); if(row.office_key!==officeKey||row.candidate_ids!==JSON.stringify(candidates)||Number(row.opens_at)!==opensAt)failure('Conflicting office auction source.'); if(row.id===id)await event(tx,id,'opened',{sourceId,officeKey,candidateIds:candidates,opensAt,closesAt:Number(row.closes_at)}); return {...publicRow(row),replayed:row.id!==id}; }); }, async bid(actor,{auctionId,requestId,amountMinor,sourceAccount,expectedRevision}){ if(!uuid(actor?.id)||!uuid(auctionId)||!uuid(requestId)||!Number.isSafeInteger(amountMinor)||amountMinor{ const row=await tx.first('SELECT * FROM jarvis_office_auctions WHERE id=? FOR UPDATE',[auctionId]);if(!row)failure('Auction not found.',404); const previous=await tx.first('SELECT * FROM jarvis_office_bids WHERE request_id=?',[requestId]); if(previous){if(previous.fingerprint!==fingerprint)failure('Bid reference already used.');return {id:previous.id,replayed:true};} const now=clock();if(row.state!=='open'||now=Number(row.closes_at))failure('Bidding is closed.'); if(!ids(row).includes(actor.id)||!await eligible(tx,actor,row))failure('Only eligible tied candidates may bid.',403); if(Number(row.revision)!==expectedRevision)failure('The auction changed. Review the latest bid.'); if(amountMinor{ const row=await tx.first('SELECT * FROM jarvis_office_auctions WHERE id=? FOR UPDATE',[auctionId]);if(!row)failure('Auction not found.',404); if(row.state!=='open')return {winnerId:row.winner_id,state:row.state,replayed:true}; if(clock()