MC/website/node/jarvis-office-auctions.mjs
2026-11-27 23:43:05 +00:00

76 lines
8.1 KiB
JavaScript

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<OFFICE_AUCTION_RULES.startMinor||!Number.isSafeInteger(expectedRevision)||expectedRevision<1||typeof sourceAccount!=='string'||!/^\d{1,12}$/.test(sourceAccount))failure('Review your bid and payment account.',400);
const fingerprint=createHash('sha256').update(JSON.stringify([actor.id,auctionId,amountMinor,sourceAccount,expectedRevision])).digest('hex');
return store.transaction(async tx=>{
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.opens_at)||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<publicRow(row).minimumBidMinor)failure('Bid below the current minimum.');
// Release the old reservation inside this transaction, allowing the same bidder
// to increase using the released balance. A failed new reservation rolls it back.
if(row.hold_id)await release(tx,{holdId:row.hold_id,auctionId});
const holdId=await reserve(tx,{actor,sourceAccount,amountMinor,auctionId,requestId,recipient:OFFICE_AUCTION_RULES.recipient});if(!uuid(holdId))throw Error('Invalid bid reservation');
const id=randomUUID();await tx.query('INSERT INTO jarvis_office_bids(id,request_id,auction_id,user_id,amount_minor,fingerprint,created_at) VALUES(?,?,?,?,?,?,?)',[id,requestId,auctionId,actor.id,amountMinor,fingerprint,now]);
await tx.query('UPDATE jarvis_office_auctions SET highest_minor=?,highest_user_id=?,hold_id=?,revision=revision+1 WHERE id=?',[amountMinor,actor.id,holdId,auctionId]);
await event(tx,auctionId,'bid_received',{bidId:id,userId:actor.id,amountMinor});return {id,replayed:false,revision:expectedRevision+1};
});
},
async close(auctionId){
if(!uuid(auctionId))failure('Choose an auction.',400);
return store.transaction(async tx=>{
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()<Number(row.closes_at))failure('Auction has not closed.');
let winnerId=row.highest_user_id,method='auction';
if(winnerId){
if(!await eligible(tx,{id:winnerId},row))failure('Winning candidate needs eligibility review.');
await settlePayment(tx,{holdId:row.hold_id,auctionId,amountMinor:Number(row.highest_minor),recipient:OFFICE_AUCTION_RULES.recipient});
}else{
const candidates=[];for(const id of JSON.parse(row.lottery_order))if(await eligible(tx,{id},row))candidates.push(id);
if(!candidates.length)failure('No eligible candidate remains for the lottery.');
winnerId=candidates[0];method='lottery';
}
const transfer=await award(tx,{auctionId,sourceId:row.source_id,officeKey:row.office_key,winnerId,method}),state=transfer?.pending?'award_pending':'awarded';
await tx.query('UPDATE jarvis_office_auctions SET state=?,winner_id=?,settled_at=?,revision=revision+1 WHERE id=?',[state,winnerId,clock(),auctionId]);
await event(tx,auctionId,state,{winnerId,method,amountMinor:Number(row.highest_minor)});return {winnerId,method,state,replayed:false};
});
},
async browse(){return (await store.query("SELECT * FROM jarvis_office_auctions WHERE state='open' ORDER BY closes_at,id LIMIT 500")).map(publicRow);}
});
}