> ## Documentation Index
> Fetch the complete documentation index at: https://docs.neuro-tech.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Token state machines

> Define auditable token workflows with states, events, actions, and persisted variables

<Warning>
  The XML on this page has not been tested with a supported Neuron and approved creation contract. Confirm the schema and lifecycle behavior before using it to create a Neuro-Feature.
</Warning>

A Neuro-Feature creation contract can embed a state-machine definition in the token's machine-readable `Definition`. The machine is optional. When present, the Trust Provider creates it as the token batch is created and links it to the creation contract and the first token in the batch.

Use a state machine when a token must react predictably to time, payments, contract signatures, notes, transfers, destruction, or persistent-data events.

## Definition namespace

The root element uses the following schema namespace:

```text theme={null}
https://paiwise.tagroot.io/Schema/StateMachines.xsd
```

The smallest useful definition has a required `startState`, at least one `State`, and any referenced `Action` elements:

```xml theme={null}
<Definition>
  <StateMachine xmlns="https://paiwise.tagroot.io/Schema/StateMachines.xsd"
                startState="Waiting">
    <Variable id="OwnerJid">
      <TokenProperty>OwnerJid</TokenProperty>
    </Variable>

    <State id="Waiting">
      <OnEvent newState="Complete" actionRef="NotifyOwner">
        <OnDuration>PT1H</OnDuration>
      </OnEvent>
    </State>

    <State id="Complete">
      <OnEnter actionRef="Stop" />
    </State>

    <Action id="NotifyOwner">
      <XmppMessage to="{OwnerJid}" content="Workflow complete." />
    </Action>

    <Action id="Stop">
      <End />
    </Action>
  </StateMachine>
</Definition>
```

This fragment belongs inside the Neuro-Feature `Create` element of a smart contract; it is not a complete contract by itself. ISO 8601 duration `PT1H` means one hour.

## Evaluation model

The machine follows this sequence:

1. Resolve initial variables from constants, token properties, token tags, or Script expressions.
2. Enter `startState` and execute its `OnEnter` action references.
3. Register the active state's event handlers.
4. When an event matches, evaluate `beforeActionScript`, run `actionRef`, and move to `newState`.
5. Run the old state's `OnLeave` actions and the new state's `OnEnter` actions.
6. Sample the state and persisted variables unless sampling is explicitly suppressed.

An `OnEvent` may set `failureState` for action failures and `suppressSample` when a transition should not create the normal audit sample. Treat both as advanced controls: hiding samples weakens the history available to reviewers.

## Variables and values

Top-level `Variable` elements initialize machine context. Their values can be:

* A token tag through `TagReference`
* A built-in token property through `TokenProperty`
* Typed literals: `String`, `Number`, `Boolean`, `Uri`, `Binary`, `Date`, `DateTime`, `Time`, or `Duration`
* A Script expression through `Calc`

Common token properties include `TokenId`, `CreatorJid`, `OwnerJid`, `TrustProviderJid`, `Value`, `Currency`, `Created`, `Updated`, `Expires`, `CreationContract`, `OwnershipContract`, `FriendlyName`, `Ordinal`, and `BatchSize`.

Variables changed while an action runs are ephemeral unless the action uses `PersistVariable`. Persisted variables are sampled for audit and survive subsequent actions:

```xml theme={null}
<Action id="RecordPayment">
  <PersistVariable name="Paid"
                   value="Paid + AmountReceived"
                   onlyIfChanged="true" />
</Action>
```

The attribute values above are Script expressions. Set `suppressSample` only when a separate operation deliberately controls sampling.

## Event types

Events can be declared inline under `OnEvent`, or declared once as an `Event` and reused through `EventReference`.

| Family              | Event elements                                                          | Use                                                                                     |
| ------------------- | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| Conditions and time | `OnCondition`, `OnDuration`, `OnTime`, `OnDateTime`                     | Evaluate a condition or wake the machine at a duration/time                             |
| Payments            | `OnPaymentReceived`, `OnPaymentSent`                                    | React to ledger payments and capture parties, amount, currency, reference, or condition |
| Notes               | `OnTextNote`, `OnXmlNote`, `OnExternalTextNote`, `OnExternalXmlNote`    | Treat token notes as commands or external signals                                       |
| Contracts           | `OnContractSignature`, `OnContractSigned`, `OnContractTemplateApproved` | React to legal workflow milestones and capture contract context                         |
| Token lifecycle     | `OnTransferred`, `OnDestroyed`                                          | React to ownership or terminal token events                                             |
| Persistence         | `OnEntryAdded`, `OnEntryUpdated`, `OnEntryDeleted`                      | React to changes in a selected collection and type                                      |

XML-note and contract events can filter on `localName` and `namespace`. External-note events can also require a `privilege`; use that instead of accepting arbitrary external senders.

`OnTime` and `OnDateTime` accept time coordinates such as `Local`, `UTC`, or a quarter-hour UTC offset. Prefer `UTC` for workflows that cross legal or geographic boundaries.

## Action types

An `Action` is an ordered sequence. The schema supports:

* Payments: `Payment`, `ReserveAmount`, `ReleaseAmount`, `BuyEDaler`, and `SellEDaler`
* Notes and authorization: `TextNote`, `XmlNote`, `AuthorizeSource`, and `UnauthorizeSource`
* Communication: `HttpPost`, `XmppMessage`, `XmppIqGet`, `XmppIqSet`, and `MailMessage`
* Runtime data: `PersistVariable`, `CreateEntry`, `PersistHash`, and `LogEvent`
* Control flow: `If`, `IfHash`, `Switch`, `For`, `ForEach`, `While`, `Do`, and `Try`/`Catch`/`Finally`
* Composition and lifecycle: `Script`, `CallAction`, `ScheduleAction`, `End`, `Destroy`, and `Fail`

Values can be supplied as attributes when simple, or as typed child elements when they are calculated. Response-producing actions such as `HttpPost` and XMPP IQ can store their result in a named variable.

<Warning>
  State-machine actions can transfer value, disclose data, call remote systems, and destroy tokens. Review every transition as production code. In particular, constrain external-note sources, validate remote responses, and make retry behavior safe.
</Warning>

## Singleton machines and token batches

One creation contract can produce a batch of tokens. The embedded definition creates one state-machine for that batch, not one independent machine per token. Use `SingletonMachineId` with a tag reference when multiple token creations must resolve to the same logical machine identifier.

Token properties such as `Ordinal` and `BatchSize` let actions reason about the current token in a batch.

## Note commands

`NoteCommand` describes a client-facing command that generates a token note. It can provide localized `Title`, `ToolTip`, `Confirmation`, `Success`, and `Failure` text; typed parameters; a context Script; and a note-generation Script.

The flags determine where the generated note may be used:

* `ownerNote`: add the note as the token owner.
* `externalNote`: submit it from an authorized external source.
* `personal`: mark the note as personal rather than generally visible.

The resulting text or XML note can trigger a matching note event in the machine. Validate generated XML against its namespace schema before exposing the command to users.

## Reports and inspection

Use the Agent API to inspect a running machine:

* [Get current state](/neuron-api/api-reference/state-machines/get-current-state) returns its current state.
* [Create report](/neuron-api/api-reference/state-machines/create-report) produces present-state, history, diagram, or profiling output.

Definitions can also include `ReportPresent` and `ReportHistory` Script templates to control human-readable report content.

## Implementation checklist

* Validate the complete contract and embedded machine against their XML schemas.
* Confirm every `startState`, `newState`, `failureState`, `actionRef`, and `eventRef` resolves.
* Use explicit namespaces for XML and contract event filters.
* Persist only values required across actions; name audit-relevant values clearly.
* Decide how every remote call behaves on timeout, rejection, and retry.
* Generate present, history, state-diagram, and profiling reports in a staging environment.
* Exercise payment, signature, note, transfer, and terminal paths before signing the creation contract.
