# makinaX and the module

> How Orbit uses Makina's makinaX library, which makinaX server tools it re-serves, and the on-chain MakinaXModule model it builds on.
>
> Describes Orbit 0.1.9. Web page: https://docs.orbit.dialectic.com/0.1.9/contributing/makinax-and-the-module/

This page is for contributors who touch anything that reads the module, builds or proves a call, or sends one. It covers the makinaX library as Orbit consumes it, the on-chain `MakinaXModule` contract model, and the rootfile and merkle-leaf format the module enforces.

Learn more: Safe's docs explain [owners, thresholds and modules](https://docs.safe.global/advanced/smart-account-overview) and [how a module acts for a Safe](https://docs.safe.global/advanced/smart-account-modules). Makina's docs describe [MakinaVM and its instructions](https://docs.makina.finance/concepts/architecture/caliber/makina-vm), the [operator role](https://docs.makina.finance/concepts/governance/operator) and the [root update lifecycle](https://docs.makina.finance/concepts/governance/root-update-lifecycle). Those pages are about Makina's own machines and calibers, which are not the same thing as an Orbit Safe with the makinaX module; read them as background on the instruction model and the roles.

## Who owns what

| Piece | Owner | How Orbit gets it |
| --- | --- | --- |
| makinaX library (Rust crate `makinax`) | Makina, MIT licence | Git dependency pinned to a release tag in `Cargo.toml` (read the `tag = "…"` there). `Cargo.lock` records the tag and the commit it resolved to, so a moved tag fails `--locked`. |
| The makinaX MCP server library | Makina, same release | Second git dependency at the same tag, imported as `makinax_mcp_server`. Its `write` feature follows Orbit's. |
| Transpiler crate (`transpiler`) | Makina | Git dependency pinned by commit (`rev = …` in `Cargo.toml`; mirrored as `TRANSPILER_REV` in `src/compose/transpile.rs`). It defines the rootfile types, leaf hashing and the merkle tree. |
| `MakinaXModule` contract and `ModuleFactory` | Makina | On chain. Orbit only holds bindings (`makinax::ext::bindings`, `src/chain/module_factory.rs`). |

Moving to another makinaX release means changing both `tag = "…"` fragments in `Cargo.toml`, updating the lock for both makinaX packages with `cargo update -p <package>`, and gating on that exact lock.

## Orbit uses only `makinax::ext`

`makinax::ext` is the library's only supported integration API; everything else in the crate may change in any release. Orbit is held to that by `tests/import_boundary.rs`:

- `the_product_uses_makinax_only_through_ext` walks every product `.rs` file and fails on any `makinax::…` path that does not go through `makinax::ext`. Aliasing the crate (`use makinax as mx;`) also fails, because paths through the alias would escape the check.
- `no_product_code_bypasses_the_wrapper_loader` fails if anything other than `src/instructions/mod.rs` reaches makinax's instruction-library loader. That wrapper adds Orbit's refusals: it will not load a compose artifact whose fork proof failed, and it owns the `Rootedness` fact (only it may say whether a Safe has a real instruction whitelist).
- A third rule keeps deployment, setup-batch and migration code (`src/onboard/deploy.rs`, `proposer.rs`, `discover.rs`, `setup_batch.rs`, `wire.rs`, `src/chain/module_factory.rs`, `src/migrate/`) dependent on makinax only, so those files could later move out of the product as a file move. Remaining product edges are listed per file in `KNOWN_PRODUCT_EDGES`, which is shrink-only.

What Orbit takes from `makinax::ext`, by area:

| Area | Examples |
| --- | --- |
| Config and errors | `MakinaxConfig`, `SignerConfig`, `ForkConfig`, `Error` (mapped variant by variant to Orbit's `Error`) |
| Chains and providers | `chains`, `chain`, `Providers`, `RootProvider` |
| Contract bindings | `bindings::IMakinaXModule`, `ISafe`, `IOracleRegistry`, `decode_revert`, `DeclaredError` |
| Building and proving | `build_call`, `CallSpec`, `BuiltCall`, `InstructionLibrary`, `proof_for`, `check_root` |
| Fetchers | swap quotes, Across, CCTP attestation, Merkl rewards (`fetch`) |
| Owner calls | `encode_owner_call`, `build_batch`, `SafeForkSession` |
| Simulation | `sim` (anvil fork manager, Tenderly client, gas budget) |
| Sending (write build only) | `Executor`, `PreSendHook`, `HookVerdict`, `PreparedTx` |

### Sending goes through Orbit's pre-send hook

The library's `Executor` cannot be built without a `PreSendHook`; there is no default and no hook-less constructor, and the library enforces nothing else itself. Orbit's hook is `OrbitHook` in `src/orbit_hook.rs`. `writes::execute::execute` registers an approval the moment it consumes a simulation receipt for a call. The hook admits a send only if that call key has an outstanding approval. Approvals are counted, not a set: each consumed receipt admits exactly one send, and an approval that never reaches the executor is withdrawn when it drops. A send with no approval is refused before anything is signed. See [Request flow](https://docs.orbit.dialectic.com/0.1.9/contributing/request-flow/) for where this sits in the pipeline.

## Re-served makinaX server tools

Orbit links the makinaX MCP server library and offers the agent a reviewed subset of its tools. The lists live in `src/tools/makinax_surface.rs`.

`ALLOW`, the six tools the agent can call:

| Tool | What it adds |
| --- | --- |
| `get_module_state` | The module's live state at the latest block |
| `get_module_events` | Module events over a block range, resumable |
| `get_proof` | The merkle proof for one action under the loaded rootfile |
| `check_root` | Whether the loaded rootfile's root is the one the module enforces |
| `list_owner_functions` | The fixed list of owner-restricted functions (no calldata) |
| `get_cctp_attestation` | Circle's attestation status for a CCTP burn |

`DENY`, never offered, each with its reason in the source:

| Tools | Why |
| --- | --- |
| `execute_call` | Sends immediately with no simulation, review, policy or send lock. Every send goes through `execute_action`. |
| `encode_owner_call`, `build_owner_batch` | Owner calldata and Safe batches come from Orbit's reviewed flows (`generate_onboarding_batch`, `compose_root`, the owner page). |
| `build_call`, `preview_call`, `simulate_call`, `simulate_owner_batch` | Build or simulate outside Orbit's pipeline; `preview_action` and `simulate_action` are the reviewed equivalents. |
| `get_swap_quote`, `get_bridge_quote` | Their output would feed a call built outside the pipeline. `get_swap_quote` is also an Orbit tool, and the Orbit one is served. |
| `list_modules`, `get_balances`, `get_oracle_price`, `list_actions` | Duplicates of Orbit tools. Where the name is shared, Orbit's handler is the one served. |

The service built for these tools is given no signer, so even a route added by mistake cannot send. It speaks Orbit's config words (`safe`, `[safes.*]`), not the server's `modules`. It loads each Safe's rootfile a second time, after Orbit has loaded the same files and checked every `rootfile_pin`; a rootfile rewritten in between leaves these tools on a different root until the next `refresh_state`.

`tests/makinax_allowlist.rs` is the tripwire:

- every server tool is in exactly one of `ALLOW` or `DENY`, so a tool the server gains in a new release fails the build until someone reviews it;
- every allowed and denied name is a real server tool (`execute_call` is absent from the read-only server, and that is the one exception);
- allowed tools reach the agent, denied ones never do;
- allowed names do not collide with Orbit tool names (routers merge by name, so a collision would silently replace a handler);
- errors over the real MCP pipe name `safe` and `[safes.*]`.

To add a tool to `ALLOW`, also follow the tool-surface steps in [Contributing](https://docs.orbit.dialectic.com/0.1.9/contributing/).

## The on-chain module

A Safe holds the funds. A `MakinaXModule` enabled on that Safe lets an operator run only instructions whose merkle leaf is under `allowedInstrRoot`. The Safe changes that root with `setAllowedInstrRoot(bytes32)`, which emits `AllowedInstrRootChanged`.

### Roles

| Role | Can do | Notes |
| --- | --- | --- |
| Owner (the Safe) | Every `onlySafe` function: `setAllowedInstrRoot`, `addOperator`/`removeOperator`, `addGuardian`/`removeGuardian`, `setOperatingMode`, loss caps, cooldowns, feed routes, swapper targets, bridge recipients, sweeps | Called through Safe transactions the owners sign. Orbit never sends these; it prepares batches. |
| Operator | `managePosition`, `accountForPosition[Batch]`, `harvest`, `swap`, `sendOutBridgeTransfer` | The key Orbit holds. Membership is `isOperator(address)`. |
| Guardian | `pause()`, `unpause()` | Both are `onlyGuardian`. The Safe is added as a guardian at initialization and `removeGuardian` refuses to remove it, so the Safe can always pause and unpause. `orbit-watchdog` holds its own guardian key and calls `pause()` when it trips. |
| Provider | `suspend`/`unsuspend`, `setProvider`, `setSwapFeeRate` | Makina's service account (`provider()`), not the Safe. A suspended module reports `suspendedByProvider()`. |

The full owner surface, as encoded by makinaX, is the section between the `OWNER_SURFACE_START` and `OWNER_SURFACE_END` markers in the library's `chain/module.rs`; `list_owner_functions` serves it.

### Instructions

An operator call carries an `Instruction` struct: `positionId`, `isDebt`, `groupId`, `instructionType`, `affectedTokens`, `positionTokens`, `commands` (weiroll), `state`, `stateBitmap`, `merkleProof`.

`instructionType` is an enum:

| Value | Type | Used by |
| --- | --- | --- |
| 0 | `MANAGEMENT` | `managePosition` (paired with an accounting instruction for the same position) |
| 1 | `ACCOUNTING` | `accountForPosition`, valuation |
| 2 | `HARVEST` | `harvest` (rewards, and value that leaves the Safe, such as fixed transfers) |
| 3 | `FLASHLOAN_MANAGEMENT` | flash-loan legs |

Swaps (`SwapOrder`) and bridge sends (`BridgeOrder`) are separate entrypoints, not merkle-proven instructions. They are bounded by the module's swapper targets, bridge recipients, loss caps and cooldowns.

### Loss caps, cooldowns and operating mode

The module stores:

- loss caps in basis points: `maxPositionIncreaseLossBps`, `maxPositionDecreaseLossBps`, `maxSwapLossBps`, and `getMaxBridgeLossBps(bridgeId)` per bridge;
- cooldowns in seconds: `instrCooldownDuration`, `swapCooldownDuration`, `bridgeCooldownDuration`;
- `operatingMode()`: `0 = OPEN`, `1 = FENCED`, `2 = WALLED`.

Which checks the module runs depends on its operating mode. Each mode adds checks to the one before it (confirmed from the module's contract source):

| Mode | What the module enforces on chain |
|---|---|
| `OPEN` (0) | Merkle-root membership, the operator role, pause and provider suspension, and the operator's own swap `minOutputAmount`. Nothing else. |
| `FENCED` (1) | Everything in OPEN, plus: the swap loss cap (`maxSwapLossBps`, oracle-priced, also covers harvest swaps), the swap cooldown (one global timer), the bridge loss cap per bridge id (`getMaxBridgeLossBps`, no oracle), the bridge cooldown (one duration, a timer per bridge id), the bridge recipient whitelist, and the Across route / LayerZero OFT registration checks. |
| `WALLED` (2) | Everything in FENCED, plus: the position increase and decrease loss caps with the direction check, the instruction cooldown (keyed on position, commands and direction), and mandatory accounting (an empty accounting instruction reverts with `AccountingMandatory`). |

In every mode: the CCTP V2 bridge encoder does not read the mode; flash loans, standalone accounting and harvest instruction execution do not depend on it; `setOperatingMode` and all setters are Safe-only and work in any mode.

Orbit reads the mode and sets `policy_is_primary = operating_mode != "WALLED"` (`src/policy/engine.rs`): outside WALLED nothing on chain bounds the value of a position change, so Orbit's mandate checks are the primary brake for those.

Cooldowns are not checked by Orbit before a send. makinaX's revert taxonomy has no entry for the cooldown error; Orbit decodes the `OngoingCooldown()` selector itself as `ongoing_cooldown` (`known: true`, in `src/chain/mod.rs`; before 0.1.8-rc.5 it read `unknown`), and `src/pipeline/limit_refusal.rs` adds a `refusal` block (`wait_not_over`) with the wait and the time left, read from the module and the chain. `max_value_loss_exceeded` and `amount_out_too_low` get the same treatment (`loss_over_limit`, `return_below_minimum`).

Orbit deploys new modules in WALLED. `src/chain/module_factory.rs` builds the factory init params with `initialOperatingMode = 2` and a zero `initialAllowedInstrRoot` (nothing is permitted until the owner's batch sets a root). `verify_walled` stops setup if a deployed module reports any other mode, or if the mode cannot be read; it never changes the mode or redeploys automatically.

### The module factory

`ModuleFactory` exposes `createModule` (AccessManager-gated, one global salt namespace) and `createModuleFree` (needs `freeDeployment()`, salt namespaced per caller as `keccak256(abi.encode(msg.sender, salt))`). Both clone the implementation the registry returns from `moduleImplementation()`; Orbit reads it at prediction time rather than pinning it. Clone creation reverts on a reused salt, so a caller must predict the address and check for code before retrying. The factory addresses Orbit knows are constants in `src/chain/module_factory.rs`.

## Rootfiles

A rootfile is the TOML file that lists every instruction a module permits. Orbit produces it with `compose_root` (see [Packages for curators](https://docs.orbit.dialectic.com/0.1.9/contributing/packages-for-curators/)) and points each Safe at it in config:

```toml
[safes.my-safe]
rootfile = "local:/path/to/rootfile.toml"
rootfile_pin = "0x…"   # the root the file must compute; boot and refresh fail on mismatch
```

Only `local:` sources load; `github:` is refused. A Safe with no rootfile gets an empty library that permits nothing and whose root is `0x00…00`, the same value an unconfigured module reports. `is_placeholder()` exists so that comparison is never read as "root matches".

The file shape (types in the transpiler's `types.rs`):

```toml
# root: 0x…            (generated header)

[tokens."${token_list.<chain>.<SYMBOL>}"]
chainId = 1
address = "0x…"
name = "…"
decimals = 6
symbol = "…"

[instructions.<protocol>.<action>.<token>]
position_id = "<decimal uint256>"
description = "…"            # optional
tags = []                    # optional
is_debt = false
group_id = "0"
instruction_type = 1         # 0..3, as in the table above
affected_tokens = ["0x…"]
position_tokens = ["0x…"]
commands = ["0x…"]           # weiroll commands, bytes32 each
state = ["0x…", "0x…"]
bitmap = "<decimal uint128>"
inputs_slots = []            # runtime-fillable slots: index, name, type, optional meta_type
```

Each entry becomes an action named `protocol.action.token` (for example `across-v2.deposit.WBTC`). A duplicate qualified name is a load error. Accounting instructions are indexed by `position_id`, so a management or harvest call finds its paired accounting instruction by position.

### Leaf hashing and the tree

makinaX computes nothing merkle-related itself; it calls the transpiler, the same code that generated the on-chain root (library `instructions/library.rs`, transpiler `types.rs` and `merkletree.rs`).

1. Instruction hash: `keccak256(abi.encode(commandsHash, stateHash, uint256(bitmap), positionId, isDebt, groupId, affectedTokensHash, positionTokensHash, uint256(instructionType)))`, where
   - `commandsHash = keccak256(abi.encodePacked(commands))`,
   - `affectedTokensHash` and `positionTokensHash` are `keccak256(abi.encodePacked(addresses))`,
   - `stateHash` is zero when `bitmap` is zero; otherwise it is `keccak256` over the packed `keccak256(state[i])` of every state slot whose bit is set, reading the 128-bit bitmap from the most significant bit.
2. The tree takes the instruction hashes, drops zero values, sorts and de-duplicates them, and pads to the next power of two.
3. Leaf: `keccak256(instructionHash)`. This is the `leaf_hash` makinaX reports.
4. Parent: `keccak256(abi.encode(min(a, b), max(a, b)))`, a sorted pair.

The bitmap is why fixed values matter. A state slot whose bit is set is committed in the leaf, so changing its value (for example, a fixed recipient or amount) changes the leaf and therefore the root. Slots left for the caller to fill at call time are listed in `inputs_slots`.

Proofs are computed at load, looked up by instruction hash, and attached to every built call. `check_root` and the `RootOnChain` fact (the `verify` module in `src/instructions/mod.rs`) compare the loaded root with `allowedInstrRoot()`.

## Related pages

- [Request flow](https://docs.orbit.dialectic.com/0.1.9/contributing/request-flow/): build, simulate, policy, execute.
- [Packages for curators](https://docs.orbit.dialectic.com/0.1.9/contributing/packages-for-curators/): where rootfile contents come from.
- [Architecture](https://docs.orbit.dialectic.com/0.1.9/contributing/architecture/): where `src/chain`, `src/instructions` and `src/tools` sit.
