MC/website/node/share-ledger.mjs
Dev 6deb4a2e7d DuneRealms V2 clean baseline
Owner-authorised history reset; current source tree preserved exactly.
2026-11-13 00:05:14 +01:00

60 lines
7.1 KiB
JavaScript

import {randomUUID} from 'node:crypto';
// Corrino Group shares: immutable share ledger design, no cash settlement or live trading.
export const shareLedgerSchema=Object.freeze([
`CREATE TABLE IF NOT EXISTS corrino_share_classes (id CHAR(36) PRIMARY KEY, company_id CHAR(36) NOT NULL, symbol VARCHAR(16) NOT NULL UNIQUE, class_name VARCHAR(80) NOT NULL, authorized_shares BIGINT NOT NULL, issued_shares BIGINT NOT NULL DEFAULT 0, created_at BIGINT NOT NULL, INDEX share_class_company(company_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
`CREATE TABLE IF NOT EXISTS corrino_share_positions (share_class_id CHAR(36) NOT NULL, account_id CHAR(36) NOT NULL, quantity BIGINT NOT NULL, PRIMARY KEY(share_class_id,account_id), INDEX share_position_account(account_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
`CREATE TABLE IF NOT EXISTS corrino_share_events (id CHAR(36) PRIMARY KEY, share_class_id CHAR(36) NOT NULL, account_id CHAR(36) NOT NULL, action VARCHAR(24) NOT NULL, quantity BIGINT NOT NULL, reference_id VARCHAR(100) NOT NULL UNIQUE, actor_id CHAR(36) NOT NULL, created_at BIGINT NOT NULL, INDEX share_events_class(share_class_id,created_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
]);
export async function initializeShareLedger(db){for(const sql of shareLedgerSchema)await db.prepare(sql).run();}
export function validateShareQuantity(quantity){if(!Number.isSafeInteger(quantity)||quantity<=0||quantity>1_000_000_000)throw new TypeError('Share quantity must be a positive safe integer under one billion');return quantity;}
export function validateShareClass({symbol,name,authorizedShares}){if(typeof symbol!=='string'||!/^[A-Z][A-Z0-9._-]{1,15}$/.test(symbol)||typeof name!=='string'||!name.trim()||name.length>80)throw new TypeError('Invalid share class');return {symbol,name:name.trim(),authorizedShares:validateShareQuantity(authorizedShares)};}
export function validateShareIssuance({authorizedShares,issuedShares,quantity}){validateShareQuantity(quantity);if(!Number.isSafeInteger(authorizedShares)||!Number.isSafeInteger(issuedShares)||issuedShares<0||authorizedShares<issuedShares||quantity>authorizedShares-issuedShares)throw new RangeError('Share issuance exceeds authorized supply');return issuedShares+quantity;}
// No public issuance route until row-locking, account checks and audited settlement are tested against MySQL.
export const SHARE_TRADING_ENABLED=false;
// Internal only: caller must be permission-checked; no public route or bank movement.
export async function issueShares(db,{shareClassId,accountId,actorId,referenceId,quantity,authorized=false}){
if(authorized!==true)throw new Error('Share issuance not authorized');
if(![shareClassId,accountId,actorId].every(v=>typeof v==='string'&&/^[0-9a-f-]{36}$/i.test(v)))throw new TypeError('Invalid account or class identifier');
if(typeof referenceId!=='string'||!/^[a-zA-Z0-9:_-]{8,100}$/.test(referenceId))throw new TypeError('Invalid issuance reference');
validateShareQuantity(quantity);
if(typeof db.transaction!=='function')throw new Error('Transactional database required');
return db.transaction(async tx=>{
const previous=await tx.first('SELECT id,share_class_id,account_id,quantity,action FROM corrino_share_events WHERE reference_id=?',[referenceId]);
if(previous){if(previous.share_class_id===shareClassId&&previous.account_id===accountId&&Number(previous.quantity)===quantity&&previous.action==='issue')return {eventId:previous.id,created:false};throw new Error('Issuance reference already used');}
const shareClass=await tx.first('SELECT authorized_shares,issued_shares FROM corrino_share_classes WHERE id=? FOR UPDATE',[shareClassId]);
if(!shareClass)throw new Error('Share class not found');
// Concurrent retries can both miss the first lookup. The class row lock
// serializes issuances for this class, so re-check the unique reference now.
const afterLock=await tx.first('SELECT id,share_class_id,account_id,quantity,action FROM corrino_share_events WHERE reference_id=?',[referenceId]);
if(afterLock){if(afterLock.share_class_id===shareClassId&&afterLock.account_id===accountId&&Number(afterLock.quantity)===quantity&&afterLock.action==='issue')return {eventId:afterLock.id,created:false};throw new Error('Issuance reference already used');}
const account=await tx.first('SELECT id FROM site_accounts WHERE id=?',[accountId]);
if(!account)throw new Error('Shareholder account not found');
// BIGINT values can be returned as strings. Use BigInt to avoid float rounding.
const authorizedShares=BigInt(shareClass.authorized_shares),issuedShares=BigInt(shareClass.issued_shares),amount=BigInt(quantity);
if(authorizedShares<0n||issuedShares<0n||issuedShares>authorizedShares||amount>authorizedShares-issuedShares)throw new RangeError('Share issuance exceeds authorized supply');
const eventId=randomUUID(),now=Date.now();
await tx.query('UPDATE corrino_share_classes SET issued_shares=issued_shares+? WHERE id=?',[quantity,shareClassId]);
await tx.query('INSERT INTO corrino_share_positions(share_class_id,account_id,quantity) VALUES(?,?,?) ON DUPLICATE KEY UPDATE quantity=quantity+VALUES(quantity)',[shareClassId,accountId,quantity]);
await tx.query('INSERT INTO corrino_share_events(id,share_class_id,account_id,action,quantity,reference_id,actor_id,created_at) VALUES(?,?,?,?,?,?,?,?)',[eventId,shareClassId,accountId,'issue',quantity,referenceId,actorId,now]);
return {eventId,created:true};
});
}
// Read-only reconciliation before any stock market or settlement goes live.
// BIGINT values are converted without losing precision; report strings for JSON safety.
export async function auditShareClass(db,shareClassId){
if(typeof shareClassId!=='string'||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(shareClassId))throw new TypeError('Invalid share class identifier');
const shareClass=await db.prepare('SELECT id,authorized_shares,issued_shares FROM corrino_share_classes WHERE id=?').bind(shareClassId).first();
if(!shareClass)throw new Error('Share class not found');
const {results:positions}=await db.prepare('SELECT account_id,quantity FROM corrino_share_positions WHERE share_class_id=?').bind(shareClassId).all();
const {results:events}=await db.prepare('SELECT action,quantity FROM corrino_share_events WHERE share_class_id=?').bind(shareClassId).all();
const issued=BigInt(shareClass.issued_shares),authorized=BigInt(shareClass.authorized_shares);
let held=0n,eventTotal=0n;const problems=[];
for(const position of positions){const quantity=BigInt(position.quantity);if(quantity<0n)problems.push('Negative shareholder position');held+=quantity;}
for(const event of events){const quantity=BigInt(event.quantity);if(quantity<=0n)problems.push('Invalid event quantity');if(event.action==='issue')eventTotal+=quantity;else problems.push('Unrecognized share event action');}
if(issued<0n||issued>authorized)problems.push('Issued supply exceeds authorized shares');
if(held!==issued)problems.push('Positions do not reconcile with issued supply');
if(eventTotal!==issued)problems.push('Issuance events do not reconcile with issued supply');
return {shareClassId,ok:problems.length===0,authorized:authorized.toString(),issued:issued.toString(),held:held.toString(),eventTotal:eventTotal.toString(),problems};
}