web/website/node/guild-subsidy.mjs
2026-11-27 23:43:05 +00:00

25 lines
7.9 KiB
JavaScript

import {GUILD_SUBSIDY_POLICY} from '../control-panel/public/political-decision-policy.mjs';
import {createHash,randomUUID} from 'node:crypto';
import {PostbankPayments} from './postbank-payments.mjs';
import {boardReadStore} from './board-deed-source.mjs';
import {officeAuthority} from './political-decisions.mjs';
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
export const GUILD_SUBSIDY_SCHEMA=[
`CREATE TABLE IF NOT EXISTS pb_guild_subsidies(id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL UNIQUE,source_id BIGINT UNSIGNED NOT NULL,actor_id CHAR(36) NOT NULL,total_minor BIGINT NOT NULL,spent_minor BIGINT NOT NULL DEFAULT 0,pending_minor BIGINT NOT NULL DEFAULT 0,released_minor BIGINT NOT NULL DEFAULT 0,expires_at BIGINT NOT NULL,state VARCHAR(16) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
`CREATE TABLE IF NOT EXISTS pb_guild_subsidy_passages(id CHAR(36) PRIMARY KEY,pool_id CHAR(36) NOT NULL,amount_minor BIGINT NOT NULL,payment_id CHAR(36) NOT NULL UNIQUE,state VARCHAR(16) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
];
export const SUBSIDY_MIN=GUILD_SUBSIDY_POLICY.minMinor,SUBSIDY_MAX=GUILD_SUBSIDY_POLICY.maxMinor,SUBSIDY_PERCENT=GUILD_SUBSIDY_POLICY.percent;
export async function reserveGuildSubsidyPool(bank,{requestId,keyId,actorId,sourceId,amountMinor,expiresAt}){
await bank.query('UPDATE pb_accounts SET reserved_minor=reserved_minor+? WHERE id=?',[amountMinor,sourceId]);await bank.query("INSERT INTO pb_guild_subsidies(id,key_id,source_id,actor_id,total_minor,expires_at,state) VALUES(?,?,?,?,?,?,'active')",[requestId,keyId,sourceId,actorId,amountMinor,expiresAt]);return{poolId:requestId,sourceId:String(sourceId),amountMinor:String(amountMinor),percent:SUBSIDY_PERCENT,expiresAt};
}
export async function verifyGuildSubsidy(central,pool,now){if(!central.guildSubsidyEnabled)return false;const db=boardReadStore(central,central),proof=await db.first("SELECT d.* FROM jarvis_political_decisions d JOIN organisation_keys k ON k.id=d.key_id AND k.account_id=? AND k.key_type='entity-state' AND k.scope_id=CONCAT('state:political-decision:',d.request_id) AND k.revoked_at IS NULL WHERE d.request_id=? AND d.decision_id='SG-03'",[STAFF_OFFICE_ACCOUNT_ID,pool.id]);if(!proof||proof.actor_id!==pool.actor_id||proof.key_id!==pool.key_id||Number(proof.expires_at)!==Number(pool.expires_at)||Number(proof.expires_at)<=now)return false;const r=JSON.parse(proof.receipt_json),p=JSON.parse(proof.payload_json);if(r.subsidy?.poolId!==pool.id||r.subsidy.amountMinor!==String(pool.total_minor)||String(r.subsidy.sourceId)!==String(pool.source_id)||Number(p.amountMinor)!==Number(pool.total_minor))return false;const current=await officeAuthority(db,{office:'spacing_guild'},{id:pool.actor_id},now);return current?.termId===proof.term_id;}
export function createGuildSubsidies(bank,{verify,clock=Date.now}={}){
const payments=new PostbankPayments(bank,null,{clock});
const available=p=>BigInt(p.total_minor)-BigInt(p.spent_minor)-BigInt(p.pending_minor)-BigInt(p.released_minor);
async function quote(store,price,existingDiscount,lock=false){if(existingDiscount>0||price<2)return null;const pool=await store.first("SELECT * FROM pb_guild_subsidies WHERE state='active' AND expires_at>? ORDER BY expires_at DESC,id DESC LIMIT 1"+(lock?' FOR UPDATE':''),[clock()]);if(!pool||!await verify(pool,clock()))return null;const amount=Math.min(Math.floor(price*SUBSIDY_PERCENT/100),Number(available(pool)),price-1);return amount>0?{poolId:pool.id,price:price-amount,amount}:null;}
async function reserve(store,passageId,offer){const pool=await store.first('SELECT * FROM pb_guild_subsidies WHERE id=? FOR UPDATE',[offer.poolId]);if(!pool||pool.state!=='active'||Number(pool.expires_at)<=clock()||available(pool)<BigInt(offer.amount))throw Error('The subsidy pool changed.');await store.query('UPDATE pb_guild_subsidies SET pending_minor=pending_minor+? WHERE id=?',[offer.amount,pool.id]);await store.query("INSERT INTO pb_guild_subsidy_passages VALUES(?,?,?,?,'pending')",[passageId,pool.id,offer.amount,randomUUID()]);}
async function release(store,passageId){const marker=await store.first('SELECT * FROM pb_guild_subsidy_passages WHERE id=? FOR UPDATE',[passageId]);if(!marker||marker.state!=='pending')return;const pool=await store.first('SELECT * FROM pb_guild_subsidies WHERE id=? FOR UPDATE',[marker.pool_id]);if(!pool||BigInt(pool.pending_minor)<BigInt(marker.amount_minor))throw Error('Subsidy reservation needs reconciliation');if(pool.state==='closed'){const source=await store.first('SELECT reserved_minor FROM pb_accounts WHERE id=? FOR UPDATE',[pool.source_id]);if(!source||BigInt(source.reserved_minor)<BigInt(marker.amount_minor))throw Error('Subsidy funding needs reconciliation');await store.query('UPDATE pb_accounts SET reserved_minor=reserved_minor-? WHERE id=?',[marker.amount_minor,pool.source_id]);await store.query('UPDATE pb_guild_subsidies SET released_minor=released_minor+? WHERE id=?',[marker.amount_minor,pool.id]);}await store.query('UPDATE pb_guild_subsidies SET pending_minor=pending_minor-? WHERE id=?',[marker.amount_minor,pool.id]);await store.query("UPDATE pb_guild_subsidy_passages SET state='released' WHERE id=?",[passageId]);}
async function settle(store,passageId,targetId){const marker=await store.first('SELECT * FROM pb_guild_subsidy_passages WHERE id=? FOR UPDATE',[passageId]);if(!marker||marker.state==='posted')return;if(marker.state!=='pending')throw Error('Subsidy passage is not pending');const pool=await store.first('SELECT * FROM pb_guild_subsidies WHERE id=? FOR UPDATE',[marker.pool_id]);if(!pool||BigInt(pool.pending_minor)<BigInt(marker.amount_minor))throw Error('Subsidy reservation needs reconciliation');const source=await store.first('SELECT a.*,c.entity_id FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number WHERE a.id=? FOR UPDATE',[pool.source_id]),target=await store.first('SELECT * FROM pb_accounts WHERE id=? FOR UPDATE',[targetId]),amount=BigInt(marker.amount_minor);if(!source||!target||target.system_key!=='sys_game_treasury'||source.state!=='active'||target.state!=='active'||BigInt(source.balance_minor)<amount||BigInt(source.reserved_minor)<amount||BigInt(target.balance_minor)+amount>9223372036854775807n)throw Error('Subsidy settlement needs reconciliation');const id=marker.payment_id,fingerprint=createHash('sha256').update(JSON.stringify([pool.id,passageId,marker.amount_minor])).digest('hex');await store.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'system','queued',?)",[id,pool.actor_id,source.id,target.id,fingerprint,marker.amount_minor,'Guild travel subsidy · '+passageId,clock()]);await payments.post(store,{id,actor_id:pool.actor_id,amount_minor:String(marker.amount_minor)},source,target,true);await store.query('UPDATE pb_guild_subsidies SET spent_minor=spent_minor+?,pending_minor=pending_minor-? WHERE id=?',[marker.amount_minor,marker.amount_minor,pool.id]);await store.query("UPDATE pb_guild_subsidy_passages SET state='posted' WHERE id=?",[passageId]);}
async function expire(){return bank.transaction(async tx=>{const pools=await tx.query("SELECT * FROM pb_guild_subsidies WHERE state='active' ORDER BY expires_at,id LIMIT 50 FOR UPDATE");let closed=0;for(const pool of pools){if(Number(pool.expires_at)>clock()&&await verify(pool,clock()))continue;const remainder=available(pool);if(remainder<0n)throw Error('Subsidy ledger requires review');const source=await tx.first('SELECT reserved_minor FROM pb_accounts WHERE id=? FOR UPDATE',[pool.source_id]);if(!source||BigInt(source.reserved_minor)<remainder)throw Error('Subsidy funding requires reconciliation');if(remainder)await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor-? WHERE id=?',[String(remainder),pool.source_id]);await tx.query("UPDATE pb_guild_subsidies SET released_minor=released_minor+?,state='closed' WHERE id=?",[String(remainder),pool.id]);closed++;}return {closed};});}
return {quote,reserve,release,settle,expire};
}