Skip to main content

qualia_core_db/modalities/
socioeconomics.rs

1//! Socioeconomics & compensation (§23, legal_logic.md) — the Permissive Commons.
2//!
3//! Shifts economic obligation from infinite linear consumption to **threshold-based discharge**
4//! to prevent extraction: a work's cost is its audited production cost plus a *legally capped*
5//! ROI; usage by an agent triggers a royalty scaled by the agent's category; payments accumulate
6//! into a pool; once the pool meets the cost, the obligation is **discharged and the use is freed
7//! globally**. Integer arithmetic throughout (deterministic, zero-heap) — units are abstract
8//! minor units (e.g. cents).
9
10/// Total economic obligation for a work: `production_cost × (1 + roi_cap)`, with the ROI margin
11/// **capped** (the `sh:maxInclusive` cap — extraction guard). `roi_cap_percent` is clamped to
12/// `max_roi_percent` before applying. Saturating.
13pub fn commons_cost(production_cost: u64, roi_cap_percent: u64, max_roi_percent: u64) -> u64 {
14    let roi = roi_cap_percent.min(max_roi_percent);
15    let margin = production_cost.saturating_mul(roi) / 100;
16    production_cost.saturating_add(margin)
17}
18
19/// The royalty a use incurs: `base × multiplier%`, where the multiplier scales by agent
20/// category (e.g. a corporate user pays a higher multiple than a non-profit). Saturating.
21#[inline]
22pub fn royalty(base: u64, agent_multiplier_percent: u64) -> u64 {
23    base.saturating_mul(agent_multiplier_percent) / 100
24}
25
26/// Accumulate a payment into the compensation pool (saturating).
27#[inline]
28pub fn pool_after(pool: u64, payment: u64) -> u64 {
29    pool.saturating_add(payment)
30}
31
32/// The obligation is **discharged** once accumulated compensation meets the cost — the use is
33/// then obligation-free (freed globally). `Active(Outstanding) → Discharged(ObligationFree)`.
34#[inline]
35pub fn is_commons_discharged(pool: u64, cost: u64) -> bool {
36    pool >= cost && cost > 0
37}
38
39/// Outstanding balance still owed before discharge (0 once met). Saturating.
40#[inline]
41pub fn outstanding(pool: u64, cost: u64) -> u64 {
42    cost.saturating_sub(pool)
43}
44
45// ─── Thermodynamic cost caps (E-ROI) ──────────────────────────────────────────────
46
47/// **Energy Return On Investment** = `energy_returned / energy_invested`. `0.0` if nothing was
48/// invested. The physics-bound viability ratio of a resource flow.
49pub fn eroi(energy_returned: u64, energy_invested: u64) -> f32 {
50    if energy_invested == 0 {
51        0.0
52    } else {
53        energy_returned as f32 / energy_invested as f32
54    }
55}
56
57/// Is a resource flow thermodynamically viable — E-ROI at or above `min_ratio`? Below this floor the
58/// flow is net-extractive (spends more energy than it recovers) and is refused — the physics-bound
59/// cost cap.
60#[inline]
61pub fn eroi_viable(energy_returned: u64, energy_invested: u64, min_ratio: f32) -> bool {
62    eroi(energy_returned, energy_invested) >= min_ratio
63}
64
65// ─── Recursive royalty trees (derivative-work attribution) ────────────────────────
66
67/// The royalty owed to an ancestor `generation` levels up a derivation chain: a geometric split
68/// where each level takes `share_percent` of what reaches it —
69/// `total × (share_percent/100)^(generation+1)`. Generation 0 = the immediate parent. Saturating
70/// integer arithmetic; zero-heap. (Recursive commons attribution for derivative works.)
71pub fn ancestor_royalty(total_royalty: u64, generation: u32, share_percent: u64) -> u64 {
72    let mut amount = total_royalty;
73    for _ in 0..=generation {
74        amount = amount.saturating_mul(share_percent) / 100;
75    }
76    amount
77}
78
79/// Total royalty distributed up a chain of `generations` ancestors (the sum of each generation's
80/// geometric share) — what leaves the deriving work as upstream attribution.
81pub fn royalty_tree_total(total_royalty: u64, generations: u32, share_percent: u64) -> u64 {
82    let mut sum = 0u64;
83    for g in 0..generations {
84        sum = sum.saturating_add(ancestor_royalty(total_royalty, g, share_percent));
85    }
86    sum
87}
88
89// ─── Multi-currency & cross-jurisdictional tax shunting ───────────────────────────
90
91/// Convert `amount` at `rate_micros` (target units per source unit, in millionths — e.g.
92/// `1_500_000` = ×1.5). Saturating (u128 intermediate).
93pub fn convert_currency(amount: u64, rate_micros: u64) -> u64 {
94    ((amount as u128).saturating_mul(rate_micros as u128) / 1_000_000u128) as u64
95}
96
97/// The tax owed on `amount` at `tax_basis_points` (1 bp = 0.01%) — the automated cross-
98/// jurisdictional tax-schema shunt. Saturating (u128 intermediate).
99pub fn apply_tax(amount: u64, tax_basis_points: u64) -> u64 {
100    ((amount as u128).saturating_mul(tax_basis_points as u128) / 10_000u128) as u64
101}
102
103// ─── Liquidity-pool ODE (drainage + replenishment) ────────────────────────────────
104
105/// One discrete Euler step of the liquidity ODE `dL/dt = inflow − drain·L`: constant `inflow`
106/// replenishment minus drainage proportional to the current pool (`drain_percent`% per step).
107/// Saturating; zero-heap. The steady state is `L* = inflow / drain`.
108pub fn liquidity_step(pool: u64, inflow: u64, drain_percent: u64) -> u64 {
109    let drained = pool.saturating_mul(drain_percent.min(100)) / 100;
110    pool.saturating_sub(drained).saturating_add(inflow)
111}
112
113/// Evolve liquidity over `steps` of the ODE (constant `inflow`, proportional `drain_percent`) —
114/// converges toward the steady state `inflow / (drain_percent/100)`.
115pub fn liquidity_after(initial: u64, inflow: u64, drain_percent: u64, steps: u32) -> u64 {
116    let mut pool = initial;
117    for _ in 0..steps {
118        pool = liquidity_step(pool, inflow, drain_percent);
119    }
120    pool
121}
122
123// ─── Usury circuit-breaker (multi-agent token ceiling) ────────────────────────────
124
125/// Default permitted overage above an agreed budget, in percent — the spec's **110%**
126/// token ceiling is `budget × (1 + 10/100)`.
127pub const USURY_OVERAGE_PERCENT_DEFAULT: u64 = 10;
128
129/// Maximum spend permitted before the usury breaker trips: `budget × (1 + overage/100)`
130/// (saturating). With the default 10% overage this is the 110% ceiling.
131#[inline]
132pub fn usury_ceiling(budget: u64, overage_percent: u64) -> u64 {
133    let margin = budget.saturating_mul(overage_percent) / 100;
134    budget.saturating_add(margin)
135}
136
137/// Has `projected_spend` breached the usury ceiling for `budget`? Spending *up to and
138/// including* the ceiling is permitted; only a strictly greater spend is usurious.
139#[inline]
140pub fn is_usurious(projected_spend: u64, budget: u64, overage_percent: u64) -> bool {
141    projected_spend > usury_ceiling(budget, overage_percent)
142}
143
144/// `ERROR_USURY_LIMIT_EXCEEDED` — a projected spend breached the agreed budget's
145/// ceiling. Carries the `budget`, the computed `ceiling`, and the offending
146/// `projected` spend so the caller can write a faithful conduct-violation record.
147#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148pub struct UsuryError {
149    pub budget: u64,
150    pub ceiling: u64,
151    pub projected: u64,
152}
153
154/// Gate a projected spend against the usury ceiling — `Ok(())` while at/under the
155/// ceiling, `Err(UsuryError)` once it is breached.
156#[inline]
157pub fn check_usury(
158    projected_spend: u64,
159    budget: u64,
160    overage_percent: u64,
161) -> Result<(), UsuryError> {
162    let ceiling = usury_ceiling(budget, overage_percent);
163    if projected_spend > ceiling {
164        Err(UsuryError {
165            budget,
166            ceiling,
167            projected: projected_spend,
168        })
169    } else {
170        Ok(())
171    }
172}
173
174// ─── QDNF Economics Metering Binding (WP-4.1) ─────────────────────────────────────
175
176use crate::net::qdnf::economics::meters::MeterReading;
177
178/// Computes the carriage compensation for observed resource meters based on
179/// allowed carriage rates (cents per unit), strictly bounded by production ROI caps.
180pub fn carriage_fee_from_meters(reading: &MeterReading, cents_per_unit_micro: u64) -> u64 {
181    let units = reading.milli_units / 1000;
182    ((units as u128).saturating_mul(cents_per_unit_micro as u128) / 1_000_000u128) as u64
183}
184
185/// Accumulates measured resource usage into an asset's compensation pool.
186pub fn accumulate_meter_to_pool(
187    pool: u64,
188    reading: &MeterReading,
189    cents_per_unit_micro: u64,
190) -> u64 {
191    let fee = carriage_fee_from_meters(reading, cents_per_unit_micro);
192    pool_after(pool, fee)
193}
194
195// ─── Persistent `.q42j` Obligation Pool NQuin Binding (WP-07) ────────────────────
196
197/// Modality opcode for persistent CommonsObligation pool checkpoints in `.q42j` journals.
198pub const OP_COMMONS_OBLIGATION_POOL: u8 = 0x58;
199/// Routing lane bit-pattern (`metadata[61..62] = 0b01`) for EnforcePermissiveCommons.
200pub const METADATA_LANE_PERMISSIVE_COMMONS: u64 = 0b01u64 << 61;
201/// Routing lane bit-pattern (`metadata[61..62] = 0b10`) for Bilateral / Active Obligation recovery.
202pub const METADATA_LANE_OBLIGATION_RECOVERY: u64 = 0b10u64 << 61;
203
204/// Encode a persistent `CommonsObligation` pool checkpoint as a 48-byte [`crate::NQuin`] for `.q42j`.
205#[inline]
206pub fn encode_obligation_pool_quin(
207    asset_did_hash: u64,
208    accumulated_pool_cents: u64,
209    capped_cost_cents: u64,
210    context_did_hash: u64,
211    lamport_clock: u32,
212) -> crate::NQuin {
213    let prop_hash = crate::q_hash("https://ns.webcivics.net/economics#obligationPoolState");
214    let predicate = (prop_hash << 8) | (OP_COMMONS_OBLIGATION_POOL as u64);
215    let object = (0b001u64 << 60) | (accumulated_pool_cents & 0x0FFF_FFFF_FFFF_FFFF);
216    let discharged = is_commons_discharged(accumulated_pool_cents, capped_cost_cents);
217    let lane_bits = if discharged {
218        METADATA_LANE_PERMISSIVE_COMMONS
219    } else {
220        METADATA_LANE_OBLIGATION_RECOVERY
221    };
222    let clock_bits = ((lamport_clock as u64) & 0x1FFF_FFFF) << 32;
223    let cost_low32 = capped_cost_cents.min(u32::MAX as u64) as u64;
224    let metadata = lane_bits | clock_bits | cost_low32;
225    let parity = asset_did_hash ^ predicate ^ object ^ context_did_hash ^ metadata;
226    crate::NQuin {
227        subject: asset_did_hash,
228        predicate,
229        object,
230        context: context_did_hash,
231        metadata,
232        parity,
233    }
234}
235
236/// Replay a slice of `.q42j` journal `NQuin`s for `asset_did_hash` in zero heap memory,
237/// returning `(accumulated_pool_cents, capped_cost_cents, is_discharged_to_commons)`.
238pub fn replay_obligation_pool_journal(
239    journal_quins: &[crate::NQuin],
240    asset_did_hash: u64,
241) -> Option<(u64, u64, bool)> {
242    let mut best_clock: Option<u32> = None;
243    let mut latest_pool = 0u64;
244    let mut latest_cost = 0u64;
245    let mut discharged = false;
246
247    for q in journal_quins {
248        if q.subject != asset_did_hash {
249            continue;
250        }
251        if (q.predicate & 0xFF) as u8 != OP_COMMONS_OBLIGATION_POOL {
252            continue;
253        }
254        let expected_parity = q.subject ^ q.predicate ^ q.object ^ q.context ^ q.metadata;
255        if q.parity != expected_parity {
256            continue;
257        }
258        let clock = ((q.metadata >> 32) & 0x1FFF_FFFF) as u32;
259        if best_clock.map_or(true, |prev| clock >= prev) {
260            best_clock = Some(clock);
261            latest_pool = q.object & 0x0FFF_FFFF_FFFF_FFFF;
262            latest_cost = q.metadata & 0xFFFF_FFFF;
263            discharged = (q.metadata & (0b11u64 << 61)) == METADATA_LANE_PERMISSIVE_COMMONS
264                || is_commons_discharged(latest_pool, latest_cost);
265        }
266    }
267
268    best_clock.map(|_| (latest_pool, latest_cost, discharged))
269}
270
271// ─── Zero-Heap Basis-Point Pool Clearing (`Pool Funded != Contributor Paid`) ─────
272
273/// Result of zero-heap basis-point pool clearing (`QUALIADB-IMPLEMENTATION-ROADMAP.md` §13).
274#[repr(C)]
275#[derive(Debug, Clone, Copy, PartialEq, Eq)]
276pub struct PoolClearingResult {
277    pub gross_receipt_cents: i64,
278    pub operating_reserve_cents: i64,
279    pub fiduciary_fee_cents: i64,
280    pub obligation_pool_allocation_cents: i64,
281    pub pool_funded_cents: i64,
282    pub settled_verified_cents: i64,
283    pub remaining_obligation_cents: i64,
284    /// `true` only when `settled_verified_cents + waived_cents >= target_obligation_cents`.
285    /// `pool_funded_cents >= target_obligation_cents` alone NEVER sets this to `true`.
286    pub contributor_obligations_discharged: bool,
287}
288
289#[inline]
290fn div_round_bankers_u128(n: u128, d: u128) -> u128 {
291    let q = n / d;
292    let r = n % d;
293    let twice_r = r * 2;
294    if twice_r > d || (twice_r == d && (q & 1) == 1) {
295        q + 1
296    } else {
297        q
298    }
299}
300
301/// Zero-heap integer basis-point clearing (`clear_pool_obligations_bps`) verifying
302/// `Pool Funded != Contributor Paid` conservation (`Gross = O + F + A`).
303#[inline]
304pub fn clear_pool_obligations_bps(
305    gross_receipt_cents: i64,
306    operating_reserve_bps: u32,
307    fiduciary_fee_bps: u32,
308    prior_pool_funded_cents: i64,
309    target_obligation_cents: i64,
310    settled_verified_cents: i64,
311    waived_obligation_cents: i64,
312) -> Option<PoolClearingResult> {
313    if gross_receipt_cents < 0
314        || prior_pool_funded_cents < 0
315        || target_obligation_cents < 0
316        || settled_verified_cents < 0
317        || waived_obligation_cents < 0
318        || operating_reserve_bps.saturating_add(fiduciary_fee_bps) > 10_000
319    {
320        return None;
321    }
322    let gross_u = gross_receipt_cents as u128;
323    let o_cents = div_round_bankers_u128(gross_u * (operating_reserve_bps as u128), 10_000) as i64;
324    let f_cents = div_round_bankers_u128(gross_u * (fiduciary_fee_bps as u128), 10_000) as i64;
325    let a_cents = gross_receipt_cents.saturating_sub(o_cents).saturating_sub(f_cents);
326    let pool_funded_cents = prior_pool_funded_cents.saturating_add(a_cents);
327    let discharged_amount = settled_verified_cents.saturating_add(waived_obligation_cents);
328    let remaining_obligation_cents = (target_obligation_cents - discharged_amount).max(0);
329    let contributor_obligations_discharged =
330        target_obligation_cents > 0 && remaining_obligation_cents == 0;
331    Some(PoolClearingResult {
332        gross_receipt_cents,
333        operating_reserve_cents: o_cents,
334        fiduciary_fee_cents: f_cents,
335        obligation_pool_allocation_cents: a_cents,
336        pool_funded_cents,
337        settled_verified_cents,
338        remaining_obligation_cents,
339        contributor_obligations_discharged,
340    })
341}
342
343#[cfg(test)]
344mod tests {
345    use super::*;
346
347    #[test]
348    fn eroi_gates_thermodynamic_viability() {
349        assert!((eroi(300, 100) - 3.0).abs() < 1e-6);
350        assert_eq!(eroi(5, 0), 0.0);
351        assert!(eroi_viable(300, 100, 2.0));
352        assert!(!eroi_viable(150, 100, 2.0), "net-extractive → refused");
353    }
354
355    #[test]
356    fn recursive_royalty_tree() {
357        assert_eq!(ancestor_royalty(100, 0, 50), 50);
358        assert_eq!(ancestor_royalty(100, 1, 50), 25);
359        assert_eq!(ancestor_royalty(100, 2, 50), 12);
360        assert_eq!(royalty_tree_total(100, 3, 50), 87);
361    }
362
363    #[test]
364    fn multi_currency_and_tax() {
365        assert_eq!(convert_currency(100, 1_500_000), 150);
366        assert_eq!(convert_currency(100, 500_000), 50);
367        assert_eq!(apply_tax(10_000, 250), 250);
368    }
369
370    #[test]
371    fn liquidity_ode_converges_to_steady_state() {
372        let one = liquidity_step(0, 100, 10);
373        assert_eq!(one, 100);
374        let settled = liquidity_after(0, 100, 10, 500);
375        assert!((settled as i64 - 1000).abs() <= 1);
376        assert!(liquidity_after(1000, 0, 50, 5) < 1000);
377    }
378
379    #[test]
380    fn roi_is_capped() {
381        assert_eq!(commons_cost(1000, 50, 20), 1200);
382        assert_eq!(commons_cost(1000, 10, 20), 1100);
383    }
384
385    #[test]
386    fn royalty_scales_by_agent_category() {
387        assert_eq!(royalty(100, 300), 300);
388        assert_eq!(royalty(100, 50), 50);
389    }
390
391    #[test]
392    fn usury_breaker_trips_past_the_110_percent_ceiling() {
393        assert_eq!(usury_ceiling(1000, USURY_OVERAGE_PERCENT_DEFAULT), 1100);
394        assert!(check_usury(1000, 1000, USURY_OVERAGE_PERCENT_DEFAULT).is_ok());
395        assert!(check_usury(1100, 1000, USURY_OVERAGE_PERCENT_DEFAULT).is_ok());
396        assert!(!is_usurious(1100, 1000, USURY_OVERAGE_PERCENT_DEFAULT));
397        let err = check_usury(1101, 1000, USURY_OVERAGE_PERCENT_DEFAULT).unwrap_err();
398        assert_eq!(err.ceiling, 1100);
399        assert_eq!(err.projected, 1101);
400        assert!(is_usurious(1101, 1000, USURY_OVERAGE_PERCENT_DEFAULT));
401        assert!(check_usury(1, 0, USURY_OVERAGE_PERCENT_DEFAULT).is_err());
402        assert!(check_usury(0, 0, USURY_OVERAGE_PERCENT_DEFAULT).is_ok());
403        assert_eq!(usury_ceiling(1000, 0), 1000);
404        assert!(check_usury(1001, 1000, 0).is_err());
405    }
406
407    #[test]
408    fn pool_discharges_at_threshold() {
409        let cost = commons_cost(1000, 20, 20);
410        let mut pool = 0u64;
411        pool = pool_after(pool, royalty(400, 300));
412        assert!(is_commons_discharged(pool, cost));
413        assert_eq!(outstanding(pool, cost), 0);
414        assert!(!is_commons_discharged(500, cost));
415        assert_eq!(outstanding(500, cost), 700);
416    }
417
418    #[test]
419    fn test_qdnf_metering_binding() {
420        use crate::net::qdnf::authority::ObservationQuality;
421        use crate::net::qdnf::economics::meters::MeterKind;
422
423        let reading = MeterReading {
424            kind: MeterKind::NetBytes,
425            milli_units: 50_000,
426            quality: ObservationQuality::Measured,
427        };
428        let fee = carriage_fee_from_meters(&reading, 2_000_000);
429        assert_eq!(fee, 100);
430        let mut pool = 1000u64;
431        pool = accumulate_meter_to_pool(pool, &reading, 2_000_000);
432        assert_eq!(pool, 1100);
433    }
434
435    #[test]
436    fn clear_pool_obligations_bps_enforces_pool_funded_not_contributor_paid() {
437        let res = clear_pool_obligations_bps(100_000, 1_000, 500, 50_000, 120_000, 40_000, 0)
438            .expect("valid bps clearing");
439        assert_eq!(
440            res.operating_reserve_cents
441                + res.fiduciary_fee_cents
442                + res.obligation_pool_allocation_cents,
443            100_000
444        );
445        assert_eq!(res.pool_funded_cents, 135_000);
446        assert_eq!(res.remaining_obligation_cents, 80_000);
447        assert!(!res.contributor_obligations_discharged);
448
449        let paid = clear_pool_obligations_bps(100_000, 1_000, 500, 50_000, 120_000, 100_000, 20_000)
450            .unwrap();
451        assert_eq!(paid.remaining_obligation_cents, 0);
452        assert!(paid.contributor_obligations_discharged);
453    }
454}