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

24 lines
6.3 KiB
JavaScript

import {EXCHANGE_INCENTIVE_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 EXCHANGE_INCENTIVE_SCHEMA=[
`CREATE TABLE IF NOT EXISTS pb_exchange_incentive_pools(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,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_exchange_incentive_rebates(purchase_id CHAR(36) PRIMARY KEY,pool_id CHAR(36) NOT NULL,buyer_id CHAR(36) NOT NULL,amount_minor BIGINT NOT NULL,payment_id CHAR(36) NOT NULL UNIQUE,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
];
export const INCENTIVE_PERCENT=EXCHANGE_INCENTIVE_POLICY.percent,INCENTIVE_WORLD=EXCHANGE_INCENTIVE_POLICY.world;
export async function reserveExchangeIncentivePool(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_exchange_incentive_pools(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:INCENTIVE_PERCENT,world:INCENTIVE_WORLD,expiresAt};}
export async function verifyExchangeIncentive(central,pool,now){if(!central.exchangeIncentiveEnabled)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='ORD-04'",[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.incentive?.poolId!==pool.id||r.incentive.amountMinor!==String(pool.total_minor)||String(r.incentive.sourceId)!==String(pool.source_id)||Number(p.amountMinor)!==Number(pool.total_minor))return false;const current=await officeAuthority(db,{office:'ordos'},{id:pool.actor_id},now);return current?.termId===proof.term_id;}
export function createExchangeIncentives(bank,{verify,clock=Date.now}={}){
const payments=new PostbankPayments(bank,null,{clock}),remaining=p=>BigInt(p.total_minor)-BigInt(p.spent_minor)-BigInt(p.released_minor);
async function rebate(tx,{purchaseId,buyerId,sellerId,buyerAccountId,originWorld,grossMinor}){
if(originWorld!==INCENTIVE_WORLD||buyerId===sellerId)return 0;const pool=await tx.first("SELECT * FROM pb_exchange_incentive_pools WHERE state='active' AND expires_at>? ORDER BY expires_at DESC,id DESC LIMIT 1 FOR UPDATE",[clock()]);if(!pool||pool.actor_id===buyerId||pool.actor_id===sellerId||!await verify(pool,clock()))return 0;
const prior=await tx.first('SELECT buyer_id,amount_minor FROM pb_exchange_incentive_rebates WHERE purchase_id=?',[purchaseId]);if(prior){if(prior.buyer_id!==buyerId)throw Error('Exchange incentive reference conflict');return Number(prior.amount_minor);}const maximum=BigInt(grossMinor)*BigInt(INCENTIVE_PERCENT)/100n,amount=remaining(pool)<maximum?remaining(pool):maximum;if(amount<=0n)return 0;
const source=await tx.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 tx.first('SELECT a.*,e.external_key FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id WHERE a.id=? FOR UPDATE',[buyerAccountId]);if(!source||!target||target.external_key!==buyerId||String(target.id)===String(source.id)||source.state!=='active'||target.state!=='active'||BigInt(source.balance_minor)<amount||BigInt(source.reserved_minor)<amount||BigInt(target.balance_minor)+amount>9223372036854775807n)throw Error('Exchange incentive settlement needs review');const id=randomUUID(),fingerprint=createHash('sha256').update(JSON.stringify([pool.id,purchaseId,buyerId,amount.toString()])).digest('hex');await tx.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,amount.toString(),'Ordos trade incentive · '+purchaseId,clock()]);await payments.post(tx,{id,actor_id:pool.actor_id,amount_minor:amount.toString()},source,target,true);await tx.query('UPDATE pb_exchange_incentive_pools SET spent_minor=spent_minor+? WHERE id=?',[amount.toString(),pool.id]);await tx.query('INSERT INTO pb_exchange_incentive_rebates VALUES(?,?,?,?,?,?)',[purchaseId,pool.id,buyerId,amount.toString(),id,clock()]);return Number(amount);
}
async function replay(tx,purchaseId){const row=await tx.first('SELECT amount_minor FROM pb_exchange_incentive_rebates WHERE purchase_id=?',[purchaseId]);return Number(row?.amount_minor||0);}
async function expire(){return bank.transaction(async tx=>{const rows=await tx.query("SELECT * FROM pb_exchange_incentive_pools WHERE state='active' ORDER BY expires_at,id LIMIT 50 FOR UPDATE");let closed=0;for(const pool of rows){if(Number(pool.expires_at)>clock()&&await verify(pool,clock()))continue;const amount=remaining(pool),source=await tx.first('SELECT reserved_minor FROM pb_accounts WHERE id=? FOR UPDATE',[pool.source_id]);if(amount<0n||!source||BigInt(source.reserved_minor)<amount)throw Error('Exchange incentive funding requires reconciliation');if(amount)await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor-? WHERE id=?',[amount.toString(),pool.source_id]);await tx.query("UPDATE pb_exchange_incentive_pools SET released_minor=released_minor+?,state='closed' WHERE id=?",[amount.toString(),pool.id]);closed++;}return {closed};});}
return {rebate,replay,expire};
}