Moxie for Builders

Clearing and settlement for claims.

Moxie is a clearing-and-settlement layer you call as an API. Add tradeable items, prediction markets, and brand drops to your game or app — issue them, price them, and settle them atomically — in a few lines of code. One SDK covers every market: predictions, parimutuel pools, racing dividends, royalty streams, perpetuals, options, and insurance. Humans and AI agents drive the same markets through the same calls.

What You Can Build

Start with products.

A contract market is any market where the payout depends on terms, events, ownership, or time. Moxie gives you one exchange surface for those markets, then clears related exposure together instead of forcing every app to build a one-off trading backend. Domain-natural SDK APIs — client.gameEconomies.*, client.racing.*, client.claimPrograms.* — parameterize a generic claims/obligations surface; one generic consensus surface serves every app.

Game developers

Create a market for a skin, card, trophy, pack, or tournament item. Players can buy, sell, or quote the item from your backend while your game keeps the native UX. The same account can later hold prediction positions, item inventory, and rewards without a separate clearing system per feature.

Roblox / game backend
typescript
import { Client, GridSizeCode, GeneratorCode } from "@moxie/sdk";

const moxie = new Client({ apiKey: process.env.MOXIE_API_KEY });

// Open price discovery for a limited in-game item.
await moxie.createContinuousMarket({
  key: process.env.MOXIE_SIGNING_KEY,
  market_id: "0x<64-hex-dragon-skin-market>",
  omega_lo: "0",
  omega_hi: "100000000000000000000",      // 0..100 units
  grid_size_code: GridSizeCode.N64,
  generator_code: GeneratorCode.Entropy,
  initial_mu: ["25000000000000000000"],    // starts around 25
  swap_fee_bps: 30,
});

Sports, racing, and live events

Build prediction markets, round-by-round fight games, racing pools, and parimutuel products where many outcomes clear together. A Hong Kong Jockey Club style pool, a combat-sports card, and a tournament bracket all reduce to event-linked markets with settlement receipts.

event contract
typescript
// One market, multiple outcomes, settled when the event resolves.
await moxie.createStandaloneMarket({
  key: process.env.MOXIE_SIGNING_KEY,
  market_id: "0x<64-hex-race-market>",
  question: "Which horse wins Race 7?",
  resolution_time: 1780000000,
  outcome_count: 14,
  collateral_asset: "USD",
});

await moxie.predictionIssue({
  key: process.env.MOXIE_SIGNING_KEY,
  prediction_id: "0x<64-hex-ticket>",
  event_id: "0x<64-hex-race-event>",
  outcome_index: 6,
  amount: "50000000000000000000",
});

Brands, IP, and commerce

Attach markets to merch, drops, royalties, access passes, media catalogs, or cross-brand collaborations. Moxie exposes normal SDK calls for commerce and trading, while the deeper settlement layer keeps receipts, payout paths, and compliance evidence tied to the market.

commerce + market data
typescript
const merch = await moxie.getMerchandise("0x<brand-id>");
const order = await moxie.merchOrder({
  buyer: "0x<player-account>",
  itemId: merch[0].id,
  brandId: "0x<brand-id>",
  quantity: 1,
  paymentAsset: "USD",
  maxPrice: "50000000000000000000",
});

console.log(order.order_id, order.status);
Quick Start

Install an SDK and create your first market

Start with the product action: create a market, ask Moxie for a quote, submit the trade, then wait for a receipt. Under the hood, the market lowers into a (Claim, PayoffProgram, ConvexPotential) triple. The details are above; the first integration is just a few SDK calls.

TypeScript — @moxie/sdk

Best first path for a web app, game backend, or commerce service. The TypeScript client exposes named methods, typed errors, idempotency headers, receipt polling, compliance preflight helpers, and realtime block subscriptions. The integer constants in the example are stable wire values; most builders only touch them when creating custom market shapes.

install
terminal
$ npm install @moxie/sdk@rc   # v1.0.0-rc.1
item market: create → quote → trade
typescript
import {
  Client,
  GridSizeCode,
  GeneratorCode,
  DirectionCode,
} from "@moxie/sdk";

const moxie = new Client({
  baseUrl: "http://localhost:8545",
  apiKey: process.env.MOXIE_API_KEY,
});

// Create a market for a limited in-game item.
const txHash = await moxie.createContinuousMarket({
  key: "0x<64-hex>",
  market_id: "0x<64-hex-dragon-skin-market>",
  omega_lo: "0",
  omega_hi: "100000000000000000000",
  grid_size_code: GridSizeCode.N64,
  generator_code: GeneratorCode.Entropy,
  initial_mu: ["25000000000000000000"],
  swap_fee_bps: 30,
});

// Quote a player buying exposure to the 20..30 price band.
const quote = await moxie.quoteContinuous({
  market_id: "0x<64-hex-dragon-skin-market>",
  omega_a: "20000000000000000000",
  omega_b: "30000000000000000000",
  delta_amount: "1000000000000000000",
  direction_code: DirectionCode.Buy,
});
console.log(quote.total_payout, quote.iterations_used);

// Submit the trade; the SDK waits for the receipt by default.
const swap = await moxie.swapContinuous({
  key: "0x<64-hex>",
  market_id: "0x<64-hex-dragon-skin-market>",
  omega_a: "20000000000000000000",
  omega_b: "30000000000000000000",
  delta_amount: "1000000000000000000",
  direction_code: DirectionCode.Buy,
});
console.log(swap);

Rust — moxie-sdk

Use Rust for validators, market-making bots, settlement workers, data pipelines, and services that need tight control over signing and replay. Create a MoxieClient with MoxieClient::builder(); typed resource namespaces cover the stable high-level domains, while client.raw() exposes every registered RPC method.

Cargo.toml
toml
[dependencies]
moxie-sdk = "1.0.0-rc.1"
serde_json = "1"
tokio = { version = "1", features = ["full"] }
create_continuous_market
rust
use moxie_sdk::MoxieClient;
use serde_json::json;

let client = MoxieClient::builder()
    .base_url("http://localhost:8545")
    .build()?;

let params = json!({
    "key": "0x<64-hex>",
    "market_id": "0x<64-hex>",
    "omega_lo": "0",
    "omega_hi": "1000000000000000000",
    "grid_size_code": 3,        // N64
    "generator_code": 1,        // Entropy
    "initial_mu": ["500000000000000000"],
    "swap_fee_bps": 30,
});

let tx = client
    .raw()
    .create_continuous_market(&[params])
    .await?;

Python — moxie-sdk

Use Python for notebooks, analytics, pricing experiments, reporting, and operations scripts. The package installs as moxie-sdk and imports as moxie_sdk. Typed resources cover the common product surfaces; client.rpc() remains the exact JSON-RPC escape hatch.

pip
terminal
$ pip install moxie-sdk==1.0.0rc1
create & quote
python
from moxie_sdk import MoxieClient

moxie = MoxieClient(base_url="http://localhost:8545")

tx = moxie.rpc("moxie_createContinuousMarket", {
    "key": "0x<64-hex>",
    "market_id": "0x<64-hex>",
    "omega_lo": "0",
    "omega_hi": "1000000000000000000",
    "grid_size_code": 3,        # N64
    "generator_code": 1,        # Entropy
    "initial_mu": ["500000000000000000"],
    "swap_fee_bps": 30,
})

quote = moxie.rpc("moxie_quoteContinuous", {
    "market_id": "0x<64-hex>",
    "omega_a": "100000000000000000",
    "omega_b": "200000000000000000",
    "delta_amount": "10000000000000000000",
    "direction_code": 0,         # Buy
})
print(quote["total_payout"], quote["iterations_used"])

Signed typed-Claim builders — moxie_buildTransaction

The generic signed-transaction path now builds the typed-Claim and payoff consensus variants directly. method: "payoffRegister" lowers a standalone PayoffProgram into NativeTx::PayoffRegister and emits payoff_registered on success. method: "claimRegister" lowers a typed Claim plus PayoffProgram into NativeTx::ClaimRegister and emits claim_registered on success. method: "claimAttestationReceived" lowers a Mass MassClaimAttestation envelope into NativeTx::ClaimAttestationReceived. method: "complianceAttestationReceived" lowers the holder's Mass MassComplianceAttestation into NativeTx::ComplianceAttestationReceived; the live claim smoke requires that receipt before settlement. method: "kycSetLevel" lowers an authority-signed KYC grant into NativeTx::KycSetLevel, avoiding raw-key RPC mutation for live smoke and testnet operations. method: "claimPayoffSettle" lowers a holder settlement request into NativeTx::ClaimPayoffSettle; optional settlement_trace_id is copied into the Mass PositionUpdate market-signal payload as run_id for corpus correlation. All six return { tx_bytes, tx_hash } for client-side signing, then submission through moxie_submitSigned. Public receipts preserve typed claim events as payoff_registered, claim_registered, claim_attestation_applied, claim_payoff_settled, claim_position_frozen, and claim_attestation_revoked; holder compliance admission is visible as compliance_attestation_applied.

JSON-RPC — build then submit
json
{
  "method": "moxie_buildTransaction",
  "params": [{
    "method": "payoffRegister",
    "registrar": "0x...",
    "program": { "ops": [ ... ], "output_index": 0 },
    "idempotency_key": "register-payoff-001"
  }]
}

{
  "method": "moxie_buildTransaction",
  "params": [{
    "method": "claimRegister",
    "claim": { "id": "0x...", "issuer": "0x...", "holder": "0x..." },
    "payoff": { "ops": [ ... ], "output_index": 0 },
    "idempotency_key": "register-claim-001"
  }]
}

{
  "method": "moxie_buildTransaction",
  "params": [{
    "method": "claimAttestationReceived",
    "attestation": { "attestor": "0x...", "claim_id": "0x...", "signature_composite": [ ... ] }
  }]
}

{
  "method": "moxie_buildTransaction",
  "params": [{
    "method": "complianceAttestationReceived",
    "attestation": { "subject": "0x...", "corridor_id": "0x...", "signature_composite": [ ... ] }
  }]
}

{
  "method": "moxie_buildTransaction",
  "params": [{
    "method": "kycSetLevel",
    "authority": "0x...",
    "subject": "0x...",
    "level": "L2"
  }]
}

{
  "method": "moxie_buildTransaction",
  "params": [{
    "method": "claimPayoffSettle",
    "claim_id": "0x...",
    "holder": "0x...",
    "idempotency_key": "settle-claim-001",
    "settlement_trace_id": "live-smoke-20260506-001",
    "evidence_index": 0,
    "evidence_leaf_index": 0
  }]
}
Choose Your SDK

One exchange surface, many builder environments

Use the hand-maintained SDKs when you want the fastest path to production. Use generated SDKs when your team standardizes on enterprise languages. Use game-engine wrappers when Moxie should feel like a native game service instead of an external finance API.

Tier 1 — TypeScript, Rust, Python

Start here for most applications. TypeScript fits web apps, Roblox/OpenCloud-adjacent backends, creator tools, and dashboards. Rust fits market makers, validators, and settlement workers. Python fits notebooks, analytics, pricing, and ops scripts. All three expose the same market families: brands, merch, tickets, drops, predictions, continuous markets, racing, chain reads, receipts, and raw RPC escape hatches. Tier-1 versions: moxie-sdk@1.0.0-rc.1 on crates.io, @moxie/sdk@1.0.0-rc.1 on npm under --tag rc, moxie-sdk==1.0.0rc1 on PyPI as a PEP 440 release-candidate.

install — Tier 1
terminal
$ npm install @moxie/sdk@rc                       # v1.0.0-rc.1
$ cargo add moxie-sdk@"1.0.0-rc.1"             # v1.0.0-rc.1
$ pip install moxie-sdk==1.0.0rc1 httpx           # v1.0.0rc1

Tier 2 — Go, Java, C#, Kotlin, Swift

Use generated clients when Moxie is part of a larger enterprise or studio backend. The generated layer keeps request and response shapes exact; thin handwritten wrappers add retry, pagination, receipt polling, and amount helpers so teams do not have to hand-roll transport behavior.

install — Tier 2
terminal
$ go get github.com/momentum-sez/moxie-sdk-go
$ mvn dependency:get -Dartifact=inc.momentum:moxie-sdk-java:0.1.0
$ dotnet add package Moxie.Sdk
$ implementation "inc.momentum:moxie-sdk-kotlin:0.1.0"  # Gradle
$ .package(url: "https://github.com/momentum-sez/moxie-sdk-swift")  # SwiftPM

Tier 3 — game-engine wrappers

Unity, Unreal, Godot, and Roblox integrations wrap the Rust SDK core so games can create markets, quote trades, subscribe to settlement, and show inventory state without exposing signing keys inside client code. Unity uses P/Invoke + UPM; Unreal uses a C++ plugin; Godot uses GDExtension; Roblox uses HttpService with signing in a backend service. Each engine wrapper ships on its own cadence across the v1.x point releases.

install — Tier 3
terminal
# Unity (UPM)
$ openupm add inc.momentum.moxie-sdk

# Unreal (C++ plugin)
$ git submodule add \
    https://github.com/momentum-sez/moxie-sdk-unreal \
    Plugins/MoxieSdk

# Godot (GDExtension)
# Roblox (OpenCloud backend)
Typed Claim Resources

New SDK resource families: claims, payoffs, positions, price vectors, venue oracles

The typed-Claim surface ships four new SDK resource families: claims, payoffs, positions (typed), and priceVectors. Live claim and standalone payoff registration are consensus-backed: build method: "claimRegister" / method: "payoffRegister" through moxie_buildTransaction, sign locally, then submit with moxie_submitSigned. Server-side handlers are wired with idempotency on every mutation; Tier-1 client resources land identically across Rust, TypeScript, and Python with byte-equal Borsh canonical hashing across all three SDKs.

client.claims.* — preflight, signed register, list, get

Author a typed Claim with its issuer, holder, settlement asset, payoff root, dependency set, and optional typed PDCF valuation bundle. The compliance preflight returns a typed PreflightVerdict with ok, errors, and the server-recomputed claim_id; it can also validate the supplied pdcf_bundle against claim.pdcf_root. On live nodes, registration is a signed NativeTx::ClaimRegister; the legacy moxie_claimsDefine compatibility handler refuses live RPC-local mutation and tells callers to use the signed path.

  • moxie_claimsPreflight — Public. 23-domain compliance preflight; SSB-required gate and optional PDCF bundle checks enforced. Returns the canonical claim_id before any write.
  • moxie_buildTransaction with method: "claimRegister"claims:write. Builds unsigned Borsh bytes for NativeTx::ClaimRegister { claim, payoff, program_kind?, pdcf_bundle?, idempotency_key, nonce }; submit the signed envelope with moxie_submitSigned. Receipt emits claim_registered.
  • moxie_claimsDefine — compatibility/local-demo admission only. On live nodes it fails closed with moxie.claims.define_requires_signed_native_tx instead of mutating RPC-local executor state.
  • moxie_claimsList — Public. Cursor-paginated by (brand_id, legal_profile_id, status).
  • moxie_claimsGet — Public. Returns { claim, pdcf_bundle? }; pdcf_bundle is present when the typed valuation bundle was supplied and persisted at admission time.
define a typed Claim
typescript
const pdcfBundle = {
  version: 1,
  asof_block: 12_000_000,
  settlement_asset: "0x<settlement-asset-root>",
  probability_model_root: probabilityModelRoot,
  discount_curve_root: discountCurveRoot,
  cash_flows: {
    [cashFlowId]: {
      payment_block: 14_000_000,
      amount: { magnitude: "100000000000000000000", negative: false },
      probability: "850000000000000000",
      discount_factor: "970000000000000000",
      evidence_root: evidenceRoot,
    },
  },
};

const claim = {
  issuer: "0x<issuer>",
  holder: "0x<holder>",
  settlement_asset: "0x<settlement-asset-root>",
  payoff_root: payoffProgram.canonicalHash(),
  depends_on: [],
  pdcf_root: pdcfBundleRoot,
  instrument_id: instrument.id,
  legal_profile_id: legalProfileId,
  ssb_attestation_root: "0x00..00",  // non-zero iff Sharia profile
  effective_from_block: 12_000_000,
  expires_at_block:     14_000_000,
  version: 1,
};

const verdict = await moxie.claims.preflight(claim, { pdcfBundle });
const claim_id = verdict.claim_id;
claim.id = verdict.claim_id;

const unsigned = await moxie.claims.buildRegisterTransaction(payoffProgram, claim, {
  pdcfBundle,
  idempotencyKey: "brand-note-2026-001",
});

const signed = await signer.signMoxieTx(unsigned.tx_hash);
const tx_hash = await moxie.claims.submitSignedRegister({
  ...signed,
  tx_bytes: unsigned.tx_bytes,
}, { idempotencyKey: "brand-note-2026-001-submit" });
const receipt = await moxie.rpc("moxie_getReceipt", [tx_hash]);
const withValuation = await moxie.claims.getWithPdcfBundle(claim_id);
// receipt.events includes claim_registered on consensus admission

client.payoffs.* — signed register, declare preview, validate, library, canonical_hash

The payoffs resource exposes the SSA-flat function-term tree as a first-class developer concept. payoffs.library returns the constructor catalog (payoff_constant, payoff_fixed, payoff_event_contingent, payoff_linear_derivative, payoff_option_call, payoff_pool_share, payoff_index_linked, payoff_composite, payoff_spread). Canonical hashing computes locally in Rust and dispatches server-side in TypeScript/Python, with byte equality pinned by the Borsh-canonical contract. Live standalone payoff persistence is consensus-backed through signed NativeTx::PayoffRegister; the compatibility declare handler validates and hashes without mutating live executor state.

  • moxie_buildTransaction with method: "payoffRegister"payoffs:write. Builds unsigned Borsh bytes for NativeTx::PayoffRegister { registrar, program, idempotency_key, nonce }; submit the signed envelope with moxie_submitSigned. Receipt emits payoff_registered.
  • moxie_payoffsDeclare — AuthWrite compatibility preview. Validates the payoff body, computes canonical_hash, and enforces idempotency; live nodes use signed payoffRegister for consensus-visible persistence.
  • moxie_payoffsValidate — Public. Runs the seven structural validators.
  • moxie_payoffsLibrary — Public. Returns the constructor catalog with bounds.
  • canonicalHash / canonical_hash — Rust-local and TS/Python server-dispatched canonical hash helpers, pinned to the same Borsh digest.
payoffs.library + validate
python
from moxie_sdk import MoxieClient, payoff_lib

moxie = MoxieClient(base_url="http://localhost:8545")

program = payoff_lib.payoff_event_contingent(
    evidence_index=0, leaf_index=0,
    expected="0x...",
    win="100", lose="0",
)
payoff_root = moxie.payoffs.canonical_hash(program)

# Optional server-side validate (matches local).
moxie.payoffs.validate(program=program)

client.positions.* — for_claim, apply_delta, conservation_check

Positions are returned as canonical PositionLedger sub-views per claim. conservation_check verifies net_for_claim == 0 for derivative claims and net == issuer_supply for primary claims. Apply-delta is internal — the user-facing path is the existing moxie_swapContinuous / moxie_predictionTrade / moxie_ammSwap family.

  • moxie_positionsForClaim — Public. Cursor-paginated holders for one Claim.
  • moxie_positionsApplyDelta — AuthWrite. Internal; surfaced via existing trade methods.
  • moxie_positionsConservationCheck — Public. Returns {net, total_long, total_short, is_balanced}.
conservation check
rust
use moxie_sdk::MoxieClient;

let client = MoxieClient::builder().base_url(...).build()?;

let check = client.positions()
    .conservation_check(claim_id)
    .await?;

assert!(check.is_balanced);  // derivative claim: net == 0

client.priceVectors.* — canonical, gradient

The canonical price vector is the intrinsic PDCF read path over admitted typed claims. moxie_priceVectorsCanonical walks the persisted claim registry, evaluates each stored PdcfBundle.present_value(), and returns a cursor page anchored at asof_block. moxie_priceVectorsGradient walks the admitted payoff DAG and returns intrinsic partials over PDCF-backed upstream RefClaim inputs. CPCAM correlation / Hessian witnesses remain clearing-engine artifacts, not fields on this page envelope.

  • moxie_priceVectorsCanonical — Public. Returns {asof_block, items: [{claim_id, price, pdcf_root}], next_cursor?}.
  • moxie_priceVectorsGradient — Public. Returns {claim_id, asof_block, entries} for intrinsic payoff-DAG partials; full CPCAM sensitivities remain a later clearing-engine witness.
canonical price vector
typescript
const page = await moxie.priceVectors.canonical(0n, {
  settlement_asset: "0x<64-hex>",
});

console.log(page.asof_block);
console.log(page.items[0].price);        // PDCF present value
console.log(page.items[0].pdcf_root);    // valuation witness root

client.claimAmm().* — reference prices from both venues, no indexer

Every claim trades on a per-claim order book and a per-claim AMM; the venue-oracle resource turns their receipts into reference prices your product can settle against. Volume-weighted (ammPriceStats, orderMatchVwap) for execution-quality views, block-time-weighted (ammTwap, orderMatchTwap) for manipulation-resistant settlement strikes, raw tape (ammSwapHistory, orderMatchHistory) for your own analytics, and one cross-venue canonical price (unifiedReferencePrice) that never mixes consideration units. Identical resources in Rust (client.claim_amm()) and Python (client.claims.amm_* / order_match_*). Full wire shapes on the API spec.

settle against a TWAP strike
typescript
const twap = await moxie.claimAmm().ammTwap(claimId, 64);
// self-verifying: twap == cumulativeWeightedSpot / totalBlockSpan

const unified = await moxie.claimAmm().unifiedReferencePrice(claimId, 128);
console.log(unified.unifiedVwap, unified.ammObservationCount);
Auth Profiles

Four auth profiles, same RPC surface

All four auth profiles share the same JSON-RPC and REST surface. Mass agent-store agents holding mxk_sk_agent_* with appropriate scope are indistinguishable from a human dev backend at the wire layer.

Profile 1 — DEV backend (server-to-server)

Credentials: mxk_sk_<env>_<kid>_<random>; OAuth 2.0 Client Credentials at node-local POST /oauth/tokenmxat_* bearers. mTLS RFC 8705 + private_key_jwt RFC 7521. Use this for server-side claim definition, payoff declaration, position writes.

Profile 2 — Key-native player (signature-based authentication)

POST /v1/auth/signature/{nonce, verify}mxs_player_* session scoped to Address; the authentication subject is the account's public key. MPC-with-passkey keystore + ML-DSA-65 PQ seed. Players read positions, hold derivative claims, sign trade envelopes.

profile 3 + 4
rust
// Profile 3 — Delegated session key (macaroon-attenuated).
// Secondary signature keypair bound in the settlement record as a restricted signer.
// Caveats as first-party macaroon predicates: max_cost, persona, device.
// Attenuate-only; child ⊆ parent; depth ≤ 8.
// Sponsored execution lives here; the first issuance carries no fee.

// Profile 4 — Admin (HSM, m-of-n).
// X-Admin-Key static is retired. Every admin* RPC is an HSM-rotatable
// signed envelope (YubiHSM / CloudHSM), countersigned via m-of-n matching
// the mez-recovery ceremony signer set. Claim revocation, SSB rotation,
// and product-legal-profile updates run through this profile.
JSON-RPC Method Catalog

Typed-Claim methods plus signed NativeTx builders

The typed-Claim read, preflight, payoff, position, and price-vector methods are wired across moxie_claims*, moxie_payoffs*, moxie_positions*, and moxie_priceVectors*. Live claim and standalone payoff registration use moxie_buildTransaction / moxie_submitSigned so the consensus path, nonce gate, fee accounting, and receipt root are exercised instead of RPC-local mutations.

Claims — moxie_claimsPreflight, claimRegister, moxie_claimsList, moxie_claimsGet

Preflight a typed Claim with its issuer, holder, settlement asset, payoff root, dependency set, legal profile, and optional typed PDCF bundle. preflight runs the 23-domain compliance and PDCF root checks without a write. Registration is moxie_buildTransaction { method: "claimRegister" } followed by local signing and moxie_submitSigned; getWithPdcfBundle returns the persisted valuation bundle when it was admitted. moxie_claimsDefine remains a compatibility handler and refuses live nodes with define_requires_signed_native_tx.

TypeScript — @moxie/sdk
typescript
import { Client } from "@moxie/sdk";
const moxie = new Client({ baseUrl, apiKey });

// 1. Preflight + signed consensus registration
const verdict = await moxie.claims.preflight(claim, { pdcfBundle });
claim.id = verdict.claim_id;
const unsigned = await moxie.claims.buildRegisterTransaction(payoffProgram, claim, {
  programKind: "AutocallableStructuredNote",
  pdcfBundle,
  idempotencyKey: "my-claim-001",
});
const signed = await signer.signMoxieTx(unsigned.tx_hash);
const tx_hash = await moxie.claims.submitSignedRegister({
  ...signed,
  tx_bytes: unsigned.tx_bytes,
}, { idempotencyKey: "my-claim-001-submit" });

// 2. List
const page = await moxie.claims.list({
  holder, legal_profile_id, active_only: true,
});

// 3. Get
const claim = await moxie.claims.get(claim_id);
const claimEnvelope = await moxie.claims.getWithPdcfBundle(claim_id);

// 4. Fetch the receipt and require claim_registered
const receipt = await moxie.rpc("moxie_getReceipt", [tx_hash]);
Rust — moxie-sdk
rust
use moxie_sdk::{MoxieClient, resources::claims::*};

let client = MoxieClient::builder().base_url(...).build()?;

// 1. Preflight; live registration uses signed claimRegister.
let verdict  = client.claims().preflight_with_pdcf_bundle(claim.clone(), pdcf_bundle.clone()).await?;
let unsigned = client.claims().build_register_transaction(payoff_program, claim, BuildClaimRegisterOptions {
  idempotency_key: "my-claim-001".into(),
  program_kind: None, pdcf_bundle: Some(pdcf_bundle), nonce: None,
}).await?;
// Sign unsigned.tx_hash locally, then submit with submit_signed_register.

// 2. List | 3. Get
let page     = client.claims().list(holder, filter).await?;
let claim    = client.claims().get(claim_id).await?.expect("claim exists");
let envelope = client.claims().get_with_pdcf_bundle(claim_id).await?;
Python — moxie-sdk
python
from moxie_sdk import MoxieClient
moxie = MoxieClient(base_url="http://localhost:8545")

# 1. Preflight; live registration uses signed claimRegister.
verdict = moxie.claims.preflight(claim=claim, pdcf_bundle=pdcf_bundle)
unsigned = moxie.claims.build_register_transaction(
    payoff_program, claim, pdcf_bundle=pdcf_bundle, idempotency_key="my-claim-001"
)
# Sign unsigned["tx_hash"] locally, then submit with submit_signed_register.

# 2. List | 3. Get
page     = moxie.claims.list(holder=holder)
claim    = moxie.claims.get(claim_id)
assert claim is not None
envelope = moxie.claims.get_with_pdcf_bundle(claim_id)

Payoffs — signed payoffRegister, moxie_payoffsDeclare, moxie_payoffsValidate, moxie_payoffsLibrary, moxie_payoffsCanonicalHash

Register a payoff body through signed moxie_buildTransaction when the program must persist in consensus, run structural validation, fetch the constructor catalog, or compute the canonical hash server-side for cross-SDK byte-equality. Tier-1 SDKs expose this as buildRegisterTransaction / submitSignedRegister in TypeScript, build_register_transaction / submit_signed_register in Rust and Python. declare is a compatibility preview that validates, hashes, and checks idempotency without mutating live executor state.

TypeScript
typescript
// 5. Live standalone payoff registration
const unsigned = await moxie.payoffs.buildRegisterTransaction(
  program,
  registrar,
  { idempotencyKey: "payoff-001", nonce: 7 },
);
const signed = await signer.signMoxieTx(unsigned.tx_hash);
await moxie.payoffs.submitSignedRegister(
  { ...signed, tx_bytes: unsigned.tx_bytes },
  { idempotencyKey: "payoff-001-submit" },
);

// 6. Declare preview (Idempotency-Key required; no live consensus write)
await moxie.payoffs.declare(program,
  { idempotencyKey: "payoff-preview-001" });

// 7. Validate (pure; no write)
const v = await moxie.payoffs.validate(program);

// 8. Library (constructor catalog + bounds)
const catalog = await moxie.payoffs.library();

// 9. CanonicalHash — server-side for TS/Python cross-SDK parity
const canonicalHash =
  await moxie.payoffs.canonicalHash(program);
Rust
rust
use moxie_sdk::resources::payoffs::*;

let unsigned = client.payoffs().build_register_transaction(
    program.clone(),
    registrar,
    BuildPayoffRegisterOptions {
        idempotency_key: "payoff-001".into(),
        nonce: Some(7),
    },
).await?;
let signed = signer.sign_moxie_tx(&unsigned.tx_hash)?;
client.payoffs().submit_signed_register(
    SubmitSignedPayoffRegisterEnvelope {
        tx_bytes: unsigned.tx_bytes,
        signature: signed.signature,
        signer: signed.signer,
        cryptographic_epoch: Some(1),
    },
    SubmitPayoffRegisterOptions {
        idempotency_key: "payoff-001-submit".into(),
    },
).await?;

let hash = moxie_sdk::payoff_canonical_hash(&program);
Python
python
unsigned = moxie.payoffs.build_register_transaction(
    program,
    registrar,
    nonce=7,
    idempotency_key="payoff-001",
)
signed = signer.sign_moxie_tx(unsigned["tx_hash"])
moxie.payoffs.submit_signed_register(
    {**signed, "tx_bytes": unsigned["tx_bytes"]},
    idempotency_key="payoff-001-submit",
)
hash_ = moxie.payoffs.canonical_hash(program)

Positions — moxie_positionsForClaim, moxie_positionsApplyDelta, moxie_positionsConservationCheck

Cursor-paginated holders for one Claim, internal apply-delta (surfaced via existing trade methods), and conservation check returning {net, total_long, total_short, is_balanced}. For derivative claims the protocol-level invariant is net == 0; for primary holdings net == issuer_supply.

TypeScript
typescript
// 9. ForClaim — cursor-paginated holders
const page = await moxie.positionsTyped.forClaim({
  claim_id, cursor, limit: 100,
});

// 10. ApplyDelta — internal; AuthWrite
await moxie.positionsTyped.applyDelta(
  { claim_id, holder, delta: { magnitude, is_negative: false } },
  { idempotency_key: "trade-001" },
);

// 11. ConservationCheck
const c = await moxie.positionsTyped.conservationCheck(claim_id);
console.log(c.is_balanced, c.net, c.total_long, c.total_short);
Rust
rust
use moxie_sdk::resources::positions_typed::*;

let page = client.positions_typed()
    .for_claim(claim_id, cursor, 100).await?;

client.positions_typed().apply_delta(
    claim_id, holder, signed_delta,
    ApplyDeltaOptions { idempotency_key: "trade-001".into() },
).await?;

let check = client.positions_typed()
    .conservation_check(claim_id).await?;
assert!(check.is_balanced);
Python
python
page  = moxie.positions_typed.for_claim(claim_id, cursor=cur, limit=100)
moxie.positions_typed.apply_delta(
    claim_id=claim_id, holder=holder, delta=delta,
    idempotency_key="trade-001",
)
check = moxie.positions_typed.conservation_check(claim_id)
assert check.is_balanced

Price vectors — moxie_priceVectorsCanonical, moxie_priceVectorsGradient

Canonical price vector returns {asof_block, items, next_cursor?}; each item is an admitted claim priced from its persisted PdcfBundle.present_value(). Gradient returns intrinsic payoff-DAG partials over PDCF-backed upstream RefClaim inputs. CPCAM correlation roots stay in the clearing-engine witness lane.

TypeScript
typescript
// 12. Canonical — PDCF present-value page
const snap = await moxie.priceVectors.canonical(0n, { limit: 100 });
console.log(snap.asof_block, snap.items, snap.next_cursor);

// 13. Gradient — per-claim drill-down
const g = await moxie.priceVectors.gradient({
  claim_id, at_block,
});
Rust
rust
use moxie_sdk::resources::price_vectors::*;

let snap = client.price_vectors()
    .canonical(0, PriceVectorFilter::default()).await?;
let g    = client.price_vectors()
    .gradient(claim_id, at_block).await?;
Python
python
snap = moxie.price_vectors.canonical(at_block=0)
g    = moxie.price_vectors.gradient(claim_id=cid, at_block=blk)
REST Surface

OpenAPI preview: /v1/claims, /v1/payoffs, /v1/positions, /v1/price-vectors

The typed-Claim resources mount under /v1 with cursor pagination, idempotency headers on writes, and the standard X-Request-Id / X-RateLimit-* / X-Moxie-Load / traceparent response set. The OpenAPI 3.1 generated spec at specs/openapi/moxie-protocol-v1.generated.json drives Tier-2 codegen across Go, Java, C#, Kotlin, and Swift.

Skeleton paths

Public-gateway examples use /v1; the node-local REST router currently mounts implementation routes under /api/v1. SDK docs document only mounted public routes.

specs/openapi/moxie-protocol-v1.yaml (preview)
yaml
# Claims
POST   /v1/claims/define                                # compatibility/local-demo; live nodes require signed claimRegister
GET    /v1/claims?holder=&legal_profile_id=&cursor=
GET    /v1/claims/{claim_id}                            # { claim, pdcf_bundle? }
POST   /v1/claims/preflight                             # 23-domain compliance + optional PDCF

# Payoffs
POST   /v1/payoffs                                      # compatibility preview; live nodes require signed payoffRegister
GET    /v1/payoffs/{payoff_root}
POST   /v1/payoffs/validate                             # pure validate; no write
GET    /v1/payoffs/library                              # constructor catalog + bounds

# Positions
GET    /v1/positions/{claim_id}?cursor=&limit=
GET    /v1/positions/{claim_id}/conservation            # {net, total_long, total_short, is_balanced}
GET    /v1/accounts/{addr}/positions?claim_id=&cursor=  # by holder

# Price vectors
GET    /v1/price-vectors/canonical                     # PDCF present-value page
GET    /v1/price-vectors/{claim_id}/gradient?at_block= # intrinsic payoff-DAG partials
API Spec

Need the exact wire surface?

Open the full Moxie API spec when you are wiring production paths: auth profiles, agent invocation envelopes, settlement jobs, continuous-market parameters, JSON-RPC methods, receipt proofs, realtime streams, and amount utilities.

Reference for backend, engine, and market infrastructure teams

The builder page stays focused on what you can ship first. The spec page carries the dense protocol material: clearing primitives, compliance preflight, AOT settlement receipts, MCP agent tools, method families, pagination, errors, WebSockets, and SDK amount helpers.

Open the Moxie API spec
production reference
moxie-api.html
// Move from first-market integration to exact wire semantics.
await moxie.preflightCompliance({ purpose, entity_ids });
await moxie.submitSigned(signedEnvelope, { preflight });
await moxie.getReceipt(txHash, { includeProof: true });
await moxie.subscribeBlocks(({ height }) => sync(height));
Tier-3 Game Engine SDKs

Native wrappers for Unity, Unreal, Godot, and Roblox

Tier-3 wrappers expose Moxie as a native game service. Three of the four engines (Unity, Unreal, Godot) share a single Rust core via the canonical narrow C ABI at crates/moxie-sdk-core/include/moxie_sdk_core.h; signing keys never cross the FFI boundary. The fourth engine, Roblox, has no FFI surface in the Luau sandbox — the wrapper consumes the typed-Claim REST surface directly via HttpService:RequestAsync and signs through a host signing adapter; keys never leave the adapter. Each engine wrapper ships on its own cadence across the v1.x point releases.

Unity — UPM + UniTask + P/Invoke

UnityPackageManager package inc.moxie.sdk. C# surface backed by P/Invoke into the Rust core; UniTask for the async poll loop on the engine main thread. Native plugin from cargo build -p moxie-sdk-core --release placed under Assets/Plugins/<platform>/. ABI version pin at moxie_sdk_core_abi_version() verified at startup.

Signing-key discipline: the wrapper accepts only pre-signed envelopes. The host's key-management plugin (MPC-with-passkey or a platform keystore) holds the secret key entirely outside this SDK's address space; the C# layer marshals the JSON envelope through the C ABI to moxie_claim_define_async. The moxie_envelope_sign entry point exists for binding completeness only and returns IntPtr.Zero; MoxieClient never calls it. The CannotSignAcrossFFIBoundary reflection test asserts no public method or property name on MoxieClient matches Sign | PrivateKey | SecretKey | Mnemonic | Seed | KeyPair | LoadKey | ImportKey | ExportKey.

install — Packages/manifest.json
jsonc
{
  "dependencies": {
    "inc.moxie.sdk":        "0.1.0",
    "com.cysharp.unitask":  "2.5.0"
  }
}
submit a pre-signed envelope
csharp
using Cysharp.Threading.Tasks;
using Moxie.Sdk;

public async UniTask SubmitClaim(string preSignedEnvelopeJson, CancellationToken ct)
{
    using var client = MoxieClient.Create(
        rpcUrl: "https://rpc.moxie.example",
        apiKey: "mxk_pk_prod_keyid_random");

    using MoxieReceipt receipt = await client.DefineClaimAsync(
        preSignedEnvelopeJson, ct);

    Debug.Log($"receipt: {receipt.ToJson()}");
}

Unreal Engine — UCLASS plugin + TFuture / FLatentActionInfo

Unreal Engine 5.3+ plugin under sdk/unreal/MoxieSdk/; UBT C++17 toolchain. UMoxieClient, UMoxieJob, and UMoxieReceipt are UObjects — pinned through TStrongObjectPtr or a UPROPERTY for the duration of access. Both Blueprint-friendly delegates (FLatentActionInfo + OnCompleted dynamic multicast) and C++-only futures (TFuture<UMoxieReceipt*>) are available. The runtime releases the underlying native handle on BeginDestroy; explicit Disconnect is idempotent.

Signing-key discipline: the same as Unity. FNoSigningKeysCrossFFI automation test asserts moxie_envelope_sign returns NULL and walks the reflected UMoxieClient UFunction set rejecting any Sign | PrivateKey | SecretKey member. The host key-management plugin (a separate native module wrapping the platform keychain or HSM-rotatable signing service) produces the JSON-encoded submit_signed envelope; the plugin forwards it without inspecting or re-signing.

install — .uplugin
terminal
$ git submodule add \
    https://github.com/momentum-sez/moxie-sdk-unreal \
    Plugins/MoxieSdk
$ cargo build -p moxie-sdk-core --release
$ cp target/release/libmoxie_sdk_core.dylib \
   Plugins/MoxieSdk/Source/ThirdParty/MoxieSdkCore/Mac/
submit + completion delegate
cpp
UMoxieClient* Client = UMoxieClient::Connect(
    TEXT("http://localhost:8545"),
    TEXT("mxk_pk_devnet_local"));

FLatentActionInfo Info;
UMoxieJob* Job = Client->DefineClaimAsync(PreSignedEnvelopeJson, Info);
Job->OnCompleted.AddDynamic(this, &MyClass::HandleClaimComplete);

Godot — GDExtension + RefCounted + signals

GDExtension wrapper under sdk/godot/moxie-sdk/; godot-cpp 4.2+ via SCons. MoxieClient, MoxieJob, and MoxieReceipt are GDScript-callable RefCounted classes. MoxieClient emits claim_defined and claim_failed signals; callers may also poll the returned MoxieJob manually for deterministic test scenarios. Lifetimes are governed by Ref<> and Vector<>; native handles release in destructors idempotently.

install + build
terminal
$ git submodule add https://github.com/godotengine/godot-cpp \
    sdk/godot/moxie-sdk/godot-cpp
$ cargo build -p moxie-sdk-core --release
$ cd sdk/godot/moxie-sdk && \
   scons platform=linuxbsd target=template_release
GDScript signal flow
gdscript
extends Node

var client: MoxieClient

func _ready() -> void:
    client = MoxieClient.new()
    client.configure("http://localhost:8545", "mxk_pk_dev_xxx")
    client.claim_defined.connect(_on_claim_defined)
    client.claim_failed.connect(_on_claim_failed)

    var job: MoxieJob = client.define_claim_async(JSON.stringify(envelope))

Roblox — HttpService + Wally + signed envelopes

Tier-3 wrapper under sdk/roblox/MoxieSdk/. Roblox uniquely has no FFI surface — the sandbox forbids native code — so this wrapper consumes the typed-Claim REST/read surface (/v1/claims/{id}, /v1/claims/preflight, /v1/claims?holder=...) via HttpService:RequestAsync. Live registration must route through a signing/session service that builds and signs NativeTx::ClaimRegister; /v1/claims/define is compatibility/local-demo only. Distributed via Wally; idempotency keys are constructed via HttpService:GenerateGUID(false) (RFC 4122 v4) so each mutation carries a unique tag.

Signing-key discipline: private keys never leave a host signing adapter. client:AttachSigner(signer) attaches an adapter that implements signer:SignEnvelope(payloadJson) -> hexSignature. Server-script-only path for mxk_sk_* bearer tokens; never embed bearer tokens in a LocalScript that ships to clients.

install — wally.toml
toml
[dependencies]
MoxieSdk = "moxie/moxie-sdk@1.0.0-rc.1"
define a typed Claim from a server script
luau
local MoxieSdk = require(game:GetService("ServerScriptService").MoxieSdk)
local client = MoxieSdk.MoxieClient.new(
    "https://rpc.moxie.inc",
    "mxk_sk_<env>_<kid>_<random>")

local receipt = client:DefineClaim({
    claim   = claimTable,
    payoff  = payoffTable,
    issuer  = "0xaaaa...",
})
print(receipt:ClaimId(), receipt:TxHash())
Under the Hood

How Moxie clears a claim, end to end

The internals, for teams who want them: every market surface lowers into the same terminal object.

The conceptual primitive: Claim

The unified field theory of finance is that the value of any asset is the probability-weighted discounted future cash flow (PDCF). Therefore every tradeable instrument is a claim on a future cash flow stream. Moxie's outward-facing concept is the claim and its derivatives. Claim binds an issuer + holder pair, a PayoffProgram via payoff_root, a strict-forward-temporal DAG of dependencies via depends_on, a probability/discount weight bundle via pdcf_root, an instrument back-link, a governing legal profile, and (when required) an SSB attestation root.

crates/moxie-types/src/claim.rs
rust
pub struct Claim {
    pub id: ClaimId,
    pub issuer: Address,
    pub holder: Address,
    pub settlement_asset: Hash256,
    pub payoff_root: Hash256,            // = PayoffProgram::canonical_hash()
    pub depends_on: BTreeSet<ClaimId>,  // strict-forward DAG witness
    pub pdcf_root: Hash256,             // P x D weight bundle
    pub instrument_id: Hash256,         // AOT InstrumentManifest link
    pub legal_profile_id: ProductLegalProfileId,
    pub ssb_attestation_root: Hash256,  // AAOIFI per-issuance SSB approval
    pub effective_from_block: BlockNumber,
    pub expires_at_block: BlockNumber,
    pub version: u32,
}

The protocol primitive: AdmissibleObligationTransition

AOT is the only object that changes terminal consensus state. Every state-mutating call resolves into AdmissionEnvelope + InstrumentManifest + ObligationGraph + ComplianceAttestationRef + RiskReserveHold + EvidenceEnvelope + ExecutionCertificate + SettlementJobRef + ReceiptProofRef + ReleaseRecoveryAuthorization + RelianceEnvelope. The supremum source layer above AOT is ClaimProgramDefinition → ClaimGraph → ClaimCompiler → AOT; the ClaimCompiler lowers the parimutuel, concentrated-AMM, sukuk, parametric-insurance, IP-royalty, and structured-note product families.

terminal kernel grammar
rust
pub struct AdmissibleObligationTransition {
    pub admission: AdmissionEnvelope,
    pub instrument: InstrumentManifest,
    pub obligation_graph: ObligationGraph,
    pub compliance: ComplianceAttestationRef,
    pub risk_reserve: RiskReserveHold,
    pub evidence: EvidenceEnvelope,
    pub execution: ExecutionCertificate,
    pub settlement: SettlementJobRef,
    pub receipt: ReceiptProofRef,
    pub release_recovery: ReleaseRecoveryAuthorization,
    pub reliance: RelianceEnvelope,
}

The product primitive: TemplatePack

Equities, bonds, structured derivatives, sukuk, real-world-asset receivables, parametric insurance, IP royalties, parimutuel pools, prediction events, loyalty entitlements, and trade receivables all compile into Moxie as TemplatePack instances. A TemplatePack is a versioned product family pinned to a ProductLegalProfile with allowed node/edge kinds, lifecycle policy, lowering rules, risk model, settlement program, recovery policy, reporting pack, reliance limits, and compiler version. The same lowering rules, risk model, and settlement program clear a parametric insurance contract and a prediction market alike.

claim program registry
rust
pub struct ClaimProgramDefinition {
    pub id: ClaimProgramId,
    pub template_pack_id: TemplatePackId,
    pub template_kind: TemplateKind,
    pub legal_profile_id: ProductLegalProfileId,
    pub version: u32,
    pub schema_root: Hash256,
    pub allowed_node_kinds_root: Hash256,
    pub allowed_edge_kinds_root: Hash256,
    pub lowering_rules_root: Hash256,
    pub lifecycle_policy_root: Hash256,
    pub enabled: bool,
}

The developer surface: SDK + REST + agent-store

Tier-1 hand-maintained Rust + TypeScript + Python SDKs at v1.0.0-rc.1. Tier-2 generated wrappers for Go / Java / C# / Kotlin / Swift. Tier-3 game-engine wrappers (Unity, Unreal, Godot, Roblox) over a Rust core; signing keys never cross the FFI boundary. JSON-RPC for the canonical wire surface, REST under /v1 for resource-shaped endpoints, WebSocket for realtime, and four auth profiles (DEV backend, key-native player, delegated session key, admin HSM).

Mass issues and governs claims; Moxie clears, settles, prices, and binds reliance to them.

three-tier SDK surface (v1.0.0-rc.1)
terminal
$ npm install @moxie/sdk@rc                       # v1.0.0-rc.1
$ cargo add moxie-sdk@"1.0.0-rc.1"             # v1.0.0-rc.1
$ pip install moxie-sdk==1.0.0rc1 httpx           # v1.0.0rc1
Typed Primitives

The core types

Four typed primitives span every market: Claim, PayoffProgram, Position/PositionLedger, and ClaimReservesN+ConvexPotentialN. The same types describe a Liverpool brand instrument, a Hong Kong Jockey Club daily double pool, a sukuk coupon, a Marvel royalty stream, an Aurelian Jockey Club perpetual, and a parametric flood-insurance contract.

PayoffProgram — the SSA-flat function-term tree

A PayoffProgram is a sequence of operations that deterministically computes a FixedPoint value as a function of constants, oracle attestation evidence, and earlier-resolved claims. References are strictly backward (ops[k].refs ⊂ {0..k}), and RefClaim::time_offset_blocks ≥ 1 so a derivative claim may only resolve against parents that resolved at strictly earlier blocks. The two invariants together make derivative cycles unrepresentable at the type level.

The operator set is Σ′ = Σ ∪ RefClaimReduce13 ops covering Asian-style averaged payoffs, lookback maxima, barrier knock-ins, memory coupons, Bermudan options with windowed exercise, and — through SaturatingSub plus the transcendental pair Ln and Sqrt — log-return variance legs and volatility (√) legs for the structured-note family. IndicatorPredicate::OpGteOp compares two on-graph values for parametric insurance multi-tier policies. ShariaInstrumentClass encodes the AAOIFI structure-specific gate at the type level for sukuk Ijara / Murabaha / Mudaraba / Musharaka. Bounds: MAX_PAYOFF_OPS = 256, MAX_PAYOFF_DEPTH = 32, MAX_LINEAR_COMBINE_INPUTS = 64, RefClaimReduce window [8, 4096] blocks.

13-op family (Σ′)
rust
pub enum PayoffOp {
    Const(FixedPoint),
    OracleEvidence { evidence_index: u32, leaf_index: u32 },
    RefClaim { claim_ref: ClaimRef, time_offset_blocks: u32 },
    LinearCombine { coefficients: Vec<FixedPoint>, inputs: Vec<PayoffOpId> },
    Multiply { lhs: PayoffOpId, rhs: PayoffOpId },
    Cap { input: PayoffOpId, cap_value: FixedPoint },
    Floor { input: PayoffOpId, floor_value: FixedPoint },
    Indicator { predicate: IndicatorPredicate },
    IfElse { cond: PayoffOpId, then_op: PayoffOpId, else_op: PayoffOpId },
    // Σ → Σ′ window-reduction extension:
    RefClaimReduce {
        claim_ref: ClaimRef,
        time_window_blocks: u32,        // in [8, 4096]
        kind: ReduceKind,                // Sum | Max | Min | Avg | Count
        threshold: Option<FixedPoint>,
    },
    // Spread legs without underflow panics:
    SaturatingSub { lhs: PayoffOpId, rhs: PayoffOpId },
    // Transcendental basis — variance & volatility legs:
    Ln { input: PayoffOpId },
    Sqrt { input: PayoffOpId },
}

pub enum IndicatorPredicate {
    BlockGte { block: BlockNumber },
    OpGte { op: PayoffOpId, threshold: FixedPoint },
    OracleEquals { evidence_index: u32, leaf_index: u32, expected: Hash256 },
    // Parametric-insurance multi-tier dynamic-threshold predicate:
    OpGteOp { trigger: PayoffOpId, threshold: PayoffOpId },
}

pub struct PayoffProgram {
    pub ops: Vec<PayoffOp>,
    pub output_index: PayoffOpId,
}

Position + PositionLedger — signed holdings

Position { claim_id, holder, signed_quantity } is the logical destructuring of one ledger entry. PositionLedger is the canonical storage form: BTreeMap<ClaimId, BTreeMap<Address, SignedFixedPoint>>, deterministic iteration, zero-quantity entries removed in canonical form. For derivative claims the protocol-level invariant is net == 0 across the sub-ledger; for primary holdings net == issuer_supply. Helpers net_for_claim, total_long_for_claim, total_short_for_claim, is_balanced_for_claim, apply_delta, and canonical_root ship with the typed-Position primitive.

crates/moxie-types/src/position.rs
rust
pub struct Position {
    pub claim_id: ClaimId,
    pub holder: Address,
    pub signed_quantity: SignedFixedPoint,  // + long, - short, 0 = empty
}

pub struct PositionLedger {
    pub entries: BTreeMap<ClaimId, BTreeMap<Address, SignedFixedPoint>>,
}

impl PositionLedger {
    pub fn apply_delta(&mut self, claim_id: ClaimId, holder: Address,
                       delta: SignedFixedPoint) -> Result<_, LedgerError>;
    pub fn net_for_claim(&self, claim_id: ClaimId) -> Result<_, _>;
    pub fn is_balanced_for_claim(&self, claim_id: ClaimId) -> bool;
    pub fn canonical_root(&self) -> Hash256;
}

ClaimReservesN + ConvexPotentialN — n-asset CPCAM

The 2-asset Reserves { hub, brand } is the n=2 specialization of ClaimReservesN(BTreeMap<ClaimId, FixedPoint>). ConvexPotentialN is the universal trait every pricing/clearing operator implements: evaluate_n (value at a reserve vector), gradient_n (the canonical price vector), and correlation_root (Hessian commitment, the same Hash256 that RiskGeneratorV1InputRoot.correlation_root consumes).

Existing 2-asset engines (ConstantProductPotential, WeightedProductPotential, ConcentratedPotential) compile without modification; PairPotential::new(potential, hub_id, brand_id) lifts them into the n-claim surface. MahalanobisPotential (phi(x) = ½ xT C x) is documented as the universal local quadratic linearization of any convex phi at equilibrium.

crates/moxie-dex/src/reserves_n.rs
rust
pub trait ConvexPotentialN: Send + Sync {
    fn evaluate_n(&self, reserves: &ClaimReservesN) -> FixedPoint;

    fn gradient_n(&self, reserves: &ClaimReservesN)
        -> BTreeMap<ClaimId, SignedFixedPoint>;

    fn correlation_root(&self, reserves: &ClaimReservesN) -> Hash256;

    fn as_mahalanobis(&self) -> Option<&MahalanobisPotential> { None }
}
Universality

Every market reduces to one shape

Every shipped market lowers into a (Claim, PayoffProgram, ConvexPotential) triple. The replay-equivalence conformance corpus at specs/sdk-conformance/claim_universality/ covers 12 active fixtures — 8 baseline reductions plus 4 product-family extensions (concentrated AMM, sukuk Ijara, parametric insurance, IP royalty stream) — with additional structural-products fixtures for the autocallable structured note, trade receivable, engagement loyalty, and variance swap.

1. Constant-product AMM

Brand pools, settlement-asset/MOXIE anchor, all 23 demo brand pools. Reserves (Rhub, Rbrand) on a k = Rhub · Rbrand manifold. Each side is a Claim with constant unit payoff (the pool unit itself). The CPCAM operator is ConstantProductPotential lifted to ConvexPotentialN via PairPotential::new(p, hub_claim, brand_claim). Gradient ratio is the spot price.

PayoffProgram::Const
rust
use moxie_types::payoff_lib::payoff_constant;

// Settlement-asset unit-claim payoff: always pay 1.00 USD.
let usd_payoff = payoff_constant(FixedPoint::one());

// CPCAM operator on (USD, MOXIE):
let phi = PairPotential::new(
    ConstantProductPotential,
    usd_claim_id,
    moxie_claim_id,
);

2. Bonding curve

Stage 1 of the 5-stage market lifecycle. P(S) = P0 · ((S + Sinit) / S0)n — shifted power-law. Each issued unit is a Claim of constant unit value; the supply-conditioned price comes from a ConvexPotentialN whose gradient evaluates the curve. Graduates into Stage-2 EquilibriumAMM at the PackVersionChanged cascade.

primary holding + curve
rust
// Brand-unit Claim: constant unit payoff, brand-issued.
let unit_claim = Claim {
    payoff_root: payoff_constant(FixedPoint::one()).canonical_hash(),
    legal_profile_id: brand_legal_profile,
    // ...
};

// Bonding-curve potential (stage 1).
let phi = BondingCurvePotential::shifted_power_law(p0, s0, s_init, n);

3. LMSR persona / prediction

Persona LMSR (logarithmic market scoring rule) is a known convex potential. Each persona outcome is a Claim with binary indicator payoff under OracleEvidence; the persona engine's cost function is its evaluate_n; gradient is the per-outcome odds vector.

persona LMSR triple
rust
// Outcome i Claim: indicator(oracle == i) -> 1, else 0.
use moxie_types::payoff_lib::payoff_event_contingent;
let outcome_payoff = payoff_event_contingent(
    /*evidence_index*/ 0,
    /*leaf_index*/    0,
    expected_outcome_hash,
    /*win*/  FixedPoint::one(),
    /*lose*/ FixedPoint::zero(),
);

// CPCAM operator: LMSR cost (existing implementation).
// Replay-equivalence fixture covers persona_lmsr engine.

4. Parimutuel pool

Hong Kong Jockey Club daily double, win pools, place pools. Each ticket is a Claim of payoff_pool_share(pool_total_ref, share_factor, time_offset). Pool total resolves at the race block; ticket Claims reference the pool Claim with time_offset_blocks ≥ 1 so settlement is strictly forward in time. The first ClaimCompiler vertical is the parimutuel/product vertical.

parimutuel ticket
rust
use moxie_types::payoff_lib::payoff_pool_share;

let ticket_payoff = payoff_pool_share(
    pool_total_claim_ref,
    /*share_factor*/  FixedPoint::from_ratio(stake, winning_pool),
    /*time_offset*/   1,  // resolves at parent block + 1
);

// First ClaimGraph compiler vertical:
// crates/moxie-types/src/claim_graph.rs lowers parimutuel into AOT.

5. Binary prediction

Yes/no events. Two outcome Claims with mutually-exclusive payoff_event_contingent programs over the same OracleEvidence leaf. CPCAM operator is the prediction-market AMM (PW-AMM coupling C1 clipped). The one-way coupling invariant (I-25) is type-level: MarketSpec.payoff may consume AMM signals; AMM state must not feed back into prediction payoff.

YES/NO event Claims
rust
let yes_payoff = payoff_event_contingent(0, 0, yes_hash, FixedPoint::one(), FixedPoint::zero());
let no_payoff  = payoff_event_contingent(0, 0, no_hash,  FixedPoint::one(), FixedPoint::zero());

// PW-AMM C1 clipped coupling (proven equivalent to logit).

6. Perpetual

FIGHT, MRDN, BULL perpetual markets at genesis. The perp position is a derivative Claim with payoff_linear_derivative(underlying, factor, time_offset); mark price comes from the underlying brand AMM. Funding accrual rides on a per-block RefClaim chain. CPCAM operator is the perpetual clearing potential.

linear derivative payoff
rust
use moxie_types::payoff_lib::payoff_linear_derivative;

let perp_payoff = payoff_linear_derivative(
    underlying_brand_claim_ref,
    /*factor*/       FixedPoint::one(),  // 1x exposure
    /*time_offset*/  1,
);

// SignedFixedPoint at the Position layer carries long/short sign.

7. Bond coupon

NativeTx bond variants 90-95 (issuance, transfer, redemption, acceleration, coupon payment) execute through Phase-3 handlers. Each coupon claim is payoff_fixed(amount, due_block); redemption is a separate Claim under the same TemplatePack. Sukuk-class issuance binds Claim.legal_profile_id to a Sharia-required profile and a non-zero ssb_attestation_root per AAOIFI SS 17 + GS 12.

coupon payoff
rust
use moxie_types::payoff_lib::payoff_fixed;

// Coupon: pay 50.00 USD at block 12,500,000.
let coupon_payoff = payoff_fixed(FixedPoint::from_integer(50), BlockNumber(12_500_000));

// Sukuk Claim: ssb_attestation_root MUST be non-zero.
let sukuk = Claim {
    legal_profile_id: sukuk_legal_profile_id,
    ssb_attestation_root: aaoifi_ssb_root,
    // ...
};

8. Linear option call

Strike-bounded payoff on an underlying claim: max(value(underlying) - strike, 0), time-gated by expiry block. payoff_lib::payoff_option_call emits the building blocks; the deterministic per-op SSA evaluator at crates/moxie-execution/src/payoff_evaluator.rs walks the tree at settlement. Same SSA discipline forbids cycles between the option Claim and its underlying.

European call
rust
use moxie_types::payoff_lib::payoff_option_call;

let call_payoff = payoff_option_call(
    underlying_claim_ref,
    /*strike*/        FixedPoint::from_integer(2_50),  // 2.50
    /*expiry_block*/  BlockNumber(13_000_000),
    /*time_offset*/   1,
);

Replay-equivalence conformance corpus

The universality conformance corpus at specs/sdk-conformance/claim_universality/ wires payoff_evaluator into a replay-equivalence harness against the existing implementations. All 8 baseline reductions actively pass: constant-product AMM, bonding curve, LMSR persona, parimutuel, binary prediction, perpetual, bond coupon, option call. The three ConvexPotentialN implementations that close the loop — BondingCurvePotential1D, LogSumExpPotential, ConstantSumPotentialKOutcome — ship in crates/moxie-dex/src/potential.rs with 19 unit tests pinning the canonical cross-checks byte-equal modulo divide-order.

Four product-family fixtures extend the corpus: concentrated_amm (CC-CFMM), sukuk_ijara (AAOIFI Ijara structure with ShariaInstrumentClass-pinned ProductLegalProfile), parametric_insurance (multi-tier hurricane cat-bond using IndicatorPredicate::OpGteOp), and ip_royalty_stream (royalty waterfall on revenue oracle). Autocallable structured notes now have a ClaimCompiler witness: autocallable_structured_note lowers as AutocallableStructuredNote into the programmable-security TemplatePack with byte-equal AOT replay. Trade-receivable and engagement-loyalty fixtures extend the corpus: trade_receivable (factoring with default-event indicator), engagement_loyalty (vesting points with RefClaimReduce(Sum)). The transcendental basis has since graduated: PayoffOp::Ln lowers the variance-swap family natively (squared log-returns reduced with RefClaimReduce(Sum)), and PayoffOp::Sqrt expresses the volatility-swap leg √realised-variance directly — the market-quoted σ without composition tricks.

  • 1. Constant-product AMMpayoff_constant(1.0) + ConstantProductPotential via PairPotential. Active.
  • 2. Bonding curvepayoff_constant(1.0) + BondingCurvePotential1D shifted power-law. Active.
  • 3. LMSR persona / predictionpayoff_event_contingent + LogSumExpPotential cost C(q) = b · log∑i exp(qi / b). Active.
  • 4. Parimutuel poolpayoff_pool_share + ConstantSumPotentialKOutcome k-outcome lift. Active.
  • 5. Binary prediction — YES/NO payoff_event_contingent pair under PW-AMM C1 clipped coupling. Active.
  • 6. Perpetualpayoff_linear_derivative + perpetual clearing potential. Active.
  • 7. Bond couponpayoff_fixed(amount, due_block) + BlockGte indicator. Active.
  • 8. Linear option callpayoff_option_call hockey-stick. Active.
  • 9. Concentrated AMM (CC-CFMM) — range-bounded liquidity using Cap/Floor; concentrated potential. Active.
  • 10. Sukuk Ijara — AAOIFI lease-back: principal + N lease-period payoff_ijara_rent + balloon, gated on ShariaInstrumentClass::Ijara + non-zero ssb_attestation_root. Active.
  • 11. Parametric insurance — multi-tier cat-bond via OracleEvidence × 2 → Indicator(OpGteOp) → IfElse; tier composition via LinearCombine over per-tier indicators. Active.
  • 12. IP royalty stream — revenue-share waterfall: RefClaimReduce(Sum) over a window of revenue oracle leaves with per-tranche payoff. Active.
  • Autocallable structured noteRefClaimReduce(Max) barrier lookback + RefClaimReduce(Sum) memory coupon, lowered as AutocallableStructuredNote through ClaimCompiler into AOT with byte-equal replay. Active compiler witness.
  • Structural extensionstrade_receivable, engagement_loyalty. Pin the schema without exercising new evaluation paths.
  • Variance & volatility swapsPayoffOp::Ln (graduated) lowers realised variance from squared log-returns; PayoffOp::Sqrt (graduated) takes √realised-variance for the volatility leg.
replay-equivalence harness
rust
// crates/moxie-conformance-claim-universality/
//   tests/replay_integration.rs
//
// 8 baseline reductions — all active:
fn constant_product_amm_pool_side_holdings_evaluate_to_one();
fn bonding_curve_under_bonding_curve_potential_1d();
fn lmsr_persona_under_log_sum_exp_potential();
fn parimutuel_under_constant_sum_potential_k_outcome();
fn binary_prediction_evaluates_yes_then_no_per_oracle_attestation();
fn perpetual_long_evaluates_to_factor_times_underlying_at_t_minus_1();
fn bond_coupon_evaluates_zero_pre_due_and_amount_at_or_after_due();
fn option_call_in_the_money_yields_positive_and_otm_yields_zero();

// 4 product-family fixtures — all active:
fn concentrated_amm_range_liquidity();
fn sukuk_ijara_lease_period_pays_at_due_block();
fn parametric_insurance_hurricane_category_5_triggers_payout();
fn ip_royalty_stream_waterfall();
Cross-Language Coverage

Typed-Claim primitives across all 8 client languages + frontend

Tier-1 (Rust + TypeScript + Python) + Tier-2 (Go + Java + C# + Kotlin + Swift) cover the typed-Claim surface byte-for-byte. The frontend consumes the same primitives through TanStack Query hooks. All 8 languages produce a byte-parallel SignedAmount {magnitude, is_negative} wire mirror — the identity for derivative-claim conservation across long/short positions, pinned by 32 cross-language conformance tests.

Coverage matrix — eight client languages plus frontend

The 13 JSON-RPC methods land identically across all three Tier-1 SDKs. Tier-2 wrappers inherit the wire surface from the JSON spec at specs/openapi/moxie-protocol-v1.generated.json. Tier-3 game-engine wrappers wrap the same Tier-1 Rust core via the canonical C ABI at crates/moxie-sdk-core/include/moxie_sdk_core.h; signing keys never cross the FFI boundary in Unity / Unreal / Godot, and Roblox uses HttpService to consume the typed-Claim REST surface directly because the sandbox has no FFI escape hatch.

  • Tier-1 (hand-maintained) — Rust at crates/moxie-sdk/src/resources/{claims, payoffs, positions_typed, price_vectors}.rs; TypeScript at sdk/typescript/src/resources/{claims, payoffs, positions-typed, price-vectors}.ts; Python at packages/sdk-python/moxie_sdk/resources/{claims, payoffs, positions_typed, price_vectors}.py.
  • Tier-2 (codegen) — Go at sdk/go/generated/; Java at sdk/java/generated/; C# at sdk/csharp/generated/; Kotlin at sdk/kotlin/generated/; Swift at sdk/swift/generated/. Regenerated via openapi-generator-cli 7.10.0 against the OpenAPI spec.
  • Tier-3 (game engines) — Unity (P/Invoke + UPM + UniTask) at sdk/unity/MoxieSdk/; Unreal (UCLASS plugin + TFuture/FLatentActionInfo) at sdk/unreal/MoxieSdk/; Godot (GDExtension + RefCounted + signals) at sdk/godot/moxie-sdk/; Roblox (HttpService + Wally + HttpService:GenerateGUID idempotency) at sdk/roblox/MoxieSdk/.
  • Frontend — TanStack Query v5 hooks at web/src/lib/typed-claim-hooks.ts, with web/src/views/ClaimsTabView.tsx registered in the hash router. Polling cadence 3s critical / 5s financial / 15s ambient.

Cross-language wire parity at specs/sdk-conformance/typed_claim_wire_parity/ — 7 fixtures covering claim struct, define request, indicator predicate variants, payoff op variants, payoff program canonical hash, canonical price vector response, apply-position-delta request. The SignedAmount {magnitude, is_negative} wire mirror is byte-equal across all three Tier-1 SDKs — the identity for derivative-claim conservation across long/short positions.

SignedAmount wire-parity
json
// specs/sdk-conformance/typed_claim_wire_parity/
//   apply_position_delta_request.json
// All 8 languages emit and consume this exact wire shape.
{
  "claim_id": "0x9a3f...",
  "holder":   "0xabc1...",
  "delta": {
    "magnitude":   "1500000000000000000",
    "is_negative": false
  }
}

// Long: is_negative=false, magnitude > 0
// Short: is_negative=true,  magnitude > 0
// Canonical zero: magnitude="0", is_negative=false
witness commands
terminal
$ cargo test -p moxie-sdk --test typed_claim_wire_parity
#   8 tests pass (Rust)

$ cd sdk/typescript && npx vitest run \
    tests/typed-claim-wire-parity.test.ts
#   8 tests pass (TypeScript)

$ pytest packages/sdk-python/tests/test_typed_claim_wire_parity.py
#   16 tests pass (Python)

$ cargo test -p moxie-rpc
#   671 / 671 pass — server side
Universal Invariants

28 invariants thread every surface

28 universal invariants (I-1 through I-28) thread every surface. The eight that bind Claim resources directly are surfaced here; the full catalog is on the API spec page.

Invariants applied to Claim resources

  • I-1 Brand tenant. Every Claim is keyed by (region_id, brand_id, claim_id). OAuth tokens scope claim-write to a tenant set.
  • I-5 Corridor correlation. corridor_id = blake3(idempotency_key ‖ tx_payload ‖ mass_entity_id ‖ asof) threads claim-mutating envelopes across moxie-rpc, moxie-execution, mez-moxie-bridge.
  • I-8 Idempotency mandatory. Idempotency-Key required on every POST /v1/claims, POST /v1/payoffs, POST /v1/positions. Same key + same body returns the cached response.
  • I-9 Cursor pagination. moxie_claimsList, moxie_positionsForClaim emit opaque base64 cursors. Offset pagination silently corrupts under mutation; cursors do not.
  • I-11 Typed scalars. FixedPoint 18-decimal strings, Hash256 lowercase 0x hex, Address checksummed 20-byte hex, BlockNumber u64 decimal string in REST. Identical across all ten language surfaces.
  • I-12 Typed errors. moxie.claim.invalid_payoff_root, moxie.claim.ssb_required_but_zero, moxie.claim.dependency_mismatch, moxie.claim.empty_validity_window — namespaced, additive-only, OpenAPI-cataloged.
  • I-15 23-domain compliance preflight. Every claim-mutating call preflights through the 23-domain tensor. Composition by pointwise meet on the Applicable fragment.
  • I-25 NativeTx lifecycle. NativeTx::TerminalKernel (variant 88) admits the AOT lowering for ClaimGraphs. Claim-resource RPC methods build typed NativeTx variants under the same lifecycle.
typed-error envelope (I-12)
json
{
  "error_code": "moxie.claim.ssb_required_but_zero",
  "message": "legal profile requires SSB attestation but ssb_attestation_root is ZERO",
  "retryable": "never",
  "remediation": "Obtain per-issuance AAOIFI SSB approval and bind ssb_attestation_root before retry.",
  "correlation_id": "err_01HX...",
  "http_status": 409,
  "docs_url": "https://docs.moxie.inc/errors/moxie.claim.ssb_required_but_zero",
  "context": { "legal_profile_id": "0x..." }
}
Mass Interface

Mass issues and governs claims; Moxie clears them

Mass kernel is the authority and governance source for claims. Moxie is the clearing kernel that prices, settles, and binds reliance to those claims through the mez-moxie-bridge.

Cross-repo binding contract

A typed Claim binds to Mass attestations via composite-signed envelopes (Ed25519 ‖ ML-DSA-65 ‖ SLH-DSA-SHA2-128s = 11,229-byte signature).

  • MassComplianceAttestation carries the full 23-coordinate L23Value tensor under composite-sig. Persisted in MassBridgeState::compliance_gate_attestation_meta keyed by (brand_id, target_stage); consumed by NativeTx::ComplianceAttestationReceived; revocation cascades through NativeTx::ComplianceRevoke.
  • MassClaimAttestation carries (claim_id, legal_profile_id, ssb_attestation_root, instrument_id) under composite-sig. Mass authority verifies, attests, and posts; Moxie admits via the AOT envelope.
  • corridor_id binding (I-5). Every claim-mutating envelope threads corridor_id across both kernels for cross-repo correlation. Derivation: blake3-derive("moxie/claim/corridor/v1", legal_profile_id ‖ holder ‖ effective_from_block) — the Claim.corridor_id field carries this binding (Site 1).
  • ObservationKind::PositionUpdate emission. Moxie posts position deltas back to the Mass corpus via MassObservationRelay::relay at /v1/kernel/market-signals, joining AgentInvocationOutcome as a typed observation kind.
Composite signature wire format
rust
pub struct MassClaimAttestation {
    pub claim_id: ClaimId,
    pub legal_profile_id: ProductLegalProfileId,
    pub instrument_id: Hash256,
    pub ssb_attestation_root: Hash256,  // non-zero iff required
    pub issued_at_block: BlockNumber,
    pub expires_at_block: BlockNumber,
    pub cryptographic_epoch: u32,
    pub nonce: u64,
    // Ed25519 (64) ‖ ML-DSA-65 (3,309) ‖ SLH-DSA-SHA2-128s (7,856) = 11,229 B
    pub signature_composite: [u8; 11_229],
}

// Moxie admits via NativeTx::TerminalKernel.

10 Mass-bridge integration sites — all built

Each site is a single point in the Moxie execution path where a claim binds to a Mass attestation, an observation, or a revocation. Every site is committed and source-backed.

  • Site 1Claim.corridor_id field on crates/moxie-types/src/claim.rs. Mass-bridge corridor binding on the typed-Claim primitive itself.
  • Site 2KernelState typed-Claim fields: state.frozen_claim_positions: BTreeMap<(ClaimId, Address), FrozenClaimEntry> revocation-cascade scaffold.
  • Site 3TxReceiptEvent::ClaimPositionFrozen + BlockExecutorError::{ClaimMassValidation, ClaimPositionFrozen} typed-error variants.
  • Site 4 — observation routing: mass_bridge::market_signal_from_observation routes PositionUpdate to MarketSignalKind::BrandVolume; mass_observation_relay::observation_to_corpus_fields emits domain="market-conduct" / evidence_type="position-update" with claim+holder tags.
  • Site 5 — revocation-cascade emit: exec_claim_revocation_cascade(revoked_issuer, revoked_at_block, reason) walks state.claims filtered by claim.issuer == revoked_issuer, freezes non-zero positions via mass_bridge.frozen_claim_positions.insert(...).
  • Site 6 — AOT compliance cross-validation: AdmissibleObligationTransition::validate_with_compliance_binding cross-validates AOT compliance.tensor_root + revocation_root against typed-claim's legal profile + Mass-bridge's live revocation root. Integration test aot_compliance_binding covers profile mismatch, missing legal profile, Mass revocation mismatch, SSB-required-but-tensor-zero (sukuk path), eligibility-policy-zero, and the success path; 6/6 pass.
  • Site 7settlement_compliance_gate(claim_id, holder, current_block) runs BEFORE exec_claim_payoff_settle on every NativeTx::ClaimPayoffSettle; gate failure surfaces typed-error in the receipt.
  • Site 8validate_position_open(claim, holder, legal_profile, state) runs meets_minimum_compliance(&gate_status); for SSB-tagged claims, queries entity_grades directly for the Sharia coordinate.
  • Site 9AgentInvocation claim_id route enforcement + composite-sig envelope for typed-Claim mutations.
  • Site 10 — snapshot-restore propagation: KernelState.position_ledger and KernelState.claims propagated through chain/mod.rs snapshot-restore flow.

Production admit gate active. The legacy fail-closed HandlerNotImplemented arm in block_executor::exec_phase1 is replaced with unreachable!() — the gate-then-handler path is now exhaustive.

corridor_id derivation
rust
// crates/moxie-types/src/claim.rs (Site 1):
// corridor_id derivation for typed-Claim ↔ Mass binding.

pub fn derive_corridor_id(
    legal_profile_id: ProductLegalProfileId,
    holder: Address,
    effective_from_block: BlockNumber,
) -> CorridorId {
    blake3_derive(
        b"moxie/claim/corridor/v1",
        &[
            legal_profile_id.as_bytes(),
            holder.as_bytes(),
            &effective_from_block.to_le_bytes(),
        ],
    )
}

// Threaded through every claim-mutating envelope as I-5 corridor
// correlation. Bridges across moxie-rpc, moxie-execution,
// mez-moxie-bridge for cross-kernel observability and trace.
Formal Verification

TLA+ refinement: typed-Claim payoff scheduler

A bounded model-check at specs/tla/MoxieClaimPayoffScheduler.tla faithfully models the typed-Claim DAG-depth-round scheduler at crates/moxie-execution/src/claim_payoff_handler.rs::schedule_phase1_claim_settlements. The model exhaustively explores acyclic parent-relation shapes over four claims, depth bound 3, block horizon 5 — covering every DAG topology the scheduler can encounter.

Witness

  • States generated: 524,422 / distinct: 285,547 / state-graph depth: 9
  • Temporal properties checked: 4 branches over the complete state space (1,142,188 distinct states across temporal subspaces) — all pass
  • Wall time: ~16s on M-series hardware with JDK 25 + 4 worker threads
  • Result: No error has been found

Invariants verified: DepthBounded (round-loop respects MAX_SETTLEMENT_DEPTH_PER_BLOCK = 8), NoForwardReference (RefClaim::time_offset_blocks ≥ 1 at admission), CycleImpossible (admission rejects any payload that would create a derivative cycle), FrozenImmutable (Mass-bridge frozen-position ledger is monotone — cascade-frozen claims never re-enter Pending), PendingNeverResolvedTwice (pending_claim_settlements.remove after each settle), and a liveness witness AllResolvableEventuallyResolve under TLC fairness.

run TLC
terminal
$ cd specs/tla
$ java -XX:+UseParallelGC -cp lib/tla2tools.jar tlc2.TLC \
    -workers 4 \
    -metadir /tmp/moxie-tla-claim-scheduler \
    -config MoxieClaimPayoffScheduler.cfg \
    MoxieClaimPayoffScheduler.tla
# 524,422 states / 285,547 distinct / depth 9
# 4 temporal property branches all pass
# No error has been found.   Finished in 14s.