Merge pull request #19 from SHOGGOTH-SECTOR/feat/stomach-economic-organ

Finish M3e tokenomics/macro V1 runtime
This commit is contained in:
2026-10-24 03:22:00 -07:00
committed by GitHub
11 changed files with 595 additions and 24 deletions
+18 -1
View File
@@ -6,6 +6,9 @@ on:
- feat/stomach-economic-organ - feat/stomach-economic-organ
paths: paths:
- "core/src/economy/sims/tokenomics/**" - "core/src/economy/sims/tokenomics/**"
- "core/src/economy/stomach.tcl"
- "core/src/economy/feeds.tcl"
- "core/src/economy/sims/hub.tcl"
- ".github/workflows/m3e-tokenomics.yml" - ".github/workflows/m3e-tokenomics.yml"
pull_request: pull_request:
paths: paths:
@@ -29,7 +32,21 @@ jobs:
- name: Compile M3e native tests - name: Compile M3e native tests
run: | run: |
mkdir -p /tmp/sica-m3e mkdir -p /tmp/sica-m3e
gfortran -std=f2018 -Wall -Wextra -Werror -pedantic -J /tmp/sica-m3e src/tokenomics_engine.f90 test/test_tokenomics.f90 -o /tmp/sica-m3e/test_tokenomics gfortran -std=f2018 -Wall -Wextra -Werror -pedantic \
-J /tmp/sica-m3e src/tokenomics_engine.f90 test/test_tokenomics.f90 \
-o /tmp/sica-m3e/test_tokenomics
gfortran -std=f2018 -Wall -Wextra -Werror -pedantic \
-J /tmp/sica-m3e src/tokenomics_engine.f90 src/tokenomics_query.f90 \
-o /tmp/sica-m3e/tokenomics_query
echo "M3E_QUERY_BIN=/tmp/sica-m3e/tokenomics_query" >> "$GITHUB_ENV"
- name: Run M3e native tests - name: Run M3e native tests
run: /tmp/sica-m3e/test_tokenomics run: /tmp/sica-m3e/test_tokenomics
- name: Run M2 → M3e → Hub integration
shell: bash
working-directory: .
run: |
set -euo pipefail
tclsh core/src/economy/sims/tokenomics/integration.test | tee /tmp/m3e-integration.out
grep -Eq 'Total[[:space:]]+4[[:space:]]+Passed[[:space:]]+4.*Failed[[:space:]]+0' /tmp/m3e-integration.out
+35 -16
View File
@@ -13,12 +13,16 @@ frameworks [6], Aave/Compound kinked interest rate models (industry standard), a
inter-protocol credit propagation (Matzakos et al. 2025). inter-protocol credit propagation (Matzakos et al. 2025).
## 2. Status / certainty ## 2. Status / certainty
KERNEL IMPLEMENTED · Fortran 2018. `core/src/economy/sims/tokenomics/` implements IMPLEMENTED · M3e V1 · Fortran 2018. `core/src/economy/sims/tokenomics/`
Euler-Maruyama state evolution, stock-flow conservation checks, kinked lending curves, implements conserved aggregate token state, Euler–Maruyama stochastic evolution, scalar Kalman
directional exposure propagation, risk-adjusted yield allocation, and liquidation shortfall. state estimation, discrete halving and burn policy flows, kinked lending curves, iterative
Native tests compile cleanly under strict gfortran flags. Full state estimation, calibrated VAR liquidation cascades, directional DeXposure propagation, VAR impulse responses, exact constrained
impulse response, and policy-event orchestration remain incremental. Foundations C4/C5; quadratic yield allocation, and all ten bounded prediction types. `tokenomics_query.f90` reads
implementation C2; specific parameters C1. normalized M2 `on_chain_event` history, rejects stock-flow violations, calibrates the aggregate
state natively, scores walk-forward innovation accuracy, and returns a bounded result to the Tcl
runner; `runner.tcl` publishes that result into M3 as `tokenomics_macro`. Strict gfortran CI
verifies the numerical kernel and the M2→Fortran→Hub boundary. Foundations C4/C5; implementation
C3; live-token parameterization remains data-driven.
## 3. Language & location ## 3. Language & location
**Fortran 2018** (gfortran) · `src/economy/sims/tokenomics/`. Build: **fpm**. Dependencies: **Fortran 2018** (gfortran) · `src/economy/sims/tokenomics/`. Build: **fpm**. Dependencies:
@@ -78,9 +82,15 @@ across the heaviest numerical sims.
- Calibration: ingests `on_chain_event` (supply metrics, staking data, lending protocol state, - Calibration: ingests `on_chain_event` (supply metrics, staking data, lending protocol state,
TVL) from M2. TVL) from M2.
## 6. Dependencies & stubs ## 6. Dependencies & runtime boundary
- M2 Data Feeds — on-chain supply/staking/lending data; *stub:* canned supply snapshots. - M2 Data Feeds — normalized `on_chain_event` supplies aggregate stock/flow state, lending
- M3 Sims hub — lifecycle management; *stub:* manual init. balances, treasury state, policy parameters, directional exposure summary, and candidate
yield APY/volatility observations.
- Native query runtime — `tokenomics_query.f90` consumes the complete ticker history and
applies Kalman updates before prediction. Stock-flow conservation is checked for every row.
- M3 Sims hub — every M3e result is published in the common bounded schema as
`tokenomics_macro`; Traders read it only through Marketplace.
- M3e has no wallet, signer, strategy-execution, transaction, or live-chain broadcast surface.
## 7. Invariants / laws ## 7. Invariants / laws
- **L1 (C5):** the SDE framework is the **canonical representation** — all token dynamics are - **L1 (C5):** the SDE framework is the **canonical representation** — all token dynamics are
@@ -114,10 +124,19 @@ collateral; isolated protocols unaffected. Yield: optimizer rebalances toward hi
APY. Calibration: state estimate converges to observed data. Bounds: SDE confidence bands cover APY. Calibration: state estimate converges to observed data. Bounds: SDE confidence bands cover
realized paths on backtest. Speed: sim tick-advances at 90:1. realized paths on backtest. Speed: sim tick-advances at 90:1.
## 10. Open items ## 10. V1 decisions and future extensions
- Which tokens to model initially (ETH? BTC? a specific alt?). - **Token universe:** V1 is token-agnostic. M2 chooses the ticker and supplies its policy/state
- State vector dimensionality (how many state variables per token model?). observations; M3e does not hardcode ETH, BTC, or any chain.
- Behavioral policy function $u(X_t, t)$ — how to parameterize aggregate cohort behavior. - **State vector:** V1 calibrates total minted, circulating, staked, locked, burned, supplied,
- Multi-token interactions (correlated diffusions across tokens?). borrowed, collateral, treasury, and velocity, with latest policy/network/yield parameters.
- DeXposure graph granularity (how many protocols? top-10 by TVL?). Additional token-specific state can extend the observation schema later.
- Lending model extensions (Morpho AdaptiveCurveIRM? variable kink parameters?). - **Behavioral policy:** V1 represents aggregate behavior through observed state drift/diffusion,
staking/locking flows, utilization, treasury burn, yield candidates and exposure pressure.
Cohort-specific structural policy functions are a future fidelity layer.
- **Multi-token interaction:** V1 operates one ticker per query. Correlated multi-token
diffusions are a future cross-asset extension rather than a V1 dependency.
- **DeXposure granularity:** V1 accepts a directional aggregate exposure factor at the query
boundary while the native engine retains full directional matrix and VAR kernels. Explicit
protocol-graph ingestion can extend M2 without changing the M3 contract.
- **Lending curves:** the canonical kinked curve is V1. Morpho-style adaptive curves and other
protocol-specific IRMs are optional later models.
+2 -2
View File
@@ -6,7 +6,7 @@ Executable scaffold for M0–M7. The stomach is an OUTER organ: its only organis
- **M1 Marketplace** — single action ingress; wallet-first admission; deterministic action/chain law; wallet brake; Conductor veto after law; simulated execution only. - **M1 Marketplace** — single action ingress; wallet-first admission; deterministic action/chain law; wallet brake; Conductor veto after law; simulated execution only.
- **M2 Feeds** — normalized datum history with explicit backpressure instead of silent eviction. - **M2 Feeds** — normalized datum history with explicit backpressure instead of silent eviction.
- **M3 Sims** — all seven native engine trees are built in. M3a V1 is complete with calibrated HMM regimes, fitted spectral rough volatility, Heston characteristic-function surface calibration, fitted DCC/t-copula dependence, Bayesian/ARIMA/GARCH risk forecasting, empirical walk-forward quality scoring, all seven prediction types, and tested price+DEX-pool M2→R→Hub routing; M3b V1 is complete with persistent five-archetype populations, native bandit-replicator learning, adaptive bounded-confidence/contagion dynamics, HJB/FP MFG stability, pump/dump ABM behavior, nine bounded prediction types, M2 social+price calibration and empirical walk-forward scoring; M3c V1 is complete with native Solidity constant-product and concentrated-liquidity mechanics, LP/JIT and arbitrage populations, split routing, five bounded prediction types, and tested M2→EVM→Hub routing; M3d is Fortran MEV, M3e Fortran tokenomics, M3f ECLiPSe consensus, and M3g Fortran microstructure. A live Tcl event-loop clock runs all six horizons at 90:1 or faster. - **M3 Sims** — all seven native engine trees are built in. M3a V1 is complete with calibrated HMM regimes, fitted spectral rough volatility, Heston characteristic-function surface calibration, fitted DCC/t-copula dependence, Bayesian/ARIMA/GARCH risk forecasting, empirical walk-forward quality scoring, all seven prediction types, and tested price+DEX-pool M2→R→Hub routing; M3b V1 is complete with persistent five-archetype populations, native bandit-replicator learning, adaptive bounded-confidence/contagion dynamics, HJB/FP MFG stability, pump/dump ABM behavior, nine bounded prediction types, M2 social+price calibration and empirical walk-forward scoring; M3c V1 is complete with native Solidity constant-product and concentrated-liquidity mechanics, LP/JIT and arbitrage populations, split routing, five bounded prediction types, and tested M2→EVM→Hub routing; M3d is Fortran MEV; M3e V1 is complete with conserved macro state, native Kalman calibration, SDE supply dynamics, halving/burn policy, kinked lending and liquidation cascades, directional VAR contagion, exact yield allocation, ten bounded prediction types, and tested on-chain-event→Fortran→Hub routing; M3f is ECLiPSe consensus, and M3g is Fortran microstructure. A live Tcl event-loop clock runs all six horizons at 90:1 or faster.
- **M4 Wallets** — permanent 1:1 trader binding plus per-action/session exposure brakes. No private-key field, signer, or RPC surface exists yet. - **M4 Wallets** — permanent 1:1 trader binding plus per-action/session exposure brakes. No private-key field, signer, or RPC surface exists yet.
- **M5 Traders** — trader registry and mechanical pause state. AI trader inference is not implemented here. - **M5 Traders** — trader registry and mechanical pause state. AI trader inference is not implemented here.
- **M6 Conductor** — veto-next, pause/resume, SAE alert intake, append-only in-memory decision log. Specialist inference is not implemented yet. - **M6 Conductor** — veto-next, pause/resume, SAE alert intake, append-only in-memory decision log. Specialist inference is not implemented yet.
@@ -33,6 +33,6 @@ It executes Tcl + every native suite whose runtime is installed. Use `--strict`
## Public scaffold API ## Public scaffold API
`::stomach::Economy` exposes `register_trader`, `bind_wallet`, `submit_action`, `feed_publish`, `feed_history`, `sim_publish`, `query_predictions`, `statistical_runner_available`, `statistical_query`, `statistical_from_feed`, `amm_runner_available`, `amm_from_feed`, `sociological_runner_available`, `sociological_from_feed`, `sim_engines`, `sim_engine_status`, `sim_horizons`, `sim_running`, `sim_advance`, `conductor_veto_next`, `conductor_pause`, `conductor_resume`, `sae_alert`, `tax_event`, and `secretion`. `::stomach::Economy` exposes `register_trader`, `bind_wallet`, `submit_action`, `feed_publish`, `feed_history`, `sim_publish`, `query_predictions`, `statistical_runner_available`, `statistical_query`, `statistical_from_feed`, `amm_runner_available`, `amm_from_feed`, `sociological_runner_available`, `sociological_from_feed`, `tokenomics_runner_available`, `tokenomics_from_feed`, `sim_engines`, `sim_engine_status`, `sim_horizons`, `sim_running`, `sim_advance`, `conductor_veto_next`, `conductor_pause`, `conductor_resume`, `sae_alert`, `tax_event`, and `secretion`.
`secretion` returns the envelope-compatible metadata `source stomach`, `destination ada_border`, `provenance organ_secretion`. The runtime Pony↔Tcl bridge is still an integration task; no code may shortcut D1 while that bridge is built. `secretion` returns the envelope-compatible metadata `source stomach`, `destination ada_border`, `provenance organ_secretion`. The runtime Pony↔Tcl bridge is still an integration task; no code may shortcut D1 while that bridge is built.
+2 -2
View File
@@ -8,7 +8,7 @@ Seven native simulator engines live here behind the Tcl M3 hub.
| M3b | sociological | ECLiPSe Prolog | V1 complete: 5 archetypes, replicator + UCB learning, adaptive HK, complex contagion, HJB/FP MFG, pump/dump ABM, 9 bounded predictions, persistent populations, empirical scoring | | M3b | sociological | ECLiPSe Prolog | V1 complete: 5 archetypes, replicator + UCB learning, adaptive HK, complex contagion, HJB/FP MFG, pump/dump ABM, 9 bounded predictions, persistent populations, empirical scoring |
| M3c | AMM/liquidity | Solidity + Foundry | V1 complete: x*y=k, IL/slippage, concentrated positions, LP/JIT strategies, backrun/sandwich pops, two-pool routing, 5 bounded predictions, price+pool calibration | | M3c | AMM/liquidity | Solidity + Foundry | V1 complete: x*y=k, IL/slippage, concentrated positions, LP/JIT strategies, backrun/sandwich pops, two-pool routing, 5 bounded predictions, price+pool calibration |
| M3d | MEV/adversarial | Fortran 2018 | all-pay PGA, block knapsack, cross-chain path comparison, sandwich score | | M3d | MEV/adversarial | Fortran 2018 | all-pay PGA, block knapsack, cross-chain path comparison, sandwich score |
| M3e | tokenomics/macro | Fortran 2018 | Euler-Maruyama, stock-flow conservation, kinked lending, directional contagion, yield weights | | M3e | tokenomics/macro | Fortran 2018 | V1 complete: conserved token state, Euler-Maruyama, Kalman calibration, halving/burn policy, kinked lending, liquidation cascades, directional VAR contagion, exact yield optimizer, 10 bounded predictions |
| M3f | consensus/staking | ECLiPSe Prolog | honesty replicator, validator Markov transitions, incentive threshold, liveness | | M3f | consensus/staking | ECLiPSe Prolog | honesty replicator, validator Markov transitions, incentive threshold, liveness |
| M3g | microstructure | Fortran 2018 | depth/slippage, spread, Almgren-Chriss schedule, arb decay, impact fit | | M3g | microstructure | Fortran 2018 | depth/slippage, spread, Almgren-Chriss schedule, arb decay, impact fit |
@@ -22,6 +22,6 @@ tclsh core/src/economy/sims/run_tests.tcl
Pass `--strict` when the environment is expected to contain every external runtime. Pass `--strict` when the environment is expected to contain every external runtime.
The Fortran engines are verified with `gfortran -std=f2018 -Wall -Wextra -Werror -pedantic`. M3a has a dedicated GitHub Actions R job that runs both the native statistical suite and the `M2 price_tick → R → M3 hub` Tcl integration suite. R is installed by the repo SessionStart hook in remote sessions. ECLiPSe and Foundry remain separately hosted toolchains, matching the existing M3 design. M3c has a dedicated Foundry workflow that runs the native Solidity suite and a Tcl boundary test against a stateless query contract on an ephemeral local Anvil instance; M3b has a dedicated ECLiPSe workflow covering the native sociological suite plus persistent M2→M3b→Hub population evolution and walk-forward correctness. The Fortran engines are verified with `gfortran -std=f2018 -Wall -Wextra -Werror -pedantic`. M3a has a dedicated GitHub Actions R job that runs both the native statistical suite and the `M2 price_tick → R → M3 hub` Tcl integration suite. R is installed by the repo SessionStart hook in remote sessions. ECLiPSe and Foundry remain separately hosted toolchains, matching the existing M3 design. M3c has a dedicated Foundry workflow that runs the native Solidity suite and a Tcl boundary test against a stateless query contract on an ephemeral local Anvil instance; M3b has a dedicated ECLiPSe workflow covering the native sociological suite plus persistent M2→M3b→Hub population evolution and walk-forward correctness. M3e has a dedicated strict-Fortran workflow that compiles both the numerical test binary and native query executable, then verifies the M2 on-chain-event → Fortran → M3 hub boundary.
This directory contains simulators only. Nothing here broadcasts transactions or bypasses M1 Marketplace, M4 wallet brakes, or D1. This directory contains simulators only. Nothing here broadcasts transactions or bypasses M1 Marketplace, M4 wallet brakes, or D1.
@@ -0,0 +1,25 @@
# M3e — tokenomics & macro-state simulator
M3e V1 is the Fortran-native macro simulator behind the stomach's `tokenomics_macro` prediction type.
Implemented kernels include conserved token stock/flow state, Euler–Maruyama SDE evolution, scalar Kalman state estimation, discrete halving and burn policy, kinked lending rates, iterative liquidation cascades, directional exposure propagation, VAR impulse response, exact constrained quadratic yield allocation, and liquidation shortfall.
The live boundary is:
`M2 on_chain_event → TokenomicsRunner (Tcl) → tokenomics_query.f90 → SimsHub → Marketplace`
Each query consumes the complete normalized history for one ticker. The native executable rejects stock-flow violations, calibrates aggregate state through sequential Kalman updates, derives confidence/correctness/certainty from evidence quality and walk-forward innovation error, computes the requested bounded prediction, and returns it to Tcl for hub publication.
The ten public prediction types are `supply_trajectory`, `inflation_rate`, `staking_ratio`, `velocity_estimate`, `halving_impact`, `treasury_runway`, `utilization_rate`, `liquidation_cascade_risk`, `systemic_contagion_index`, and `optimal_yield_allocation`.
The `optimal_yield_allocation` scalar is the largest portfolio weight; the full three-weight allocation is retained as prediction metadata. All hub-facing outputs remain numeric and bounded.
M3e models aggregate token/protocol state only. It does not hold keys, sign messages, submit swaps, rebalance capital, or broadcast transactions.
Verification is performed by dedicated CI with strict Fortran flags:
```sh
gfortran -std=f2018 -Wall -Wextra -Werror -pedantic
```
The job compiles the native kernel tests and query executable, requires `TOKENOMICS TESTS PASSED`, and enforces `4 passed / 0 failed` at the M2→M3e→Hub boundary.
@@ -0,0 +1,68 @@
package require tcltest 2
namespace import ::tcltest::*
set here [file dirname [file normalize [info script]]]
source [file join $here .. .. stomach.tcl]
proc seed_m3e {s ticker} {
for {set i 0} {$i < 18} {incr i} {
set minted [expr {1000000.0 + 1000.0*$i}]
set burned [expr {10000.0 + 25.0*$i}]
set staked [expr {300000.0 + 800.0*$i}]
set locked [expr {100000.0 - 200.0*$i}]
set circulating [expr {$minted-$burned-$staked-$locked}]
$s feed_publish on_chain_event chain [expr {$i*86400}] [dict create token_ticker $ticker total_minted $minted circulating $circulating staked $staked locked $locked burned $burned supplied [expr {500000.0+1000.0*$i}] borrowed [expr {280000.0+1500.0*$i}] collateral [expr {420000.0+700.0*$i}] ltv 0.80 treasury [expr {250000.0-1200.0*$i}] treasury_burn_rate 1200.0 velocity [expr {2.0+0.02*$i}] base_emission_rate 1000.0 halving_interval 1000.0 policy_time [expr {900.0+10.0*$i}] exposure_factor 0.35 yield_apy {0.06 0.08 0.07} yield_vol {0.10 0.12 0.08}] 9.0
}
}
test m3e-runner-available-1.0 {Fortran-backed tokenomics runner is available in M3e CI} -body {
set s [::stomach::Economy new -history_cap 256]
set out [$s tokenomics_runner_available]
$s destroy
set out
} -result 1
test m2-to-m3e-to-hub-1.0 {on-chain state produces bounded tokenomics prediction in M3 hub} -body {
set s [::stomach::Economy new -history_cap 256]
$s register_trader trader-macro tokenomics_macro
seed_m3e $s TEST
set p [$s tokenomics_from_feed TEST supply_trajectory weekly]
set q [$s query_predictions trader-macro tokenomics_macro]
set out [list [dict get $p sim_type] [dict get $p prediction_type] [expr {[dict get $p lower_bound] <= [dict get $p value]}] [expr {[dict get $p value] <= [dict get $p upper_bound]}] [dict get $q token_ticker] [dict get $p calibration_sources] [dict get $p state_estimator]]
$s destroy
set out
} -result {tokenomics_macro supply_trajectory 1 1 TEST on_chain_event kalman}
test m3e-all-types-bounded-1.0 {all ten tokenomics prediction types honor hub bounds} -body {
set s [::stomach::Economy new -history_cap 256]
seed_m3e $s TYPES
set types {
supply_trajectory inflation_rate staking_ratio velocity_estimate
halving_impact treasury_runway utilization_rate
liquidation_cascade_risk systemic_contagion_index
optimal_yield_allocation
}
set ok 1
foreach type $types {
set p [$s tokenomics_from_feed TYPES $type monthly]
if {[dict get $p lower_bound] > [dict get $p value] ||
[dict get $p value] > [dict get $p upper_bound] ||
[dict get $p confidence] < 0 || [dict get $p confidence] > 10 ||
[dict get $p correctness] < 0 || [dict get $p correctness] > 10 ||
[dict get $p certainty] < 0 || [dict get $p certainty] > 10} {
set ok 0
break
}
}
$s destroy
set ok
} -result 1
test m3e-insufficient-history-1.0 {M3e refuses queries without on-chain observations} -body {
set s [::stomach::Economy new -history_cap 256]
set code [catch {$s tokenomics_from_feed TEST inflation_rate annual} msg]
$s destroy
list $code $msg
} -result {1 insufficient_on_chain_history}
cleanupTests
+146
View File
@@ -0,0 +1,146 @@
namespace eval ::stomach {}
oo::class create ::stomach::TokenomicsRunner {
variable runtime
constructor {{runtime_cmd ""}} {
if {$runtime_cmd ne ""} {
set runtime $runtime_cmd
} elseif {[info exists ::env(M3E_QUERY_BIN)]} {
set runtime $::env(M3E_QUERY_BIN)
} else {
set runtime tokenomics_query
}
}
method available {} {
if {[file pathtype $runtime] eq "absolute"} {
return [expr {[file exists $runtime] && [file executable $runtime]}]
}
expr {[auto_execok $runtime] ne ""}
}
method _horizon {horizon} {
switch -- $horizon {
current { return [list 0.0 current] }
tick_hourly -
hourly { return [list 0.000114077116 1h] }
daily { return [list 0.002737850787 24h] }
weekly { return [list 0.019164955510 7d] }
monthly { return [list 0.082135523614 30d] }
annual { return [list 1.0 1y] }
five_year { return [list 5.0 5y] }
default { error "unknown_horizon" }
}
}
method _prediction_type {name} {
set allowed {
supply_trajectory inflation_rate staking_ratio velocity_estimate
halving_impact treasury_runway utilization_rate
liquidation_cascade_risk systemic_contagion_index
optimal_yield_allocation
}
if {[lsearch -exact $allowed $name] < 0} {
error "unknown_prediction_type"
}
return $name
}
method _number {payload key} {
if {![dict exists $payload $key]} { error "on_chain_missing_$key" }
set value [dict get $payload $key]
if {![string is double -strict $value]} { error "on_chain_invalid_$key" }
return [expr {double($value)}]
}
method _triple {payload key} {
if {![dict exists $payload $key]} { error "on_chain_missing_$key" }
set values [dict get $payload $key]
if {[llength $values] != 3} { error "on_chain_invalid_$key" }
set out {}
foreach value $values {
if {![string is double -strict $value] || $value < 0} {
error "on_chain_invalid_$key"
}
lappend out [expr {double($value)}]
}
return $out
}
method _observations {history ticker} {
set rows {}
foreach datum $history {
if {![dict exists $datum payload]} { continue }
set payload [dict get $datum payload]
if {![dict exists $payload token_ticker] ||
[dict get $payload token_ticker] ne $ticker} {
continue
}
set confidence [dict get $datum confidence]
if {![string is double -strict $confidence]} {
error "invalid_on_chain_confidence"
}
set apy [my _triple $payload yield_apy]
set vol [my _triple $payload yield_vol]
set row [list [dict get $datum timestamp] [my _number $payload total_minted] [my _number $payload circulating] [my _number $payload staked] [my _number $payload locked] [my _number $payload burned] [my _number $payload supplied] [my _number $payload borrowed] [my _number $payload collateral] [my _number $payload ltv] [my _number $payload treasury] [my _number $payload treasury_burn_rate] [my _number $payload velocity] [my _number $payload base_emission_rate] [my _number $payload halving_interval] [my _number $payload policy_time] [my _number $payload exposure_factor] [lindex $apy 0] [lindex $vol 0] [lindex $apy 1] [lindex $vol 1] [lindex $apy 2] [lindex $vol 2] [expr {double($confidence)}]]
lappend rows $row
}
return $rows
}
method _parse_result {output} {
set line ""
foreach candidate [split [string trim $output] "\n"] {
if {[string match "RESULT *" [string trim $candidate]]} {
set line [string trim $candidate]
}
}
if {$line eq ""} { error "invalid_tokenomics_output" }
set fields [regexp -all -inline {[^[:space:]]+} $line]
if {[llength $fields] != 11 || [lindex $fields 0] ne "RESULT"} {
error "invalid_tokenomics_output"
}
set nums {}
foreach value [lrange $fields 1 end] {
if {![string is double -strict $value]} {
error "invalid_tokenomics_output"
}
lappend nums [expr {double($value)}]
}
return $nums
}
method query_history {ticker prediction_type horizon history} {
if {![my available]} { error "tokenomics_runtime_unavailable" }
set prediction_type [my _prediction_type $prediction_type]
lassign [my _horizon $horizon] horizon_years horizon_label
set rows [my _observations $history $ticker]
if {[llength $rows] < 2} { error "insufficient_on_chain_history" }
set payload "[llength $rows]\n"
foreach row $rows {
append payload "[join $row { }]\n"
}
set output [exec $runtime $prediction_type $horizon_years << $payload]
lassign [my _parse_result $output] value lower upper confidence correctness certainty recent_shift detail1 detail2 detail3
if {$lower > $value || $value > $upper} {
error "tokenomics_prediction_out_of_bounds"
}
foreach metric [list $confidence $correctness $certainty] {
if {$metric < 0 || $metric > 10} {
error "tokenomics_quality_out_of_range"
}
}
set result [dict create value $value lower_bound $lower upper_bound $upper confidence $confidence correctness $correctness certainty $certainty time_horizon $horizon_label sim_type tokenomics_macro token_ticker $ticker recent_shift $recent_shift prediction_type $prediction_type calibration_sources on_chain_event state_estimator kalman timestamp [clock seconds]]
if {$prediction_type eq "optimal_yield_allocation"} {
dict set result allocation_weights [join [list $detail1 $detail2 $detail3] ,]
}
return $result
}
}
@@ -210,4 +210,99 @@ contains
real(8), intent(in) :: collateral,ltv,borrowed real(8), intent(in) :: collateral,ltv,borrowed
shortfall=max(0d0,borrowed-collateral*ltv) shortfall=max(0d0,borrowed-collateral*ltv)
end function end function
pure real(8) function clamp_real(x, lo, hi) result(y)
real(8), intent(in) :: x, lo, hi
y = min(hi,max(lo,x))
end function clamp_real
subroutine tokenomics_prediction(kind, horizon_years, total_minted, circulating, staked, locked, burned, &
supplied, borrowed, collateral, ltv, treasury, treasury_burn_rate, velocity, base_emission_rate, &
halving_interval, policy_time, exposure_factor, apy, vol, uncertainty, value, lower, upper, detail)
character(len=*), intent(in) :: kind
real(8), intent(in) :: horizon_years, total_minted, circulating, staked, locked, burned
real(8), intent(in) :: supplied, borrowed, collateral, ltv, treasury, treasury_burn_rate
real(8), intent(in) :: velocity, base_emission_rate, halving_interval, policy_time, exposure_factor
real(8), intent(in) :: apy(:), vol(:), uncertainty
real(8), intent(out) :: value, lower, upper
real(8), intent(out) :: detail(3)
real(8) :: emission, days, width, denom, risk, ratio, weights(size(apy))
logical :: unit_interval
if (size(apy) /= size(vol) .or. size(apy) < 1) error stop 'yield shape'
days = max(0d0,horizon_years)*365.25d0
emission = halving_emission_rate(base_emission_rate,policy_time,halving_interval)
detail = 0d0
unit_interval = .false.
select case (trim(kind))
case ('supply_trajectory')
value = max(0d0,total_minted + emission*days)
width = max(1d-9,uncertainty*max(value,1d0))
case ('inflation_rate')
denom = max(total_minted-burned,1d-12)
value = 100d0*emission*365.25d0/denom
width = max(1d-9,uncertainty*max(abs(value),0.1d0))
case ('staking_ratio')
denom = max(circulating+staked+locked,1d-12)
value = clamp_real(staked/denom,0d0,1d0)
width = max(1d-6,uncertainty)
unit_interval = .true.
case ('velocity_estimate')
value = max(0d0,velocity)
width = max(1d-9,uncertainty*max(value,0.1d0))
case ('halving_impact')
if (base_emission_rate <= 1d-15) then
value = 0d0
else
value = clamp_real(1d0-emission/base_emission_rate,0d0,1d0)
end if
width = max(1d-6,0.5d0*uncertainty)
unit_interval = .true.
case ('treasury_runway')
if (treasury_burn_rate <= 1d-15) then
value = 1d12
else
value = max(0d0,treasury/treasury_burn_rate)
end if
width = max(1d-9,uncertainty*max(value,1d0))
case ('utilization_rate')
denom = max(supplied+borrowed,1d-12)
value = clamp_real(borrowed/denom,0d0,1d0)
width = max(1d-6,uncertainty)
unit_interval = .true.
case ('liquidation_cascade_risk')
denom = max(borrowed,1d-12)
risk = liquidation_shortfall(collateral,clamp_real(ltv,0d0,1d0),borrowed)/denom
value = clamp_real(risk*(1d0+max(0d0,exposure_factor)),0d0,1d0)
width = max(1d-6,uncertainty)
unit_interval = .true.
case ('systemic_contagion_index')
ratio = borrowed/max(collateral*max(ltv,1d-12),1d-12)
value = clamp_real(max(0d0,exposure_factor)*ratio,0d0,1d0)
width = max(1d-6,1.25d0*uncertainty)
unit_interval = .true.
case ('optimal_yield_allocation')
call yield_weights(apy,vol,2d0,weights)
value = maxval(weights)
detail = 0d0
detail(1:min(3,size(weights))) = weights(1:min(3,size(weights)))
width = max(1d-6,uncertainty)
unit_interval = .true.
case default
error stop 'unknown prediction type'
end select
lower = value-width
upper = value+width
if (unit_interval) then
lower = clamp_real(lower,0d0,1d0)
upper = clamp_real(upper,0d0,1d0)
else
lower = max(0d0,lower)
end if
if (lower > value) lower = value
if (upper < value) upper = value
end subroutine tokenomics_prediction
end module end module
@@ -0,0 +1,170 @@
program tokenomics_query
use tokenomics_engine
implicit none
integer :: n, i, ios, innovation_count
character(len=64) :: kind, horizon_arg
real(8) :: horizon_years
real(8) :: timestamp, total_minted, circulating, staked, locked, burned
real(8) :: supplied, borrowed, collateral, ltv, treasury, treasury_burn_rate
real(8) :: velocity, base_emission_rate, halving_interval, policy_time, exposure_factor
real(8) :: apy(3), vol(3), confidence
real(8) :: m_total, v_total, m_circ, v_circ, m_staked, v_staked
real(8) :: m_locked, v_locked, m_burned, v_burned
real(8) :: m_supplied, v_supplied, m_borrowed, v_borrowed
real(8) :: m_collateral, v_collateral, m_treasury, v_treasury
real(8) :: m_velocity, v_velocity
real(8) :: obs_var, process_var, scale, confidence_sum
real(8) :: innovation_sum, innovation, uncertainty, correctness, certainty
real(8) :: value, lower, upper, detail(3), recent_shift, first_circulating
real(8) :: last_ltv, last_treasury_burn_rate, last_base_emission
real(8) :: last_halving_interval, last_policy_time, last_exposure_factor
real(8) :: last_apy(3), last_vol(3), relative_variance
call get_command_argument(1,kind)
call get_command_argument(2,horizon_arg)
if (len_trim(kind) == 0 .or. len_trim(horizon_arg) == 0) error stop 'query args'
read(horizon_arg,*,iostat=ios) horizon_years
if (ios /= 0 .or. horizon_years < 0d0) error stop 'invalid horizon'
read(*,*,iostat=ios) n
if (ios /= 0 .or. n < 2) error stop 'insufficient history'
confidence_sum = 0d0
innovation_sum = 0d0
innovation_count = 0
first_circulating = 0d0
do i=1,n
read(*,*,iostat=ios) timestamp, total_minted, circulating, staked, locked, burned, &
supplied, borrowed, collateral, ltv, treasury, treasury_burn_rate, velocity, &
base_emission_rate, halving_interval, policy_time, exposure_factor, &
apy(1), vol(1), apy(2), vol(2), apy(3), vol(3), confidence
if (ios /= 0) error stop 'invalid observation row'
if (timestamp < 0d0 .or. total_minted < 0d0 .or. circulating < 0d0 .or. &
staked < 0d0 .or. locked < 0d0 .or. burned < 0d0 .or. supplied < 0d0 .or. &
borrowed < 0d0 .or. collateral < 0d0 .or. treasury < 0d0 .or. &
treasury_burn_rate < 0d0 .or. velocity < 0d0 .or. base_emission_rate < 0d0 .or. &
halving_interval < 0d0 .or. policy_time < 0d0 .or. exposure_factor < 0d0 .or. &
any(apy < 0d0) .or. any(vol < 0d0) .or. confidence < 0d0 .or. confidence > 10d0) &
error stop 'invalid observation values'
if (.not. stock_flow_conserved(circulating,staked,locked,burned,total_minted, &
max(1d-6,1d-8*max(total_minted,1d0)))) error stop 'stock flow violation'
confidence_sum = confidence_sum + confidence
if (i == 1) then
first_circulating = circulating
call init_estimate(total_minted,m_total,v_total)
call init_estimate(circulating,m_circ,v_circ)
call init_estimate(staked,m_staked,v_staked)
call init_estimate(locked,m_locked,v_locked)
call init_estimate(burned,m_burned,v_burned)
call init_estimate(supplied,m_supplied,v_supplied)
call init_estimate(borrowed,m_borrowed,v_borrowed)
call init_estimate(collateral,m_collateral,v_collateral)
call init_estimate(treasury,m_treasury,v_treasury)
call init_estimate(velocity,m_velocity,v_velocity)
else
innovation = 0d0
innovation = innovation + relative_error(total_minted,m_total)
innovation = innovation + relative_error(circulating,m_circ)
innovation = innovation + relative_error(staked,m_staked)
innovation = innovation + relative_error(locked,m_locked)
innovation = innovation + relative_error(burned,m_burned)
innovation = innovation + relative_error(supplied,m_supplied)
innovation = innovation + relative_error(borrowed,m_borrowed)
innovation = innovation + relative_error(collateral,m_collateral)
innovation = innovation + relative_error(treasury,m_treasury)
innovation = innovation + relative_error(velocity,m_velocity)
innovation_sum = innovation_sum + innovation/10d0
innovation_count = innovation_count + 1
scale = max(0.01d0,(10d0-confidence)/10d0)
call update_estimate(total_minted,scale,m_total,v_total)
call update_estimate(circulating,scale,m_circ,v_circ)
call update_estimate(staked,scale,m_staked,v_staked)
call update_estimate(locked,scale,m_locked,v_locked)
call update_estimate(burned,scale,m_burned,v_burned)
call update_estimate(supplied,scale,m_supplied,v_supplied)
call update_estimate(borrowed,scale,m_borrowed,v_borrowed)
call update_estimate(collateral,scale,m_collateral,v_collateral)
call update_estimate(treasury,scale,m_treasury,v_treasury)
call update_estimate(velocity,scale,m_velocity,v_velocity)
end if
last_ltv = ltv
last_treasury_burn_rate = treasury_burn_rate
last_base_emission = base_emission_rate
last_halving_interval = halving_interval
last_policy_time = policy_time
last_exposure_factor = exposure_factor
last_apy = apy
last_vol = vol
end do
relative_variance = 0d0
relative_variance = relative_variance + v_total/max(m_total*m_total,1d0)
relative_variance = relative_variance + v_circ/max(m_circ*m_circ,1d0)
relative_variance = relative_variance + v_staked/max(m_staked*m_staked,1d0)
relative_variance = relative_variance + v_locked/max(m_locked*m_locked,1d0)
relative_variance = relative_variance + v_burned/max(m_burned*m_burned,1d0)
relative_variance = relative_variance + v_supplied/max(m_supplied*m_supplied,1d0)
relative_variance = relative_variance + v_borrowed/max(m_borrowed*m_borrowed,1d0)
relative_variance = relative_variance + v_collateral/max(m_collateral*m_collateral,1d0)
relative_variance = relative_variance + v_treasury/max(m_treasury*m_treasury,1d0)
relative_variance = relative_variance + v_velocity/max(m_velocity*m_velocity,1d0)
uncertainty = min(0.5d0,sqrt(max(0d0,relative_variance/10d0)))
confidence = min(10d0,max(0d0,confidence_sum/real(n,8)))
if (innovation_count > 0) then
correctness = 10d0*exp(-20d0*innovation_sum/real(innovation_count,8))
else
correctness = 5d0
end if
correctness = min(10d0,max(0d0,correctness))
certainty = 10d0/(1d0+20d0*uncertainty)
certainty = min(10d0,max(0d0,certainty))
call tokenomics_prediction(trim(kind),horizon_years,m_total,m_circ,m_staked,m_locked,m_burned, &
m_supplied,m_borrowed,m_collateral,last_ltv,m_treasury,last_treasury_burn_rate,m_velocity, &
last_base_emission,last_halving_interval,last_policy_time,last_exposure_factor,last_apy,last_vol, &
uncertainty,value,lower,upper,detail)
if (first_circulating > 1d-15) then
recent_shift = m_circ/first_circulating-1d0
else
recent_shift = 0d0
end if
write(*,'(A,1X,10(ES24.16E3,1X))') 'RESULT', value, lower, upper, confidence, correctness, certainty, &
recent_shift, detail(1), detail(2), detail(3)
contains
subroutine init_estimate(observation,mean,var)
real(8), intent(in) :: observation
real(8), intent(out) :: mean,var
mean = observation
var = max(1d-12,(0.05d0*max(abs(observation),1d0))**2)
end subroutine init_estimate
subroutine update_estimate(observation,noise_scale,mean,var)
real(8), intent(in) :: observation,noise_scale
real(8), intent(inout) :: mean,var
real(8) :: posterior_mean,posterior_var
process_var = (0.002d0*max(abs(mean),1d0))**2
obs_var = (noise_scale*max(abs(observation),1d0))**2
call kalman_scalar_update(mean,var,observation,obs_var,process_var,posterior_mean,posterior_var)
mean = posterior_mean
var = posterior_var
end subroutine update_estimate
pure real(8) function relative_error(observation,estimate) result(err)
real(8), intent(in) :: observation,estimate
err = abs(observation-estimate)/max(abs(observation),1d0)
end function relative_error
end program tokenomics_query
@@ -6,6 +6,7 @@ program test_tokenomics
real(8) :: var_a(3,3), impulse(3,4) real(8) :: var_a(3,3), impulse(3,4)
real(8) :: opt_apy(3), opt_vol(3), opt_w(3), marginal(3) real(8) :: opt_apy(3), opt_vol(3), opt_w(3), marginal(3)
real(8) :: est_mean, est_var, next_mean, next_var real(8) :: est_mean, est_var, next_mean, next_var
real(8) :: em_shocks(1000), em_path(1001), em_mean, em_var, em_inc
integer :: est_i integer :: est_i
type(token_state) :: state0, state1 type(token_state) :: state0, state1
real(8) :: e_before, e_half, e_quarter real(8) :: e_before, e_half, e_quarter
@@ -77,5 +78,28 @@ program test_tokenomics
end do end do
if (abs(est_mean-100d0)>0.5d0) error stop 'state estimate convergence' if (abs(est_mean-100d0)>0.5d0) error stop 'state estimate convergence'
if (est_var >= 4d0) error stop 'state estimate uncertainty' if (est_var >= 4d0) error stop 'state estimate uncertainty'
do est_i=1,1000
if (mod(est_i,2) == 0) then
em_shocks(est_i) = 1d0
else
em_shocks(est_i) = -1d0
end if
end do
call euler_maruyama(10d0,0.03d0,0.20d0,0.01d0,em_shocks,em_path)
em_mean = 0d0
do est_i=1,1000
em_mean = em_mean + (em_path(est_i+1)-em_path(est_i))
end do
em_mean = em_mean/1000d0
em_var = 0d0
do est_i=1,1000
em_inc = em_path(est_i+1)-em_path(est_i)
em_var = em_var + (em_inc-em_mean)**2
end do
em_var = em_var/1000d0
if (abs(em_mean-0.0003d0)>1d-12) error stop 'sde mean law'
if (abs(em_var-0.0004d0)>1d-10) error stop 'sde variance law'
print *, 'TOKENOMICS TESTS PASSED' print *, 'TOKENOMICS TESTS PASSED'
end program end program
+10 -3
View File
@@ -8,14 +8,14 @@ foreach __stomach_file {
traders.tcl wallets.tcl sae.tcl conductor.tcl feeds.tcl traders.tcl wallets.tcl sae.tcl conductor.tcl feeds.tcl
sims/registry.tcl sims/scheduler.tcl sims/hub.tcl sims/registry.tcl sims/scheduler.tcl sims/hub.tcl
sims/statistical/runner.tcl sims/amm/runner.tcl sims/statistical/runner.tcl sims/amm/runner.tcl
sims/sociological/runner.tcl marketplace.tcl sims/sociological/runner.tcl sims/tokenomics/runner.tcl marketplace.tcl
} { } {
source [file join $__stomach_dir $__stomach_file] source [file join $__stomach_dir $__stomach_file]
} }
unset __stomach_file unset __stomach_file
oo::class create ::stomach::Economy { oo::class create ::stomach::Economy {
variable traders wallets sae conductor feeds sims registry clock statistical_runner amm_runner sociological_runner market taxes variable traders wallets sae conductor feeds sims registry clock statistical_runner amm_runner sociological_runner tokenomics_runner market taxes
constructor {args} { constructor {args} {
set cap 256 set cap 256
if {[llength $args] % 2 != 0} { error "options must be key/value pairs" } if {[llength $args] % 2 != 0} { error "options must be key/value pairs" }
@@ -37,11 +37,12 @@ oo::class create ::stomach::Economy {
set statistical_runner [::stomach::StatisticalRunner new [file join $::stomach::root sims statistical engine.R]] set statistical_runner [::stomach::StatisticalRunner new [file join $::stomach::root sims statistical engine.R]]
set amm_runner [::stomach::AMMRunner new] set amm_runner [::stomach::AMMRunner new]
set sociological_runner [::stomach::SociologicalRunner new [file join $::stomach::root sims sociological engine.ecl]] set sociological_runner [::stomach::SociologicalRunner new [file join $::stomach::root sims sociological engine.ecl]]
set tokenomics_runner [::stomach::TokenomicsRunner new]
set market [::stomach::Marketplace new $traders $wallets $conductor $sae $sims] set market [::stomach::Marketplace new $traders $wallets $conductor $sae $sims]
set taxes {} set taxes {}
} }
destructor { destructor {
foreach obj [list $market $sociological_runner $amm_runner $statistical_runner $clock $registry $sims $feeds $conductor $sae $wallets $traders] { foreach obj [list $market $tokenomics_runner $sociological_runner $amm_runner $statistical_runner $clock $registry $sims $feeds $conductor $sae $wallets $traders] {
catch {$obj destroy} catch {$obj destroy}
} }
} }
@@ -64,6 +65,12 @@ oo::class create ::stomach::Economy {
method statistical_runner_available {} { return [$statistical_runner available] } method statistical_runner_available {} { return [$statistical_runner available] }
method amm_runner_available {} { return [$amm_runner available] } method amm_runner_available {} { return [$amm_runner available] }
method sociological_runner_available {} { return [$sociological_runner available] } method sociological_runner_available {} { return [$sociological_runner available] }
method tokenomics_runner_available {} { return [$tokenomics_runner available] }
method tokenomics_from_feed {ticker prediction_type horizon} {
set p [$tokenomics_runner query_history $ticker $prediction_type $horizon [$feeds history on_chain_event]]
$sims publish tokenomics_macro $p
return $p
}
method sociological_from_feed {ticker prediction_type horizon} { method sociological_from_feed {ticker prediction_type horizon} {
set p [$sociological_runner query_history $ticker $prediction_type $horizon [$feeds history price_tick] [$feeds history rss_news]] set p [$sociological_runner query_history $ticker $prediction_type $horizon [$feeds history price_tick] [$feeds history rss_news]]
$sims publish sociological $p $sims publish sociological $p