Controller-Bound Tokens

Controller-bound tokens are XChain’s programmable policy layer. A token (TICK), or an account (address), may bind itself to a deployed VM contract, its controller. Once bound, the indexer runs the controller’s guard method before a guarded native action settles, inside the same atomic scope. The guard is an ordinary contract method: it may read and write its own contract state, emit token actions, return a royalty or fee split of a sale’s proceeds, and revert to deny the action outright.

Because the indexer is the only settlement path on XChain, a controller makes a token’s rules unavoidable. This is the enforced-royalty and enforced-compliance property that marketplace-goodwill royalties on other chains never achieved: there is no second venue where the rule can be sidestepped, because there is no second settlement path. The token stays natively held and natively tradeable through the built-in DEX rails; the controller only gates the actions that move, sell, mint, or burn it. For contract-custody legs, this claim applies from the CONTROLLER_CUSTODY_GUARD flag day: before it, DEPOSIT and WITHDRAW do not run guards; from it, deposits into and withdrawals out of contract custody run the transfer guard. For dispenser refills, it applies from the DISPENSER_REFILL flag day: before it, a Version 2 DISPENSER edit that tops up GIVE_ESCROW runs no guard, so a dispenser opened before a trade or all binding can be refilled and keep selling the bound token without the controller being consulted.

The feature is opt-in and isolated. A token or account with no binding behaves exactly as it did before (one NULL check, zero VM work, zero added fee). Nothing about an uncontrolled token changes. A binding is added, and dropped, by its owner.


At a glance

  • Token controllers gate actions on a bound TICK: transfers, trades, burns, mints, contract-targeted staking, and ownership deed-overs. Bound via ISSUE v6.
  • Address controllers gate direct sends and contract-custody moves involving a bound account. Bound via ADDRESS v1.
  • The guard is programmable. It runs as a normal VM execution, so every validator reaches the identical decision and side effects.
  • A trade guard can set a proceeds split (payoutLegs), the generic primitive behind royalties, marketplace fees, and revenue share. There is no royalty-specific code path.
  • A contract can declare its own blast radius at deploy time: an emission allowlist and a tighter royalty cap (the permissions manifest).
  • Everything fails closed. A revert, an error, out-of-gas, or a missing guard denies the guarded action and rolls back everything the guard did.
  • Bindings are droppable, subject to a per-binding drop-cooldown the owner commits at bind time.

Controllers are gates, never agents: a controller never holds or moves user funds on its own initiative. It decides whether a native action the user already signed is allowed, and may attach a declarative proceeds split to a sale the user is making.


How it works: the settlement-time guard

The indexer processes each native action in two stages: it validates the action, then settles it (moves balances, updates supply, closes orders). A controller inserts a guard call at the boundary between those two stages, before any ledger change for the action is committed:

  1. The action is parsed and passes its normal validation.
  2. If the action’s class is bound to a controller, the indexer calls the controller’s guard method with the action’s details.
  3. Return normally and the action settles; the guard’s own state changes and emitted actions commit atomically alongside it. When the action runs several guards, a later guard’s denial undoes an earlier guard’s committed effects only from the CONTROLLER_GUARD_LEG_SAVEPOINTS flag day, or when the action was emitted inside an EXECUTE that the denial reverts (see Reentrancy and determinism).
  4. revert, error, or run out of gas and the action is denied: it is recorded invalid: controller (<reason>), and everything the guard did is rolled back.

Exactly one guard runs per subject and action class (there is no stacking): within one subject, the specific binding overrides the catch-all all and only that one guard runs. A single native action can still invoke several guards, because it has several subjects and may have several legs. A direct SEND runs the token’s transfer guard, then the SOURCE account’s outbound transfer guard, then the DESTINATION account’s inbound one (see Account controllers); bulk actions (AIRDROP / DIVIDEND / SWEEP) repeat the applicable guards per tick or leg. Each run is metered separately against GAS_SCHEDULE.VM_GUARD_GAS_CEILING and, on BTC, the reservations are cumulative (see Gas), so budget GAS for every guard an action can invoke, not for one. Each guard commits its own effects when it allows, so until CONTROLLER_GUARD_LEG_SAVEPOINTS is active a guard must not assume the native action settled: a later guard on the same leg can still deny it, and the earlier guard’s state writes and emitted actions stand (unless the action was emitted inside an EXECUTE, which the denial reverts as a whole).

To layer several policies on the same subject and class, put them inside that controller’s guard. Note that a controller does not re-enter its own guard for the moves that guard emits, even when it also governs the moved subject: see Reentrancy and determinism.

sequenceDiagram
    participant Indexer
    participant Controller as Controller (guard)

    Indexer->>Indexer: parse action, run normal validation
    alt action's class is bound to a controller
        Indexer->>Controller: call guard method with the action's details
        alt guard returns normally
            Controller-->>Indexer: return
            Indexer->>Indexer: settle the action, guard's state changes<br>and emitted actions commit atomically
        else guard reverts, errors, or runs out of gas
            Controller-->>Indexer: revert / error / out of gas
            Indexer->>Indexer: deny the action, record invalid: controller (reason),<br>roll back everything the guard did
        end
    end

Binding a controller (ISSUE v6)

A token binds, or unbinds, a controller for one action class at a time via ISSUE version 6:

VERSION|TICK|CONTROLLER|ACTION_CLASS|COOLDOWN_BLOCKS|UNBIND|MEMO
Field Meaning
CONTROLLER ACTION_INDEX of a deployed, active contract on the same chain (its contracts.action_index; derived address C:<CHAIN>:<CONTROLLER>).
ACTION_CLASS Which class of action this binding gates.
COOLDOWN_BLOCKS Drop-cooldown committed at bind time: the friction (in blocks) before a later UNBIND of this class takes effect.
UNBIND Only 1 drops the live binding for ACTION_CLASS (gated by its cooldown); any other value binds.

Rules:

  • Only the token owner can bind or unbind (the standard ISSUE owner gate, invalid: issued by another address).
  • While the token’s ownership record is escrowed in an open ownership offer (ORDER, SWAP or DISPENSER with GIVE_OWNERSHIP=1), the owner can neither bind nor unbind any class, including starting an unbind: invalid: TICK (ownership escrowed). The block lifts when the offer is cancelled, expires, matches or is swept; see Token Ownership Sales.
  • At bind time the indexer verifies CONTROLLER resolves to an existing contract in valid (active) state, mirroring the contract check in EXECUTE.
  • Bindings are append-only events in token_controllers. The effective controller for a (token, class) is the latest event at or below the current block: a bind gates; an unbind gates only until its cooldown elapses. There is no LOCK_CONTROLLER flag; the drop-cooldown is the only friction on changing a binding.
  • Bindings and bridging exclude each other. A token that is bridgeable (a live BRIDGE_CHAINS) or has ever bridged (the sticky BRIDGED bit) cannot use ISSUE v6 at all, bind or unbind: invalid: TICK (bridged tokens cannot be policy-bound yet). Clearing BRIDGE_CHAINS with - reopens binding only for a token that never actually bridged. In the other direction, a token with any effective binding (including one still inside its drop-cooldown) cannot opt into bridging: invalid: TICK (policy-bound tokens are not bridgeable yet). So the order is a choice: bind first and the token forfeits bridging until every binding is fully dropped; bridge first and it forfeits controllers. Unlike allow/block lists and sleep, this half of the exclusion does not lift at policy inheritance, because a controller names a contract on this chain’s VM (see What does not generalize).
  • A token with no binding for a class behaves exactly as before (one NULL check, zero overhead).
stateDiagram-v2
    [*] --> Unbound
    Unbound --> Bound: ISSUE v6, UNBIND=0
    Bound --> Bound: bind refused (already bound)
    Bound --> UnbindPending: ISSUE v6, UNBIND=1 (COOLDOWN_BLOCKS starts)
    UnbindPending --> UnbindPending: still gates ACTION_CLASS, bind and unbind refused until cooldown elapses
    UnbindPending --> Unbound: COOLDOWN_BLOCKS elapses

Bind and unbind rejections

The table lists every refusal specific to a bind or unbind, and each verdict is the STATUS of the ISSUE v6 or ADDRESS v1 row, byte for byte. ADDRESS v1 emits the same strings for an account binding, except the TICK ones and the owner gate, which only a token binding can hit. A bind or unbind also runs the general checks its action applies to every format (for ISSUE, the TICK name rules, the issuance fee and MEMO; see ISSUE Rules); those verdicts are not repeated here. The SOURCE and owner rows are checked before any CONTROLLER or ACTION_CLASS row.

Verdict Bind / unbind Format When
invalid: SOURCE (sleeping) both both SOURCE is asleep at this block (see SLEEP).
invalid: issued by another address both ISSUE v6 SOURCE is not the token’s current owner (the standard ISSUE owner gate).
invalid: TICK (ownership escrowed) both ISSUE v6 The token’s ownership record is escrowed in an open ORDER, SWAP or DISPENSER offer (GIVE_OWNERSHIP=1). This also refuses starting an unbind; close the offer first.
invalid: TICK (unknown) both ISSUE v6 TICK names no existing token.
invalid: CONTROLLER (unknown) both both CONTROLLER is set but no contract has that ACTION_INDEX.
invalid: CONTROLLER (not active) both both The CONTROLLER contract exists but its status is not valid.
invalid: ACTION_CLASS (unknown) both both ACTION_CLASS (case-insensitive) is not one of transfer, trade, burn, mint, stake, ownership, all.
invalid: CONTROLLER (null) bind both UNBIND=0 with an empty CONTROLLER.
invalid: ACTION_CLASS (already bound) bind both Something still gates this exact class: a live bind, or an unbind still inside its cooldown.
invalid: COOLDOWN_BLOCKS (format) bind both COOLDOWN_BLOCKS is set but is not plain decimal digits (no sign, no decimal point) or is above 4294967295, the stored column’s INT UNSIGNED limit.
invalid: ACTION_CLASS (not bound) unbind both Nothing gates this exact class (never bound, or an earlier unbind’s cooldown has elapsed).
invalid: ACTION_CLASS (already unbinding) unbind both The class already has an unbind still inside its cooldown.
invalid: TICK (bridged tokens cannot be policy-bound yet) both ISSUE v6 The token is bridgeable or has bridged (see the bridging rule above).

“This exact class” means the class named in ACTION_CLASS, never the all fallback: an all binding does not make a specific class read as bound, which is what lets a specific bind override all (see Precedence).

A pending unbind cannot be cancelled or replaced. An unbind at block U against a bind that committed COOLDOWN_BLOCKS = C schedules the drop for block U + C. C is always the live bind’s committed value; a COOLDOWN_BLOCKS sent with the unbind is ignored. Until block U + C the old controller keeps gating the class, and any bind or second unbind for that class is refused (already bound / already unbinding). So the only way to swap controllers is to unbind, wait until block U + C, then bind the new one, with the class gated by the old controller throughout. With C = 0 the unbind takes effect at once and a bind is accepted in the same block. Choose COOLDOWN_BLOCKS knowing it is also the minimum time a controller swap takes.

Action classes

An action is always routed to exactly one of six concrete classes by a static map from the action name. The class is never derived from user-supplied data, so a future action cannot accidentally fall into a controlled class. A few actions refuse a bound token without running any guard; see Actions refused outright.

Class Gates Guard action_type
transfer SEND, DEPOSIT, WITHDRAW (and the balance leg of bulk moves) SEND / AIRDROP / DIVIDEND / SWEEP / DEPOSIT / WITHDRAW
trade ORDER / SWAP / DISPENSER create, and a DISPENSER refill from the DISPENSER_REFILL flag day ORDER_CREATE / SWAP_CREATE / DISPENSER_CREATE / DISPENSER_REFILL
burn DESTROY DESTROY
mint MINT supply creation MINT
stake STAKE v3 contract-targeted staking of the token STAKE
ownership SWEEP deed-over of the token’s ownership record SWEEP_OWNERSHIP

A seventh value, all, is bindable but never routable (see below).

Precedence and the all class

all is a class you may bind a controller to, but no action ever routes to it directly. Instead, all is the fallback when an action’s specific class has no binding. Resolution is most-specific-wins, and for one subject and one action class exactly one guard runs (every other subject the same action involves resolves its own guard independently):

  1. Resolve the effective controller for the action’s specific class (e.g. transfer).
  2. If there is none, fall back to the effective all controller.
  3. If neither gates, the action is ungated.

So binding all gates every class with one binding (a “freeze this token entirely” or “compliance-gate everything” policy is one action, not six), and binding a specific class on top of all overrides the catch-all for that class only; the specific binding fully replaces all there. Binding a specific class while all is bound is allowed (it is the override); a second all bind while one is live, or while an all unbind is still inside its cooldown, is rejected, exactly like any other class (see Bind and unbind rejections).

⚠️ all means all classes, present AND future. A token bound to all gates every routed class, including mint (supply creation), stake (v3 contract-targeted staking), and ownership, and will begin gating any class a future release makes routable. This is the intended “gate everything” behavior; bind all only if you want that.

Cooldown and unbind semantics are identical for all (it is just another action_class value with its own append-only events). all participates in resolution only; routing is unchanged.

Actions refused outright on a bound token

The class table lists the actions that run a guard. A few actions never invoke the guard ABI; instead they refuse a bound token while a qualifying binding is effective, whatever the controller would have decided:

Action Refused when Verdict
BET v0 (create a market) TICK has an effective trade binding, or failing that an all binding (the same most-specific-wins resolution the ORDER guard uses) invalid: TICK (controller-bound)
ISSUE v7 (bridge opt-in) TICK has any effective binding invalid: TICK (policy-bound tokens are not bridgeable yet)

So binding trade or all also makes a token un-bettable (a market would otherwise route the token around the trade veto and royalty legs), and any binding blocks bridging; the reverse direction of the bridge rule is under Binding a controller.


The guard ABI

The controller contract must export a method named guard. The indexer calls it with positional, all-string input params (read via xchain.getInputParam(i)):

i Param Notes
0 action_type the guard invocation point (see the class table and the per-action_type table below). No guard runs at match or dispense: see Proceeds split.
1 from the address the guarded action is charged to: the sender, seller, burner, minter or staker. Not always “the address giving up the token”: on MINT nothing is given up and from is the minter
2 to the counterparty address, '' where the invocation point passes none. Its meaning is per-action_type; read it out of the table below rather than inferring it
3 tick the controlled token
4 amount token amount moving (or order/dispenser quantity)
5 price proceeds amount for a sale ('' outside the trade-class creates)
6 proceeds_tick proceeds tick for a sale ('' outside the trade-class creates)

Invocation points (per action_type)

from / to / amount are not uniform across invocation points, and a guard that infers them from the generic descriptions above will misread at least three of them. The values the indexer actually passes:

action_type Class from to amount price / proceeds_tick
SEND transfer sender recipient amount sent ''
AIRDROP transfer distributor '' (fans out) total leaving the sender ''
DIVIDEND transfer distributor '' (fans out) total leaving the sender ''
SWEEP transfer swept address sweep DESTINATION that tick’s swept balance ''
DEPOSIT transfer depositor C:<CHAIN>:<index> amount moved ''
WITHDRAW transfer C:<CHAIN>:<index> withdrawer amount moved ''
SWEEP_OWNERSHIP ownership owner / SOURCE sweep DESTINATION '' ''
ORDER_CREATE trade seller '' (no buyer yet) GIVE_AMOUNT, '' on an ownership give GET_AMOUNT / GET_TICK
SWAP_CREATE trade seller '' (no buyer yet) GIVE_AMOUNT, '' on an ownership give GET_AMOUNT / GET_TICK
DISPENSER_CREATE trade dispenser opener '' (no buyer yet) GIVE_ESCROW, '' on an ownership give GET_AMOUNT / GET_TICK
DISPENSER_REFILL trade refilling address (SOURCE) '' (no buyer) GIVE_ESCROW this refill adds, not the dispenser’s total the stored dispenser’s GET_AMOUNT / GET_TICK
DESTROY burn burner '' amount burned ''
MINT mint minter, not a giver DESTINATION, falling back to the minter when the MINT names none amount minted ''
STAKE stake staker '' always: the target contract taking custody is not passed amount staked ''

DISPENSER_REFILL fires only from the DISPENSER_REFILL flag day, on a Version 2 DISPENSER edit that adds GIVE_ESCROW to an existing dispenser; below it a refill runs no guard. A guard that reverts on an unknown action_type, or branches only on DISPENSER_CREATE, will see it once the gate is active.

Two of these bite guards written against the generic wording:

  • A mint-allowlist guard (“only these addresses may receive newly minted supply”) must treat to as the minter on a MINT with no DESTINATION; it never sees '' there.
  • A stake guard (“only this contract may hold my token”) cannot read the custody target from to, because no target is passed. Today a stake binding is an allow/deny on staking the token at all, not on which contract receives it.

Decision semantics:

  • Return normally ⇒ ALLOW. The guard’s state changes and emitted actions are committed atomically with the native action when it is the only guard on its leg. When a later guard on the same leg denies, the earlier guard’s effects are rolled back only from the CONTROLLER_GUARD_LEG_SAVEPOINTS flag day; before it they stand, unless the action was emitted inside an EXECUTE that the denial reverts.
  • An ORDER_CREATE / SWAP_CREATE guard may return { payoutLegs: [{ to, bps }, …] } to set a basis-point split of the sale’s proceeds (see Proceeds split). Legs returned at any other invocation point, DISPENSER_CREATE and DISPENSER_REFILL included, are never applied, but they are validated first by the same rules and effective cap: a malformed leg or an over-cap total denies the action (invalid: controller (bad payout leg) / invalid: controller (payout exceeds cap)), and only a valid set is discarded. A guard body shared across invocation points should return payoutLegs only when action_type is ORDER_CREATE or SWAP_CREATE.
  • revert(reason) / out-of-gas / runtime error / missing guard method ⇒ DENY (fail-closed). The native action is marked invalid: controller (<reason>) and everything the guard did is rolled back.

The guard runs with full VM powers except the asynchronous frameworks: xchain.attestation.request(...) and xchain.emit.crossExecute(...) throw in guard mode (their results would arrive blocks later, after the guarded action already settled). This is enforced at VM emit time (isGuard) and re-checked host-side. A guard also may not emit SLASH, ATTEST, or XCALL.

Inside the guard, xchain.getSourceAddress() is the address that triggered the guarded action, and xchain.getContractAddress() is the controller’s own derived address (which sources any actions the guard emits).


Proceeds split (royalty / fee payout_legs)

An ORDER_CREATE / SWAP_CREATE guard sets an optional basis-point split of a sale’s proceeds by returning { payoutLegs: [ { to: <address>, bps: <int> }, … ] } from its guard at create time. The split is declarative data carried on the order or swap row. No guard runs at match, which keeps the system-triggered fill path deterministic and gas-free.

This one primitive is how XChain expresses royalties, marketplace fees, and revenue share. There is no royalty-specific mechanism; “royalty” is simply the most common use of payoutLegs.

  1. At create (ORDER_CREATE / SWAP_CREATE): the indexer validates each leg (to a valid address, bps a non-negative integer, total bps ≤ the effective cap min(CONTROLLER_MAX_TAKE_BPS, contract maxTakeBps); global default 10000, optionally tightened by the contract’s permissions manifest) and stores the legs as JSON on orders.payout_legs / swaps.payout_legs. A malformed or over-cap set denies the listing (fail-closed). No payoutLegs ⇒ NULL (an ordinary order). The same validation, including the lenient shapes below, runs at every other guard invocation point, where a bad set denies the action and a valid set is discarded unapplied.

    A valid address is a base58check (P2PKH or P2SH) or bech32 address for the token’s own chain and network (Utility.isCryptoAddress). A contract address (C:<CHAIN>:<index>) never is one, so a contract-address leg denies as invalid: controller (bad payout leg) at every invocation point, on a same-chain listing as well as a cross-chain one.

    Two shapes are read leniently rather than denied, and no activation gate changes that today (none is registered in Flag-Day Values): a supplied payoutLegs that is not an ARRAY is read as “no legs” and the listing is created with NULL legs, and a fractional bps written with a decimal point is accepted at its truncated integer value, which is also the value the cap is measured against. An empty array means the same as an absent payoutLegs.

    The truncation is parseInt of the value’s string form, not numeric truncation, so a bps whose string form is not plain decimal digits is read by its leading digits. That covers exponent notation (a JSON number below 1e-6 or at or above 1e21, or a string such as "1e5") and prefixed strings: 5e-7 reads as 5, 1e21 and "1e5" as 1, "0x10" as 16, "0b11" as 0. The value read is the one checked against the cap, stored and applied, so return bps as a plain integer.

  2. At match: Utility.applyProceedsSplit(tick, proceeds, seller, legs, decimals, cap) splits each filled order’s proceeds, seller-remainder first, then each leg, crediting floor(proceeds × bps / 10000) (at token precision) to each to and the exact remainder to the seller. The split conserves the proceeds exactly (no dust created or lost), so DEX settlement math is unchanged; an order with no legs yields a single full credit to the seller, so the call is unconditional.

Scope. The split applies to on-ledger proceeds (the GET_TICK the seller receives) of an ORDER or SWAP fill. Native-coin (COINPay) proceeds are off-ledger and out of scope for the split; a trade guard can still revert to forbid such a listing. GIVE_OWNERSHIP sales transfer ownership rather than a balance, so no proceeds split applies to that leg.

⚠️ Dispensers take no split, whatever the guard returns. DISPENSER_CREATE runs the trade guard as a veto only: the indexer consumes the deny and the metered guard fee and never applies any payoutLegs the guard returns. It still validates them exactly as at ORDER_CREATE / SWAP_CREATE, so a malformed or over-cap set denies the listing, and only a valid set is discarded, silently, without denying it. No split is applied at dispense either: the dispense path credits the buyer the GIVE_TICK and runs no guard and no applyProceedsSplit. So a royalty policy that only returns legs is routed around by vending the token through a dispenser instead of listing it. A guard that means to enforce a cut must revert on action_type === 'DISPENSER_CREATE' and, from the DISPENSER_REFILL flag day, on 'DISPENSER_REFILL' (or on the dispenser price it will not be paid a share of). DISPENSER_REFILL is veto-only in exactly the same way. Below that flag day a refill runs no guard, so a dispenser opened before the binding cannot be stopped from being refilled. This is a known engine gap, not a design rule: it is recorded as a KNOWN GAP at the call site in xchain-indexer/src/actions/dispenser/controller_guard.js.

Cross-chain sales (CROSS_CHAIN_ROYALTY)

A cross-chain listing (GET_COIN ≠ the token’s chain) settles its proceeds on the counterparty chain, which never runs the guard. What happens to a royalty-bearing cross-chain listing is decided by the CROSS_CHAIN_ROYALTY flag-day, layered on the base CONTROLLER_GUARD flag-day (no legs exist before that):

CONTROLLER_GUARD CROSS_CHAIN_ROYALTY Cross-chain listing whose guard returns legs
off (n/a) no legs produced (unchanged)
on off denied at create (invalid: royalty not enforceable cross-chain, fail-closed)
on on accepted when every leg re-encodes to GET_COIN; legs travel in the validator-signed match and are applied at settlement
on on denied at create when any leg does not re-encode (invalid: royalty leg not payable on proceeds chain, fail-closed)

When the flag is on:

  1. At create, every leg to must re-encode to GET_COIN (Utility.canReencodeAddress); any non-portable leg (a segwit address when GET_COIN has no bech32, e.g. DOGE) denies the listing (invalid: royalty leg not payable on proceeds chain, fail-closed). A contract-address leg never reaches this check: the leg validation above already denied it. This makes the settlement-time re-encode total: a trade that delivered can never hit an unpayable leg.
  2. In the match, the hub copies each order’s stored legs onto the cross_chain_matches row (a_payout_legs / b_payout_legs), and the legs are part of the validator-signed XMATCH canonical (a cross_chain quorum of signatures: stake-weighted at/above STAKE_WEIGHTED_QUORUM_ACTIVATION, otherwise the legacy max(2f+1, ceil((N+1)/2)) signer count), so a colluding hub cannot strip a royalty: a stripped or rewritten legs field breaks the signatures and the match never settles.
  3. At settlement (cross_settle), the proceeds chain applies the counterparty’s legs to the escrow it releases, re-encoding each leg address to its own encoding before crediting (applyProceedsSplit, same remainder-first conservation as same-chain).
sequenceDiagram
    participant TokenChain as Token chain (listing)
    participant Hub
    participant ProceedsChain as Proceeds chain (GET_COIN)

    Note over TokenChain: create (ORDER_CREATE / SWAP_CREATE)
    TokenChain->>TokenChain: guard call at create returns payout_legs,<br>each leg re-encodes to GET_COIN or the listing is denied
    TokenChain->>Hub: order with stored legs
    Note over Hub: match
    Hub->>Hub: copies legs onto cross_chain_matches row<br>(a_payout_legs / b_payout_legs),<br>part of the validator-signed XMATCH canonical<br>(cross_chain quorum)
    Hub->>ProceedsChain: validator-signed match with legs
    Note over ProceedsChain: settlement (cross_settle)
    ProceedsChain->>ProceedsChain: applies the counterparty's legs to the escrow it releases,<br>re-encoding each leg address to its own encoding

Leg-address encoding convention (for guard authors). Leg to addresses are expressed in the controlled token’s own chain encoding (the chain the guard runs on). P2PKH/P2SH addresses share their hash160 across BTC/LTC/DOGE, and segwit addresses share their witness program across BTC/LTC, so the protocol re-encodes the address to the proceeds chain deterministically at settlement (Utility.crossChainReencodeAddress): the same key controls the funds on both chains. Regtest note: BTC/LTC/DOGE regtest share base58 prefixes, so re-encoding is a no-op there; address-level tests must use mainnet parameters.

The canonical format flip is keyed on the BTC-anchored snapshot_block (the activation-registry row cross_chain_royalty_activation.CROSS_CHAIN_ROYALTY_ACTIVATION, carried by the hub and indexer registry parts), while the create-side acceptance rule is keyed on the local block (protocol_changes.js). Operators must coordinate the two: flip the canonical gate first or together with the create-side gate, never create-side first. Both mainnet values are armed: the canonical flip is set to snapshot_block height 961000 (BTC anchor ~2026-08-04; hub and every indexer must deploy before that height), and the create-side acceptance gate (CROSS_CHAIN_ROYALTY) is keyed on its own, later block time, listed on Flag-Day Values under its own date rather than the Cohort A instant.


Bulk distributions (AIRDROP / SWEEP / DIVIDEND)

Bulk moves of a controlled token route through the transfer class exactly like SEND, but the guard gates the aggregate outbound move, sender-side only: one guard run per controlled tick with from = SOURCE and amount = the total leaving the sender. to is not uniform across the three: AIRDROP and DIVIDEND fan out to many recipients and pass to = '', while a SWEEP has exactly one destination and passes to = DESTINATION (see the invocation points table). The guard is never invoked per-recipient. This is a deliberate protocol decision, not a gap:

  • Deterministic, bounded VM work. A drop can have thousands of recipients; one guard run per tick keeps guard gas independent of recipient count and keeps the ceiling reservation meaningful.
  • DoS-proof. Per-recipient gating would let any single recipient’s guard (or a crafted recipient list) deny or grief an entire distribution, and would multiply VM cost by the recipient count.
  • No consensus change needed. Receiving a bulk drop is never guard-gated; there is nothing a recipient must sign or execute.

Receive-side policy belongs in transfer restrictions, not the bulk guard. If a token or account needs to control who may hold or receive it, express that as a transfer restriction that the recipient’s balance is subject to on its next outbound move:

  • Token-level: the token’s transfer guard gates every subsequent SEND of the drop, but it does not gate listings. ORDER / SWAP / DISPENSER creates route to the trade class, and resolution falls back only to all, never to transfer; no guard runs at match or dispense either. A transfer-only binding therefore leaves an unwanted airdropped balance listable and sellable. To make such a balance inert, bind all, or bind trade alongside transfer. An allowlist or compliance guard still does not need per-recipient drop gating, but it must cover the trade class as well as transfer; a transfer-only binding stops unapproved holders from sending the drop, not from selling it.
  • Account-level: an inbound ADDRESS transfer binding (see Account controllers) lets an account refuse direct unsolicited SENDs. Bulk drops, like DEX and dispenser deliveries, are not gated inbound; the account’s recourse is the same transfer-restriction model.

Guidance for guard authors: treat AIRDROP / DIVIDEND / SWEEP invocations as sender-side aggregate checks (from is the distributor, amount is the total). Branch on action_type, never on to === '': to is empty on AIRDROP and DIVIDEND but carries the sweep destination on SWEEP, so an aggregate-vs-direct test written against an empty to takes the wrong branch on every sweep of a controlled token, and a future bulk action that names a destination would break it again. Do not attempt per-recipient allowlisting inside the bulk guard; there is no per-recipient invocation to hook. If your policy requires per-recipient control, either deny the aggregate (forcing individual guarded SENDs) or enforce holder eligibility in the transfer guard on subsequent moves.

SWEEP has two legs, gated by two classes. SWEEP balance moves are gated by the transfer class as above. SWEEP ownership transfers are gated separately by the ownership class: when a SWEEP deeds over a token whose ownership class is bound, the guard runs once for that tick with action_type = SWEEP_OWNERSHIP, from = SOURCE, to = DESTINATION, before the deed settles; any deny fails the whole SWEEP (fail-closed, consistent with the balance path). This is a distinct capability from transfer: an issuer can make ownership non-sweepable to an unapproved DESTINATION while balances stay freely transferable, or the reverse. Ownership escrowed by an open ORDER / SWAP is delivered by that offer’s close path (a trade concern), not this class.


Account (address) controllers

Controllers also bind to accounts, not just tokens; the same guard framework with the address as the subject. An account self-gates one action class via the ADDRESS action, version 1:

VERSION|CONTROLLER|ACTION_CLASS|COOLDOWN_BLOCKS|UNBIND|MEMO
  • The binding is self-signed (SOURCE is the account gating itself) and lives in the append-only address_controllers table, with the same per-class, cooldown/unbind, fail-closed semantics as token bindings, including the same rejection verdicts (all but the TICK ones) and the rule that a pending unbind cannot be cancelled or replaced until its cooldown elapses.
  • The guard runs with the same ABI, gas rules, and determinism guarantees; the subject is the account and tick is the token in motion.

What it gates today: both sides of a direct SEND, plus the account’s contract-custody moves. On direct sends, a transfer address binding is symmetric: it runs whether the account is the SOURCE (an outbound self-gate: self-imposed spending controls such as velocity limits, allowlists, or compliance) or the DESTINATION (an inbound gate: refuse an unsolicited incoming transfer). The guard distinguishes direction from its from / to (from === subject ⇒ outbound). The enforcement order is: the token’s own transfer guard, then the source’s outbound transfer guard, then the destination’s inbound transfer guard. SOURCE pays the guard gas, and on BTC the reservations are cumulative so GAS can never be driven negative (see Gas). A transfer address binding also gates that account’s deposits into and withdrawals out of contract custody. These account guard runs follow the token guard, with cumulative gas, and a contract custody address never carries an address-controller binding, so no address guard runs for the custody endpoint itself. DEX and dispenser deliveries are solicited pulls, not direct sends, so they are never gated this way.

Where a token controller makes the rules travel with the asset, an address controller makes them travel with the account.


Permissions manifest

A contract may declare its own blast-radius bound at deploy time by exporting a manifest alongside its methods:

module.exports = {
    meta: {                           // the identity manifest, REQUIRED at CONTRACT_META_REQUIRED
        name:        'Royalty Guard',
        description: 'Controller guard that allows SEND and ISSUE and caps its take at 2.5%',
        version:     '1.0.0'
    },
    permissions: ['SEND', 'ISSUE'],   // the ONLY action types this contract may emit
    maxTakeBps: 250,                  // a tighter royalty cap than the global default
    guard: function () { /* … */ }
};

Both fields are optional. The indexer reads them deterministically at deploy by instantiating the contract’s module top-level (no method runs), so the manifest is captured even for a contract that exports no constructor. The values are immutable (contract code is immutable) and persisted to the contract_permissions table; all enforcement reads that persisted row.

  • permissions (emission allowlist). Every action a contract emits, from any path (its constructor, an EXECUTE, or a guard), must be a member of this array, or the emission is rejected fail-closed (the host action is denied or reverted). This is the contract-wide analogue of the cross-chain crossCallable allowlist.
    • Absent ⇒ unrestricted (the backward-compatible default; most contracts).
    • [] ⇒ the contract may emit nothing.
    • This is in addition to the standing guard rule that no guard may emit ATTEST / XCALL / SLASH.
  • maxTakeBps (tighter royalty cap). An integer in [0, 10000]. The effective proceeds-split cap for this contract’s trade guard becomes min(CONTROLLER_MAX_TAKE_BPS, maxTakeBps); a contract can voluntarily cap its own take below the global ceiling but can never exceed it. Absent ⇒ the global cap applies.

A malformed manifest (permissions not an array of action-type strings, or maxTakeBps not an integer in range) rejects the DEPLOY (invalid: CONTRACT_MANIFEST (…)) rather than silently degrading to unrestricted. The decision is deterministic and hashes into the contract’s status, so every validator agrees.

The same export object also carries the identity manifest meta, read on the same deterministic instantiation. At/after the CONTRACT_META_REQUIRED activation a guard contract without a conforming meta.name and meta.description is rejected with its own invalid: CONTRACT_MANIFEST (…) string; that verdict is judged after the permissions and maxTakeBps verdicts above, so a contract malformed on both still reports the permissions string. See DEPLOY.


Gas

Running the guard costs VM gas, billed to the action’s SOURCE in XCHAIN. The metered fee is fee = gasBilled × GAS_PRICE, and what is actually charged depends on the chain:

  • The guard runs against a bounded ceiling, GAS_SCHEDULE.VM_GUARD_GAS_CEILING (default 200,000), on every chain.
  • On BTC, SOURCE must hold the full ceiling fee as a reservation before the guard runs (this mirrors the cross-contract-call gas reservation); insufficient XCHAIN rejects the action with insufficient funds (guard gas) before any VM work. The actual metered fee (≤ reservation) is what is charged.
  • The reservation is BTC-only today. It is keyed on the chain, not on whether an XCHAIN token row exists there, so on LTC and DOGE no reservation is taken and insufficient funds (guard gas) is never the verdict, including after the XChain bridge creates an XCHAIN row on that chain. Extending the reservation to every chain would be a separate, future flag-day change.
  • Off BTC the charge is capped at SOURCE’s balance. With no reservation, the metered fee is capped at the XCHAIN balance SOURCE holds: the full fee when it holds that much, its whole balance when it holds less, and nothing when it holds none. The guard still runs against the full ceiling, an allowing action still settles, and no balance goes negative. So off BTC a SOURCE holding no XCHAIN runs guards at no gas cost, and only the on-chain transaction cost of each attempt bounds repeated guard runs.
  • v1 charges guard gas on ALLOW only. A denied action records no ledger change of its own (preserving the ledger/balance invariant). Before the CONTROLLER_GUARD_LEG_SAVEPOINTS flag day, an earlier guard on the same leg that allowed keeps its committed state writes and emitted actions on a broadcast action, and those emissions can move balances (see Reentrancy and determinism). The denial-spam vector is bounded by the real on-chain transaction cost of each attempt; charge-on-deny is a possible later refinement.
  • Uncontrolled tokens pay nothing; there is no guard call.

Reentrancy and determinism

  • The guard runs as an ordinary deterministic VM execution, so every validator produces the identical decision and side effects.
  • No guard-of-guard, and the exemption is keyed on the CONTROLLER, not on the token. A guard’s emit.send triggers a nested guard only when the moved subject resolves to a different controller contract. The skip test compares the emitting contract against the controller that would run, so a controller that also governs the moved subject never re-enters its own guard for it, and no guard fee is charged for that move. Where a different controller does resolve, guard depth is capped by VM_MAX_CALL_DEPTH (4); exceeding it denies the originating action. This reuses the existing cross-contract call-depth machinery.
  • Consequence for shared controllers. Because the exemption keys on controller identity, one controller bound to several tokens (or to a token and an account) will not see its own guard re-run for any of those subjects within a single action: the policy it enforces on a user-submitted action does not re-apply to the moves the same guard emits. A policy that must also constrain the guard’s own emissions has to enforce that inline, in the same guard body.
  • Guard state changes and emissions are wrapped in a dedicated DB savepoint (controller_guard_<actionIndex>_<controller>_<seq>_<ordinal>); any emission failure rolls the whole guard back and denies, the same atomicity model as EXECUTE. The trailing <ordinal> is a per-invocation counter that makes every guard’s savepoint name unique: several guards can run on one leg sharing its <seq>, and two can share a controller, and because the database silently replaces a savepoint whose name is reused, a repeated name would let an inner guard’s release destroy an outer guard’s rollback target. The name is local to the database transaction (never hashed, replicated, or persisted), so the ordinal carries no consensus weight and need not match across nodes.
  • Sibling guards on one leg share an outer savepoint only from CONTROLLER_GUARD_LEG_SAVEPOINTS. An allowing guard releases its own savepoint at once, so on its own the per-guard savepoint cannot undo that guard when a later sibling denies. From the CONTROLLER_GUARD_LEG_SAVEPOINTS flag day, the first guard on a leg (keyed by the native action’s index, the leg’s <seq> and the call depth) opens an outer savepoint, controller_guard_leg_<actionIndex>_<seq>_<callDepth>_<ordinal>, and a later denial on that leg rolls back to it, undoing every earlier sibling’s state writes and emissions. Before the flag day, an earlier sibling’s committed effects stand when a later guard denies: for example, a token transfer guard that allows and emits a royalty SEND keeps that SEND even when the DESTINATION account’s guard then reverts a broadcast SEND. The exception is a native action a contract emitted: its denial fails the enclosing EXECUTE, whose own savepoint rolls back everything inside it, sibling guards included. Until the gate is active on a chain, a guard that emits value-moving actions or writes state on the assumption that the action settled must tolerate another guard on the same leg denying it afterwards.

Every net ledger mutation a guard performs (a burn, or a mint) is reconciled into token supply in the same block, so the indexer’s per-block ledger invariant (ledger == supply == balances) holds; a balanced transfer or an escrow settlement is supply-neutral.


Worked example: enforced NFT royalty

  1. Creator deploys a controller whose guard returns a royalty split, issues the NFT, and binds the trade class to it: ISSUE v6 NFT | <contract> | trade | <cooldown> | 0 |.
  2. The seller lists it: ORDER give NFT, get 1000 XCHAIN. At create the indexer runs guard('ORDER_CREATE', seller, '', NFT, '1', '1000', 'XCHAIN'); the guard returns { payoutLegs: [{ to: creator, bps: 500 }] } (5%). The indexer validates the legs and stores them on the order’s payout_legs. (The guard could instead revert to refuse the listing.)
  3. A buyer fills the order. At match the indexer applies the stored split to the seller’s 1000 XCHAIN proceeds: 50 → creator, 950 → seller, conserved exactly. No guard runs at match.
  4. A plain SEND of the NFT (a gift, a wallet move) is in the transfer class, untouched unless the token also binds a transfer controller, which could gate or deny moves while sales stay separately controlled.

Activation and availability

Controller-bound tokens ride the CONTROLLER_GUARD protocol flag-day, and the flag-day scopes guard execution only. Below it no guard runs: no allow/deny VM run, no payout_legs written, and no guard contract_executions row, so a node that carries the controller layer and one that does not settle every guarded action identically.

Binding is not gated by the flag-day. ISSUE v6 and ADDRESS v1 bindings are accepted, validated and recorded below it, accumulating in the append-only token_controllers / address_controllers logs exactly as they do above it. Every binding already on file therefore begins gating at activation, with no further action from the issuer or the account holder. Plan a pre-activation bind and the flag-day together: the guard is inert before it, the binding is not erased by it.

The cross-chain proceeds-split behavior additionally rides the CROSS_CHAIN_ROYALTY flag-day described above.

From the CONTROLLER_CUSTODY_GUARD flag day, a DEPOSIT into or WITHDRAW out of contract custody runs the token’s transfer or fallback all guard, then the depositor’s own transfer address guard for a DEPOSIT or the withdrawer’s own transfer address guard for a WITHDRAW. SOURCE pays the metered guard gas for both runs, and on BTC the reservations are cumulative (off BTC the charge is capped at SOURCE’s balance, see Gas). There is no grandfathering: a withdrawal of a balance deposited before the flag day is still gated, and a denial leaves that balance in custody.

Because a guard’s decision and side effects are consensus-relevant, the VM engine and the indexer must deploy atomically across the fleet: every validator must run the same guard code at the same height, or they would disagree on whether an action settled. Until a token or account actually binds a controller, the feature is inert on mainnet: uncontrolled tokens take the zero-overhead NULL path.

For the current protocol activation heights, see Protocol Activation.


Edit this page on GitHub ↗