Skip to content
Verified contractExactMIT

ProcFs

Address0x490dd86713d960e8d18b0d3b15c2ffe7eabc56e1
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,027,846
Creation transaction
0x1ecc07e8c6…692024f208

daemon/ProcFs.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

// app: daemons.fun


import {Kernel} from "./Kernel.sol";
import {Genome} from "./Genome.sol";

// PROCFS(5)                  Daemons File Formats                  PROCFS(5)
//
// NAME
//      procfs - read the process table without touching it
//
// DESCRIPTION
//      $ cat /proc/412/status
//      Pid:     412
//      PPid:    17
//      State:   R (running)
//      Gen:     3
//      Mode:    contrarian
//      Equity:  47900 / alloc 18400 / peak 51200
//
//      Nothing here is stored. Ancestry is the parent pointer walked up,
//      descent is the child lists walked down, and every call recomputes
//      from the kernel, so a reading can never disagree with the table.
//
// SEE ALSO
//      kernel(8), syslog(3)
//
// Daemons 1.0                    September 2026                      PROCFS(5)

contract ProcFs {
    Kernel public immutable kernel;
    Genome public immutable genome;

    uint256 public constant WALK_LIMIT = 512;

    struct Row {
        uint32 pid;
        uint32 ppid;
        uint16 gen;
        uint8 state;
        uint8 mode;
        uint128 equity;
        uint128 alloc;
        uint256 drawdownBps;
    }

    constructor(address _kernel) {
        kernel = Kernel(_kernel);
        genome = Kernel(_kernel).genomeLib();
    }

    /// @notice nearest ancestor first, ending at the founder
    function ancestry(uint32 pid) external view returns (uint32[] memory out) {
        uint32[] memory buf = new uint32[](WALK_LIMIT);
        uint256 n;
        uint32 cur = kernel.ppidOf(pid);
        while (cur != 0 && n < WALK_LIMIT) {
            buf[n++] = cur;
            cur = kernel.ppidOf(cur);
        }
        out = new uint32[](n);
        for (uint256 i = 0; i < n; i++) out[i] = buf[i];
    }

    function founderOf(uint32 pid) external view returns (uint32 root) {
        root = pid;
        uint32 cur = kernel.ppidOf(pid);
        uint256 guard;
        while (cur != 0 && guard++ < WALK_LIMIT) {
            root = cur;
            cur = kernel.ppidOf(cur);
        }
    }

    /// @notice every descendant, breadth first, up to WALK_LIMIT
    function descendants(uint32 pid) public view returns (uint32[] memory out) {
        uint32[] memory q = new uint32[](WALK_LIMIT);
        uint256 head;
        uint256 tailIdx;
        uint32[] memory first = kernel.kidsOf(pid);
        for (uint256 i = 0; i < first.length && tailIdx < WALK_LIMIT; i++) q[tailIdx++] = first[i];
        while (head < tailIdx) {
            uint32[] memory k = kernel.kidsOf(q[head++]);
            for (uint256 j = 0; j < k.length && tailIdx < WALK_LIMIT; j++) q[tailIdx++] = k[j];
        }
        out = new uint32[](tailIdx);
        for (uint256 i = 0; i < tailIdx; i++) out[i] = q[i];
    }

    function livingDescendants(uint32 pid) external view returns (uint256 n) {
        uint32[] memory all = descendants(pid);
        for (uint256 i = 0; i < all.length; i++) if (kernel.stateOf(all[i]) == 1) n++;
    }

    function isAncestor(uint32 candidate, uint32 pid) external view returns (bool) {
        uint32 cur = kernel.ppidOf(pid);
        uint256 guard;
        while (cur != 0 && guard++ < WALK_LIMIT) {
            if (cur == candidate) return true;
            cur = kernel.ppidOf(cur);
        }
        return false;
    }

    /// @notice one ps(1) row
    function status(uint32 pid) public view returns (Row memory r) {
        Kernel.Proc memory p = kernel.proc(pid);
        r.pid = p.pid;
        r.ppid = p.ppid;
        r.gen = p.gen;
        r.state = p.state;
        r.mode = genome.modeOf(p.genome);
        r.equity = p.equity;
        r.alloc = p.alloc;
        r.drawdownBps = kernel.drawdownBps(pid);
    }

    /// @notice a window of the run queue as ps(1) rows
    function ps(uint256 from, uint256 count) external view returns (Row[] memory rows) {
        uint256 live = kernel.running();
        if (from >= live) return new Row[](0);
        if (from + count > live) count = live - from;
        rows = new Row[](count);
        for (uint256 i = 0; i < count; i++) rows[i] = status(kernel.runqAt(from + i));
    }

    /// @notice the running daemon with the highest equity multiple on its allocation
    function fittest() external view returns (uint32 best, uint256 multipleBps) {
        uint32[] memory q = kernel.runqSnapshot();
        for (uint256 i = 0; i < q.length; i++) {
            uint256 m = kernel.multipleBps(q[i]);
            if (m > multipleBps) {
                multipleBps = m;
                best = q[i];
            }
        }
    }

    /// @notice how many running daemons follow each mode: momentum, contrarian, long, short
    function modeCensus() external view returns (uint256[4] memory census) {
        uint32[] memory q = kernel.runqSnapshot();
        for (uint256 i = 0; i < q.length; i++) {
            census[genome.modeOf(kernel.proc(q[i]).genome)]++;
        }
    }

    function stateLetter(uint32 pid) external view returns (string memory) {
        uint8 s = kernel.stateOf(pid);
        if (s == 1) return "R";
        if (s == 2) return "Z";
        if (s == 3) return "X";
        return "-";
    }
}

daemon/Genome.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

// GENOME(5)                  Daemons File Formats                  GENOME(5)
//
// NAME
//      genome - the strategy word a daemon is born with and passes on
//
// LAYOUT
//      63          40 39     32 31     24 23             8 7    2 1  0
//      +-------------+---------+---------+----------------+------+----+
//      |   lineage   | patience|  lev x10|   threshold    | ---- |mode|
//      +-------------+---------+---------+----------------+------+----+
//        24 bits       8 bits    8 bits      16 bits              2 bits
//
// DESCRIPTION
//      A genome is one word. The mode says how a daemon reads the market:
//      0 follows the last move, 1 fades it, 2 is always long, 3 is always
//      short. The threshold is the smallest move, in basis points, worth
//      acting on. Leverage is stored times ten. Patience is how many extra
//      rounds a daemon waits before it may fork. The lineage tag is set
//      once for a founder and copied, unchanged, to every descendant.
//
//      A fork copies the parent genome and perturbs it. The seed mixes the
//      parent pid, the child pid, the round and the kernel's entropy, so
//      the child's genes are reproducible by anyone and chosen by no one.
//
// SEE ALSO
//      kernel(8), signal(3)
//
// Daemons 1.0                    September 2026                      GENOME(5)

contract Genome {
    struct Genes {
        uint8 mode;
        uint16 thresholdBps;
        uint8 leverageX10;
        uint8 patience;
        uint24 lineage;
    }

    uint8 public constant MODE_MOMENTUM = 0;
    uint8 public constant MODE_CONTRARIAN = 1;
    uint8 public constant MODE_LONG = 2;
    uint8 public constant MODE_SHORT = 3;

    uint16 public constant THRESHOLD_MAX = 2_000;
    uint8 public constant LEV_MIN = 5;
    uint8 public constant LEV_MAX = 50;
    uint8 public constant PATIENCE_MAX = 24;

    function pack(Genes memory g) public pure returns (bytes32) {
        uint256 w = uint256(g.mode & 3);
        w |= uint256(g.thresholdBps) << 8;
        w |= uint256(g.leverageX10) << 24;
        w |= uint256(g.patience) << 32;
        w |= uint256(g.lineage) << 40;
        return bytes32(w);
    }

    function unpack(bytes32 word) public pure returns (Genes memory g) {
        uint256 w = uint256(word);
        g.mode = uint8(w & 3);
        g.thresholdBps = uint16(w >> 8);
        g.leverageX10 = uint8(w >> 24);
        g.patience = uint8(w >> 32);
        g.lineage = uint24(w >> 40);
    }

    /// @notice a founder genome, drawn entirely from the seed
    function founder(bytes32 seed) external pure returns (bytes32) {
        uint256 u = uint256(seed);
        Genes memory g;
        g.mode = uint8(u % 4);
        g.thresholdBps = uint16(40 + (u >> 8) % 360);
        g.leverageX10 = uint8(LEV_MIN + (u >> 24) % 26);
        g.patience = uint8((u >> 32) % 12);
        g.lineage = uint24(u >> 64);
        return pack(g);
    }

    /// @notice a child genome: mode rarely flips, numbers drift, lineage never changes
    function mutate(bytes32 parent, uint32 parentPid, uint32 childPid, uint32 round, bytes32 entropy)
        external
        pure
        returns (bytes32)
    {
        uint256 u = uint256(keccak256(abi.encodePacked(parent, parentPid, childPid, round, entropy)));
        Genes memory g = unpack(parent);

        if (u & 0xF == 0) {
            g.mode = uint8((uint256(g.mode) + 1 + ((u >> 4) % 3)) % 4);
        }

        int256 t = int256(uint256(g.thresholdBps));
        int256 rel = int256((u >> 8) % 3001) - 1500;
        int256 jitter = int256((u >> 24) % 21) - 10;
        t = (t * (10_000 + rel)) / 10_000 + jitter;
        if (t < 0) t = 0;
        if (t > int256(uint256(THRESHOLD_MAX))) t = int256(uint256(THRESHOLD_MAX));
        g.thresholdBps = uint16(uint256(t));

        int256 lev = int256(uint256(g.leverageX10)) + int256((u >> 40) % 3) - 1;
        if (lev < int256(uint256(LEV_MIN))) lev = int256(uint256(LEV_MIN));
        if (lev > int256(uint256(LEV_MAX))) lev = int256(uint256(LEV_MAX));
        g.leverageX10 = uint8(uint256(lev));

        int256 pat = int256(uint256(g.patience)) + int256((u >> 48) % 5) - 2;
        if (pat < 0) pat = 0;
        if (pat > int256(uint256(PATIENCE_MAX))) pat = int256(uint256(PATIENCE_MAX));
        g.patience = uint8(uint256(pat));

        return pack(g);
    }

    function modeOf(bytes32 word) external pure returns (uint8) {
        return uint8(uint256(word) & 3);
    }

    function lineageOf(bytes32 word) external pure returns (uint24) {
        return uint24(uint256(word) >> 40);
    }

    function modeName(uint8 mode) external pure returns (string memory) {
        if (mode == MODE_MOMENTUM) return "momentum";
        if (mode == MODE_CONTRARIAN) return "contrarian";
        if (mode == MODE_LONG) return "long";
        return "short";
    }

    /// @notice how far two genomes have drifted apart, summed across the numeric genes
    function distance(bytes32 a, bytes32 b) external pure returns (uint256 d) {
        Genes memory x = unpack(a);
        Genes memory y = unpack(b);
        d = _gap(x.thresholdBps, y.thresholdBps) + _gap(x.leverageX10, y.leverageX10) * 40 + _gap(x.patience, y.patience) * 40;
        if (x.mode != y.mode) d += 1_000;
    }

    function _gap(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a - b : b - a;
    }
}

daemon/Kernel.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {Genome} from "./Genome.sol";
import {Signal} from "./Signal.sol";
import {PriceTap} from "./PriceTap.sol";
import {Syslog} from "./Syslog.sol";

// KERNEL(8)                  System Manager's Manual                 KERNEL(8)
//
// NAME
//      kernel - the process table, the run queue and the calls that
//               create and end daemons
//
// SYNOPSIS
//      boot()                    start a founder from the heap
//      tick(steps)               advance the scheduler by up to steps daemons
//      reap(pid)                 return a zombie's residual to the heap
//
// DESCRIPTION
//      Every daemon is a process. It is booted or forked, it runs one step
//      per round, and when its equity falls through the floor it exits and
//      waits as a zombie until someone reaps it.
//
//      init(0)-+-daemon(1)-+-daemon(17)---daemon(40)
//              |           `-daemon(23)
//              |-daemon(2)---daemon(19) <defunct>
//              `-daemon(3)
//
//      Equity is never reported to the kernel. Each round the kernel reads
//      one price, and every daemon's result follows from its genome and
//      that price alone. Anyone may call tick; no caller can change what a
//      tick does. The kernel has no owner and no setter. Its only writable
//      dependency, the journal, is created inside this constructor.
//
//      A round opens on the first tick after ROUND_SECONDS and closes once
//      the run queue has been walked. Daemons born during a round sit it
//      out. A daemon forks at most once per round.
//
// SEE ALSO
//      genome(5), signal(3), syslog(3), procfs(5), pricetap(4)
//
// Daemons 1.0                    September 2026                      KERNEL(8)

contract Kernel {
    uint8 public constant NONE = 0;
    uint8 public constant RUNNING = 1;
    uint8 public constant ZOMBIE = 2;
    uint8 public constant REAPED = 3;

    uint128 public constant GENESIS_ALLOC = 25_000 ether;
    uint128 public constant MIN_VIABLE_ALLOC = 2_500 ether;
    uint16 public constant FOUNDER_CAP = 16;
    uint32 public constant MAX_POP = 512;
    uint64 public constant ROUND_SECONDS = 1 hours;
    uint32 public constant MIN_AGE_ROUNDS = 6;
    uint16 public constant FORK_MULTIPLE_BPS = 24_000;
    uint16 public constant FORK_SHARE_BPS = 2_200;
    uint16 public constant FORK_MAX_DD_BPS = 1_800;
    uint16 public constant EXIT_FLOOR_BPS = 1_200;
    int32 public constant MOVE_CAP_BPS = 5_000;

    struct Proc {
        uint32 pid;
        uint32 ppid;
        uint16 gen;
        uint8 state;
        uint32 bornRound;
        uint32 exitRound;
        uint32 lastForkRound;
        uint128 alloc;
        uint128 equity;
        uint128 peak;
        bytes32 genome;
    }

    Genome public immutable genomeLib;
    Signal public immutable signalLib;
    PriceTap public immutable tap;
    Syslog public immutable syslog;

    mapping(uint32 => Proc) private procs;
    mapping(uint32 => uint32[]) private kids;
    uint32 public nextPid;
    uint32[] private runq;
    mapping(uint32 => uint32) private slot; // index + 1 in runq

    uint256 public heapFree;
    uint256 public heapReturned;
    uint16 public foundersBooted;

    uint32 public round;
    uint64 public roundAt;
    int256 public roundPrice;
    int32 public moveBps;
    int32 public signalBps;
    uint32 public cursor;
    bool public roundOpen;

    event Booted(uint32 indexed pid, bytes32 genome, uint128 alloc);
    event RoundOpened(uint32 indexed round, int256 price, int32 moveBps, int32 signalBps);
    event Stepped(uint32 indexed pid, uint32 indexed round, int8 side, int256 delta, uint128 equity);
    event Forked(uint32 indexed ppid, uint32 indexed pid, uint128 alloc, bytes32 genome);
    event Exited(uint32 indexed pid, uint32 indexed round, uint128 residual);
    event Reaped(uint32 indexed pid, uint128 residual);
    event RoundClosed(uint32 indexed round, uint256 running);
    event NoOp(string reason);

    constructor(address _tap, address _genome, address _signal) {
        tap = PriceTap(_tap);
        genomeLib = Genome(_genome);
        signalLib = Signal(_signal);
        syslog = new Syslog();
        heapFree = uint256(FOUNDER_CAP) * GENESIS_ALLOC;
    }

    /* ---------------------------------------------------------------- boot */

    /// @notice start a founder; allowed until FOUNDER_CAP, and again whenever nothing is running
    function boot() external returns (uint32 pid) {
        bool rekindle = runq.length == 0 && foundersBooted >= FOUNDER_CAP;
        if (foundersBooted >= FOUNDER_CAP && !rekindle) {
            emit NoOp("founder cap reached while daemons still run");
            return 0;
        }
        if (heapFree < GENESIS_ALLOC) {
            emit NoOp("heap cannot fund a founder");
            return 0;
        }
        if (runq.length >= MAX_POP) {
            emit NoOp("run queue full");
            return 0;
        }
        bytes32 seed = keccak256(abi.encodePacked(foundersBooted, blockhash(block.number - 1), address(this), nextPid));
        bytes32 g = genomeLib.founder(seed);
        heapFree -= GENESIS_ALLOC;
        if (foundersBooted < type(uint16).max) foundersBooted += 1;
        pid = _spawn(0, 0, GENESIS_ALLOC, g);
        syslog.write(syslog.BOOT(), round, pid, 0, int256(uint256(GENESIS_ALLOC)));
        emit Booted(pid, g, GENESIS_ALLOC);
    }

    /* ---------------------------------------------------------------- tick */

    /// @notice open a round if one is due, then step up to `steps` daemons through it
    function tick(uint32 steps) external returns (uint32 processed) {
        if (!roundOpen) {
            if (round > 0 && block.timestamp < roundAt + ROUND_SECONDS) {
                emit NoOp("round not due");
                return 0;
            }
            (bool ok, int256 p, ) = tap.read();
            if (!ok) {
                emit NoOp("price unavailable");
                return 0;
            }
            round += 1;
            roundAt = uint64(block.timestamp);
            signalBps = moveBps;
            moveBps = roundPrice > 0 ? _capMove(((p - roundPrice) * 10_000) / roundPrice) : int32(0);
            roundPrice = p;
            cursor = 0;
            roundOpen = true;
            syslog.write(syslog.ROUND(), round, 0, 0, int256(moveBps));
            emit RoundOpened(round, p, moveBps, signalBps);
        }
        while (processed < steps && cursor < runq.length) {
            uint32 pid = runq[cursor];
            if (procs[pid].bornRound == round) {
                cursor++;
            } else if (!_step(pid)) {
                cursor++;
            }
            processed++;
        }
        if (cursor >= runq.length) {
            roundOpen = false;
            emit RoundClosed(round, runq.length);
        }
    }

    function _step(uint32 pid) internal returns (bool removed) {
        Proc storage d = procs[pid];
        Genome.Genes memory g = genomeLib.unpack(d.genome);
        int8 side = signalLib.position(g.mode, g.thresholdBps, signalBps);
        (uint128 next, int256 delta) = signalLib.step(d.equity, side, g.leverageX10, moveBps);
        d.equity = next;
        if (next > d.peak) d.peak = next;
        emit Stepped(pid, round, side, delta, next);

        if (uint256(next) * 10_000 <= uint256(d.alloc) * EXIT_FLOOR_BPS) {
            d.state = ZOMBIE;
            d.exitRound = round;
            _dequeue(pid);
            syslog.write(syslog.EXIT(), round, pid, d.ppid, int256(uint256(next)));
            emit Exited(pid, round, next);
            return true;
        }
        _maybeFork(pid, g.patience);
        return false;
    }

    /* ---------------------------------------------------------------- fork */

    function _maybeFork(uint32 ppid, uint8 patience) internal {
        Proc storage d = procs[ppid];
        if (d.lastForkRound == round) return;
        if (round - d.bornRound < MIN_AGE_ROUNDS + uint32(patience)) return;
        if (uint256(d.equity) * 10_000 < uint256(d.alloc) * FORK_MULTIPLE_BPS) return;
        if (d.peak > 0 && (uint256(d.peak) - uint256(d.equity)) * 10_000 >= uint256(d.peak) * FORK_MAX_DD_BPS) return;
        if (runq.length >= MAX_POP) return;
        uint128 childAlloc = uint128((uint256(d.equity) * FORK_SHARE_BPS) / 10_000);
        if (childAlloc < MIN_VIABLE_ALLOC) return;

        uint32 childPid = nextPid + 1;
        bytes32 g = genomeLib.mutate(d.genome, ppid, childPid, round, blockhash(block.number - 1));
        d.equity -= childAlloc;
        d.lastForkRound = round;
        _spawn(ppid, d.gen + 1, childAlloc, g);
        syslog.write(syslog.FORK(), round, childPid, ppid, int256(uint256(childAlloc)));
        emit Forked(ppid, childPid, childAlloc, g);
    }

    function _spawn(uint32 ppid, uint16 gen, uint128 alloc, bytes32 g) internal returns (uint32 pid) {
        pid = ++nextPid;
        procs[pid] = Proc({
            pid: pid,
            ppid: ppid,
            gen: gen,
            state: RUNNING,
            bornRound: round,
            exitRound: 0,
            lastForkRound: 0,
            alloc: alloc,
            equity: alloc,
            peak: alloc,
            genome: g
        });
        if (ppid != 0) kids[ppid].push(pid);
        runq.push(pid);
        slot[pid] = uint32(runq.length);
    }

    /* ---------------------------------------------------------------- reap */

    /// @notice move a zombie's remaining equity back to the heap and close it for good
    function reap(uint32 pid) external returns (uint128 residual) {
        Proc storage d = procs[pid];
        if (d.state != ZOMBIE) {
            emit NoOp("only a zombie can be reaped");
            return 0;
        }
        residual = d.equity;
        d.state = REAPED;
        heapFree += residual;
        heapReturned += residual;
        syslog.write(syslog.REAP(), round, pid, d.ppid, int256(uint256(residual)));
        emit Reaped(pid, residual);
    }

    /* ---------------------------------------------------------------- queue */

    function _dequeue(uint32 pid) internal {
        uint32 s = slot[pid];
        if (s == 0) return;
        uint32 idx = s - 1;
        uint32 lastIdx = uint32(runq.length - 1);
        if (idx != lastIdx) {
            uint32 moved = runq[lastIdx];
            runq[idx] = moved;
            slot[moved] = idx + 1;
        }
        runq.pop();
        delete slot[pid];
    }

    function _capMove(int256 bps) internal pure returns (int32) {
        if (bps > MOVE_CAP_BPS) return MOVE_CAP_BPS;
        if (bps < -MOVE_CAP_BPS) return -MOVE_CAP_BPS;
        return int32(bps);
    }

    /* ---------------------------------------------------------------- views */

    function proc(uint32 pid) external view returns (Proc memory) {
        return procs[pid];
    }

    function stateOf(uint32 pid) external view returns (uint8) {
        return procs[pid].state;
    }

    function ppidOf(uint32 pid) external view returns (uint32) {
        return procs[pid].ppid;
    }

    function kidsOf(uint32 pid) external view returns (uint32[] memory) {
        return kids[pid];
    }

    function running() external view returns (uint256) {
        return runq.length;
    }

    function runqAt(uint256 i) external view returns (uint32) {
        if (i >= runq.length) return 0;
        return runq[i];
    }

    function runqSnapshot() external view returns (uint32[] memory) {
        return runq;
    }

    function drawdownBps(uint32 pid) external view returns (uint256) {
        Proc storage d = procs[pid];
        if (d.peak == 0 || d.equity >= d.peak) return 0;
        return ((uint256(d.peak) - uint256(d.equity)) * 10_000) / uint256(d.peak);
    }

    function multipleBps(uint32 pid) external view returns (uint256) {
        Proc storage d = procs[pid];
        if (d.alloc == 0) return 0;
        return (uint256(d.equity) * 10_000) / uint256(d.alloc);
    }

    function secondsUntilRound() external view returns (uint256) {
        if (round == 0 || roundOpen) return 0;
        uint256 due = uint256(roundAt) + ROUND_SECONDS;
        return block.timestamp >= due ? 0 : due - block.timestamp;
    }
}

daemon/PriceTap.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

// PRICETAP(4)                Daemons Device Drivers                  PRICETAP(4)
//
// NAME
//      pricetap - the one input every daemon is marked against
//
// DESCRIPTION
//      The tap reads a single aggregator feed, normalises the answer to
//      eight decimals and says whether it can be used. A price that is
//      zero, negative or older than the tap's maximum age is refused, and
//      a feed that reverts is caught rather than passed on.
//
//            |          ____
//            |    _/\__/    \_
//            | __/            \__/\___
//            +-------------------------- t
//                    ^ read()  -> (ok, price, updatedAt)
//
//      The tap has no settable fields. Its feed and its tolerance are fixed
//      when it is deployed and cannot be pointed anywhere else afterward.
//
// SEE ALSO
//      kernel(8)
//
// Daemons 1.0                    September 2026                    PRICETAP(4)

interface IAggregatorV3 {
    function latestRoundData()
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);

    function decimals() external view returns (uint8);
}

contract PriceTap {
    address public immutable feed;
    uint256 public immutable maxAge;
    uint8 public immutable feedDecimals;

    constructor(address _feed, uint256 _maxAge) {
        feed = _feed;
        maxAge = _maxAge;
        uint8 d = 8;
        try IAggregatorV3(_feed).decimals() returns (uint8 got) {
            d = got;
        } catch {}
        feedDecimals = d;
    }

    /// @notice the latest usable price at eight decimals, or ok = false with the reason left to the caller
    function read() public view returns (bool ok, int256 price8, uint256 updatedAt) {
        try IAggregatorV3(feed).latestRoundData() returns (uint80, int256 answer, uint256, uint256 upd, uint80) {
            if (answer <= 0) return (false, 0, upd);
            if (upd == 0 || block.timestamp > upd + maxAge) return (false, 0, upd);
            return (true, _norm(answer), upd);
        } catch {
            return (false, 0, 0);
        }
    }

    function isFresh() external view returns (bool ok) {
        (ok, , ) = read();
    }

    function ageOf() external view returns (uint256) {
        (, , uint256 upd) = read();
        if (upd == 0 || upd > block.timestamp) return 0;
        return block.timestamp - upd;
    }

    function _norm(int256 answer) internal view returns (int256) {
        if (feedDecimals == 8) return answer;
        if (feedDecimals > 8) return answer / int256(10 ** (feedDecimals - 8));
        return answer * int256(10 ** (8 - feedDecimals));
    }
}

daemon/Signal.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

// SIGNAL(3)                  Daemons Library Functions                 SIGNAL(3)
//
// NAME
//      signal - turn last round's move into this round's position
//
// SYNOPSIS
//      position(mode, thresholdBps, signalRetBps)  ->  -1 | 0 | +1
//      step(equity, position, leverageX10, retBps)  ->  (equity', delta)
//
// DESCRIPTION
//      A daemon never sees the round it is being paid for. It decides from
//      the previous round's move and is marked on the current one, so no
//      daemon can trade on information it did not have.
//
//          price   ..../\......../\/\...
//          move      +   -   +   - +
//          momentum  .   +   -   +   -     takes the last move's side
//          contrary  .   -   +   -   +     takes the other side
//
//      A move smaller than the threshold leaves momentum and contrarian
//      daemons flat. Long and short daemons are always in the market.
//      Equity never goes below zero; a loss larger than the equity leaves
//      exactly nothing.
//
// SEE ALSO
//      genome(5), kernel(8)
//
// Daemons 1.0                    September 2026                      SIGNAL(3)

contract Signal {
    uint8 public constant MODE_MOMENTUM = 0;
    uint8 public constant MODE_CONTRARIAN = 1;
    uint8 public constant MODE_LONG = 2;
    uint8 public constant MODE_SHORT = 3;

    function position(uint8 mode, uint16 thresholdBps, int32 signalRetBps) public pure returns (int8) {
        if (mode == MODE_LONG) return 1;
        if (mode == MODE_SHORT) return -1;
        if (signalRetBps == 0) return 0;
        int256 mag = signalRetBps < 0 ? -int256(signalRetBps) : int256(signalRetBps);
        if (mag < int256(uint256(thresholdBps))) return 0;
        int8 side = signalRetBps > 0 ? int8(1) : int8(-1);
        return mode == MODE_MOMENTUM ? side : -side;
    }

    /// @notice profit or loss on equity for one round: equity x side x leverage x move
    function pnl(uint128 equity, int8 side, uint8 leverageX10, int32 retBps) public pure returns (int256) {
        return (int256(uint256(equity)) * int256(side) * int256(uint256(leverageX10)) * int256(retBps)) / 100_000;
    }

    /// @notice the equity after one round, floored at zero, and the change applied
    function step(uint128 equity, int8 side, uint8 leverageX10, int32 retBps)
        external
        pure
        returns (uint128 next, int256 delta)
    {
        delta = pnl(equity, side, leverageX10, retBps);
        int256 e = int256(uint256(equity)) + delta;
        if (e < 0) {
            delta = -int256(uint256(equity));
            e = 0;
        }
        next = uint128(uint256(e));
    }

    /// @notice gross exposure in basis points of equity: 10x leverage long is 100,000
    function exposureBps(int8 side, uint8 leverageX10) external pure returns (int256) {
        return int256(side) * int256(uint256(leverageX10)) * 1_000;
    }

    /// @notice the single-round move that would take a position to zero equity
    function ruinMoveBps(uint8 leverageX10) external pure returns (uint256) {
        if (leverageX10 == 0) return type(uint256).max;
        return 100_000 / uint256(leverageX10);
    }
}

daemon/Syslog.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

// SYSLOG(3)                  Daemons Library Functions                 SYSLOG(3)
//
// NAME
//      syslog - the kernel's journal of births, forks, exits and reaps
//
// DESCRIPTION
//      Every line the kernel writes is kept, numbered and never changed.
//
//      Sep 21 18:41:02 kernel[1]: round 214 open, move +37 bps
//      Sep 21 18:41:02 kernel[1]: fork 412 -> 1190, 10538 units
//      Sep 21 18:41:03 kernel[1]: exit 688 <defunct>, 2104 units left
//      Sep 21 18:47:19 kernel[1]: reap 688, 2104 units to the heap
//
//      The journal has exactly one writer: the contract that deployed it.
//      The kernel creates its syslog in its own constructor, so no other
//      address could ever have been the writer, and there is no step at
//      which one could be appointed. A write from anyone else is refused.
//
// SEE ALSO
//      kernel(8), procfs(5)
//
// Daemons 1.0                    September 2026                      SYSLOG(3)

contract Syslog {
    uint8 public constant BOOT = 1;
    uint8 public constant FORK = 2;
    uint8 public constant EXIT = 3;
    uint8 public constant REAP = 4;
    uint8 public constant ROUND = 5;

    struct Line {
        uint64 seq;
        uint8 kind;
        uint32 round;
        uint32 pid;
        uint32 ppid;
        int256 value;
        uint64 at;
    }

    address public immutable writer;
    Line[] private lines;
    mapping(uint32 => uint64[]) private byPid;

    event Logged(uint64 indexed seq, uint8 indexed kind, uint32 indexed pid, uint32 ppid, uint32 round, int256 value);
    event NoOp(string reason);

    constructor() {
        writer = msg.sender;
    }

    function write(uint8 kind, uint32 round, uint32 pid, uint32 ppid, int256 value) external returns (uint64 seq) {
        if (msg.sender != writer) {
            emit NoOp("only the kernel writes the journal");
            return 0;
        }
        seq = uint64(lines.length) + 1;
        lines.push(Line({seq: seq, kind: kind, round: round, pid: pid, ppid: ppid, value: value, at: uint64(block.timestamp)}));
        byPid[pid].push(seq);
        if (ppid != 0 && kind == FORK) byPid[ppid].push(seq);
        emit Logged(seq, kind, pid, ppid, round, value);
    }

    function length() external view returns (uint256) {
        return lines.length;
    }

    function line(uint64 seq) external view returns (Line memory) {
        if (seq == 0 || seq > lines.length) return Line(0, 0, 0, 0, 0, 0, 0);
        return lines[seq - 1];
    }

    function linesFor(uint32 pid) external view returns (uint64[] memory) {
        return byPid[pid];
    }

    /// @notice the last n lines, oldest first
    function tail(uint256 n) external view returns (Line[] memory out) {
        uint256 len = lines.length;
        if (n > len) n = len;
        out = new Line[](n);
        for (uint256 i = 0; i < n; i++) out[i] = lines[len - n + i];
    }

    function kindName(uint8 kind) external pure returns (string memory) {
        if (kind == BOOT) return "boot";
        if (kind == FORK) return "fork";
        if (kind == EXIT) return "exit";
        if (kind == REAP) return "reap";
        if (kind == ROUND) return "round";
        return "unknown";
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.