forked from unimatrix/web
57 lines
7.5 KiB
JavaScript
57 lines
7.5 KiB
JavaScript
import {ECONOMY_POLICY,economicIndex,systemPrice,indexedRateBps,indexedPay} from './jarvis-economy-policy.mjs';
|
|
import {readFinancialPolicy,validateFinancialPolicy,queueRatesPublication} from './postbank-financial-policy.mjs';
|
|
import {SPICE_POLICY} from './spice-policy.mjs';
|
|
import {economyId} from './economy-operations.mjs';
|
|
export const FED_POLICY_KEY='federal_reserve';
|
|
const calendar=new Intl.DateTimeFormat('en-CA',{timeZone:'Europe/Brussels',year:'numeric',month:'2-digit',day:'2-digit'});
|
|
export function federalDay(now){const p=Object.fromEntries(calendar.formatToParts(new Date(now)).map(p=>[p.type,p.value]));return p.year+'-'+p.month+'-'+p.day;}
|
|
export async function readFederalReserve(db){const row=await db.first('SELECT policy_json,version FROM pb_financial_policies WHERE policy_key=?',[FED_POLICY_KEY]);return row?{...JSON.parse(row.policy_json),revision:Number(row.version)}:null;}
|
|
export async function writeFederalPolicy(tx,key,value,actor,now){
|
|
const old=await tx.first('SELECT version FROM pb_financial_policies WHERE policy_key=? FOR UPDATE',[key]);
|
|
await tx.query('INSERT INTO pb_financial_policies(policy_key,policy_json,version,updated_by,updated_at) VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE policy_json=VALUES(policy_json),version=VALUES(version),updated_by=VALUES(updated_by),updated_at=VALUES(updated_at)',[key,JSON.stringify(value),Number(old?.version||0)+1,actor,now]);
|
|
}
|
|
export async function initialiseFederalReserve(tx,{epoch,resetAt,actor}){
|
|
const bank=await readFinancialPolicy(tx,'bank_rates'),payroll=await readFinancialPolicy(tx,'payroll');
|
|
const value={schema:1,enabled:true,epoch,resetAt,state:'awaiting-payroll',referenceMinor:null,baselineId:epoch,indexMicros:1000000,baseBankRates:bank.value,basePayroll:payroll.value,lastDay:null,lastPayMonth:federalDay(resetAt).slice(0,7),prices:{'spice.guild':SPICE_POLICY.guild,'spice.smuggler':SPICE_POLICY.smuggler},basePrices:{'spice.guild':SPICE_POLICY.guild,'spice.smuggler':SPICE_POLICY.smuggler},priceStep:ECONOMY_POLICY.dailyPriceStep,minPriceFactor:ECONOMY_POLICY.minPriceFactor,maxPriceFactor:ECONOMY_POLICY.maxPriceFactor};
|
|
await writeFederalPolicy(tx,FED_POLICY_KEY,value,actor,resetAt);return value;
|
|
}
|
|
export async function federalSpicePolicy(db){const fed=await readFederalReserve(db);return fed?.enabled?{...SPICE_POLICY,guild:fed.prices['spice.guild'],smuggler:fed.prices['spice.smuggler'],economyDay:fed.lastDay}:SPICE_POLICY;}
|
|
async function fundedPayroll(db,resetAt){
|
|
const runs=await db.query("SELECT period,state,created_at FROM pb_payroll_runs WHERE state='completed' AND created_at>=? UNION ALL SELECT period,state,created_at FROM pb_payroll_additional_runs WHERE state='completed' AND created_at>=? ORDER BY created_at,period LIMIT 1",[resetAt,resetAt]);
|
|
if(!runs.length)return false;
|
|
return !!await db.first("SELECT id FROM pb_orders WHERE mode='payroll' AND state='posted' AND posted_at>=? LIMIT 1",[resetAt]);
|
|
}
|
|
export async function federalCirculation(db){const row=await db.first('SELECT COALESCE(SUM(CASE WHEN balance_minor>0 THEN balance_minor ELSE 0 END),0) total FROM pb_accounts WHERE system_key IS NULL');const value=Number(row.total);if(!Number.isSafeInteger(value)||value<0)throw Error('Economic circulation exceeds supported range');return value;}
|
|
export function createFederalReserve(bank,operate,{actorId,clock=Date.now,recordSnapshot=async()=>{}}={}){
|
|
return {async run(){
|
|
const policy=await readFederalReserve(bank),day=federalDay(clock());if(!policy?.enabled)return {enabled:false};
|
|
if(!policy.referenceMinor&&(!await fundedPayroll(bank,policy.resetAt)||!await federalCirculation(bank)))return {state:'awaiting-payroll',payrollExecuted:false};
|
|
const id=economyId(['federal-cycle',policy.epoch,day]);
|
|
if(policy.lastDay===day){const saved=await bank.first('SELECT receipt_json FROM pb_economy_operations WHERE id=?',[id]);const receipt=saved&&JSON.parse(saved.receipt_json);if(receipt?.observation)await recordSnapshot(receipt.observation);return {state:policy.state,unchanged:true};}
|
|
const result=await operate({action:'economy.federal-cycle',id,fields:{epoch:policy.epoch,day,policyVersion:ECONOMY_POLICY.version},apply:async(tx,{now,keyId})=>{
|
|
await tx.query("INSERT INTO pb_financial_policies(policy_key,policy_json,version,updated_by,updated_at) VALUES('publication_guard','{}',0,?,?) ON DUPLICATE KEY UPDATE policy_key=VALUES(policy_key)",[actorId,now]);
|
|
await tx.first("SELECT policy_key FROM pb_financial_policies WHERE policy_key='publication_guard' FOR UPDATE");
|
|
await tx.first('SELECT policy_key FROM pb_financial_policies WHERE policy_key=? FOR UPDATE',[FED_POLICY_KEY]);const current=await readFederalReserve(tx);
|
|
if(!current?.enabled||current.epoch!==policy.epoch||current.lastDay&¤t.lastDay>=day)throw Error('Federal policy period changed');
|
|
const circulation=await federalCirculation(tx);
|
|
if(!current.referenceMinor){if(!await fundedPayroll(tx,current.resetAt)||!circulation)throw Error('A funded completed payroll is required for the baseline');current.referenceMinor=circulation;current.baselineAt=now;}
|
|
const index=economicIndex({circulatingMinor:circulation,referenceMinor:current.referenceMinor}),rates=await readFinancialPolicy(tx,'bank_rates');
|
|
for(const [key,base]of Object.entries(current.basePrices))current.prices[key]=systemPrice({baseMinor:base,currentMinor:current.prices[key],index});
|
|
for(const [product,base]of Object.entries(current.baseBankRates.creditAnnualBps)){
|
|
if(base===0){rates.value.creditAnnualBps[product]=0;continue;}
|
|
const target=indexedRateBps({baseBps:base,index,sensitivityBps:ECONOMY_POLICY.loanSensitivityBps,minBps:Math.floor(base/2),maxBps:Math.min(10000,base*2)}),old=rates.value.creditAnnualBps[product];rates.value.creditAnnualBps[product]=Math.max(old-25,Math.min(old+25,target));
|
|
}
|
|
validateFinancialPolicy('bank_rates',rates.value);await writeFederalPolicy(tx,'bank_rates',rates.value,actorId,now);
|
|
if(current.lastPayMonth!==day.slice(0,7)){
|
|
const payroll=await readFinancialPolicy(tx,'payroll');for(const role of Object.keys(payroll.value.netMinor)){const base=current.basePayroll.netMinor[role];payroll.value.netMinor[role]=Math.max(100,Math.floor(base/2),Math.min(base*2,indexedPay({baseMinor:base,currentMinor:payroll.value.netMinor[role],index})));}validateFinancialPolicy('payroll',payroll.value);await writeFederalPolicy(tx,'payroll',payroll.value,actorId,now);current.lastPayMonth=day.slice(0,7);
|
|
}
|
|
current.state='active';current.indexMicros=Math.round(index*1000000);current.lastDay=day;current.lastKeyId=keyId;current.circulatingMinor=circulation;
|
|
await writeFederalPolicy(tx,FED_POLICY_KEY,current,actorId,now);const publication=await queueRatesPublication(tx,actorId,now);
|
|
const pay=await readFinancialPolicy(tx,'payroll'),payBase=Object.values(current.basePayroll.netMinor).reduce((a,b)=>a+b,0),payNow=Object.values(pay.value.netMinor).reduce((a,b)=>a+b,0);
|
|
const observation={id:economyId(['federal-observation',current.epoch,day]),baselineId:current.baselineId,observedAt:now,policyVersion:ECONOMY_POLICY.version,circulatingMinor:circulation,referenceMinor:current.referenceMinor,indexMicros:current.indexMicros,priceIndexMicros:Math.round(current.prices['spice.guild']/current.basePrices['spice.guild']*1000000),payIndexMicros:Math.round(payNow/payBase*1000000),loanBps:rates.value.creditAnnualBps.personal_loan};
|
|
return {state:'active',epoch:current.epoch,day,keyId,publication,observation,payrollExecuted:false};
|
|
}});
|
|
// Retry this sealed observation even after a lost central acknowledgement.
|
|
if(result.observation)await recordSnapshot(result.observation);return result;
|
|
}};
|
|
}
|

Staff