Clearing and settlement for claims.
Moxie clears and settles PDCF-priced claims and their derivatives. Every tradeable instrument — equity-style brand exposure, prediction outcomes, parimutuel pools, racing dividends, royalty streams, sukuk coupons, parametric insurance, perpetuals, options, receivables — lowers into a typed Claim with a PayoffProgram over a strict-forward-temporal DAG. CPCAM is the general-purpose convex-program operator that quotes, clears, and prices correlated claims under one constraint surface. AOT is the admissibility, settlement, release, and reliance envelope.
Four layers, one terminal kernel
Moxie is layered top-to-bottom so that product surfaces stay domain-natural while consensus stays generic. Every developer-callable surface lowers into the same terminal object.
Layer 1 — 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.
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,
}
Layer 2 — 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 first compiler vertical (parimutuel/product) is shipped, broader product-family compilers are residual.
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,
}
Layer 3 — Product primitive: TemplatePack
Equities, bonds, structured derivatives, sukuk, RWAs, 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. Sports + event-contingent markets are one product family of nine, not the universal pitch.
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,
}
Layer 4 — 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, wallet-native player, delegated session key, admin HSM).
Mass mints and governs claims; Moxie clears, settles, prices, and binds reliance to them.
$ 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
The four types that span every market
Four typed primitives span every market: Claim, PayoffProgram (SSA-flat function-term tree), Position/PositionLedger, and ClaimReservesN+ConvexPotentialN with multi-claim convex-program solver. The same types describe a Liverpool token, 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 Σ′ = Σ ∪ RefClaimReduce — 13 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.
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.
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.
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 }
}
Eight reductions: every shipped market shape lowers into one triple
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 three additional structural-products fixtures (autocallable structured note, trade receivable, engagement loyalty) and a variance_swap residual marker awaiting Ln operator graduation. The triples themselves are unambiguous.
1. Constant-product AMM
Brand pools, USDC/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 token itself). The CPCAM operator is ConstantProductPotential lifted to ConvexPotentialN via PairPotential::new(p, hub_claim, brand_claim). Gradient ratio is the spot price.
use moxie_types::payoff_lib::payoff_constant;
// USDC unit-claim payoff: always pay 1 USDC.
let usdc_payoff = payoff_constant(FixedPoint::one());
// CPCAM operator on (USDC, MOXIE):
let phi = PairPotential::new(
ConstantProductPotential,
usdc_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 minted 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.
// Token Claim: constant unit payoff, brand-issued.
let token_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.
// 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.
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.
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.
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 variants 90-95 (BondIssue, BondMint, BondTransfer, BondRedeem, BondAccelerate, CouponPayment) 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.
use moxie_types::payoff_lib::payoff_fixed;
// Coupon: pay 50 USDC 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, // load-bearing
// ...
};
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.
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. Two remaining structural-products fixtures ship the SHOULD-EXIST shape under Σ′: 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 AMM —
payoff_constant(1.0)+ConstantProductPotentialviaPairPotential. Active. - 2. Bonding curve —
payoff_constant(1.0)+BondingCurvePotential1Dshifted power-law. Active. - 3. LMSR persona / prediction —
payoff_event_contingent+LogSumExpPotentialcostC(q) = b · log∑i exp(qi / b). Active. - 4. Parimutuel pool —
payoff_pool_share+ConstantSumPotentialKOutcomek-outcome lift. Active. - 5. Binary prediction — YES/NO
payoff_event_contingentpair under PW-AMM C1 clipped coupling. Active. - 6. Perpetual —
payoff_linear_derivative+ perpetual clearing potential. Active. - 7. Bond coupon —
payoff_fixed(amount, due_block)+BlockGteindicator. Active. - 8. Linear option call —
payoff_option_callhockey-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 onShariaInstrumentClass::Ijara+ non-zerossb_attestation_root. Active. - 11. Parametric insurance — multi-tier cat-bond via
OracleEvidence × 2 → Indicator(OpGteOp) → IfElse; tier composition viaLinearCombineover 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 note —
RefClaimReduce(Max)barrier lookback +RefClaimReduce(Sum)memory coupon, lowered asAutocallableStructuredNotethrough ClaimCompiler into AOT with byte-equal replay. Active compiler witness. - Structural extensions (SHOULD-EXIST shapes) —
trade_receivable,engagement_loyalty. Pin the schema under Σ′ without exercising new evaluation paths. - Variance & volatility swaps —
PayoffOp::Ln(graduated) lowers realised variance from squared log-returns;PayoffOp::Sqrt(graduated) takes √realised-variance for the volatility leg.
// 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();
Start with products, not protocol jargon
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; consensus stays generic, not one native transaction per 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.
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.
// 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_token: "USDC",
});
await moxie.predictionMint({
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.
const merch = await moxie.getMerchandise("0x<brand-id>");
const order = await moxie.merchOrder({
buyer: "0x<player-wallet>",
itemId: merch[0].id,
brandId: "0x<brand-id>",
quantity: 1,
paymentToken: "USDC",
maxPrice: "50000000000000000000",
});
console.log(order.order_id, order.status);
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 canonicalclaim_idbefore any write.moxie_buildTransactionwithmethod: "claimRegister"—claims:write. Builds unsigned Borsh bytes forNativeTx::ClaimRegister { claim, payoff, program_kind?, pdcf_bundle?, idempotency_key, nonce }; submit the signed envelope withmoxie_submitSigned. Receipt emitsclaim_registered.moxie_claimsDefine— compatibility/local-demo admission only. On live nodes it fails closed withmoxie.claims.define_requires_signed_native_txinstead 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_bundleis present when the typed valuation bundle was supplied and persisted at admission time.
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 wallet.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_buildTransactionwithmethod: "payoffRegister"—payoffs:write. Builds unsigned Borsh bytes forNativeTx::PayoffRegister { registrar, program, idempotency_key, nonce }; submit the signed envelope withmoxie_submitSigned. Receipt emitspayoff_registered.moxie_payoffsDeclare— AuthWrite compatibility preview. Validates the payoff body, computescanonical_hash, and enforces idempotency; live nodes use signedpayoffRegisterfor 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.
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}.
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.
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.
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);
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. The load-bearing finding: all 8 languages produce a byte-parallel SignedAmount {magnitude, is_negative} wire mirror — the load-bearing 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 atsdk/typescript/src/resources/{claims, payoffs, positions-typed, price-vectors}.ts; Python atpackages/sdk-python/moxie_sdk/resources/{claims, payoffs, positions_typed, price_vectors}.py. - Tier-2 (codegen) — Go at
sdk/go/generated/; Java atsdk/java/generated/; C# atsdk/csharp/generated/; Kotlin atsdk/kotlin/generated/; Swift atsdk/swift/generated/. Regenerated viaopenapi-generator-cli 7.10.0against the OpenAPI spec. - Tier-3 (game engines) — Unity (P/Invoke + UPM + UniTask) at
sdk/unity/MoxieSdk/; Unreal (UCLASS plugin +TFuture/FLatentActionInfo) atsdk/unreal/MoxieSdk/; Godot (GDExtension +RefCounted+ signals) atsdk/godot/moxie-sdk/; Roblox (HttpService + Wally +HttpService:GenerateGUIDidempotency) atsdk/roblox/MoxieSdk/. - Frontend — TanStack Query v5 hooks at
web/src/lib/typed-claim-hooks.tswith placeholderweb/src/views/ClaimsTabView.tsxregistered in the hash router. Polling cadence 3s critical / 5s financial / 15s ambient perweb/CLAUDE.md.
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 load-bearing identity for derivative-claim conservation across long/short positions.
// 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
$ 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
28 invariants thread every surface
PLATONIC-IDEAL-SDK.md §1 specifies 28 universal invariants (I-1 through I-28). 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 acrossmoxie-rpc,moxie-execution,mez-moxie-bridge. - I-8 Idempotency mandatory.
Idempotency-Keyrequired on everyPOST /v1/claims,POST /v1/payoffs,POST /v1/positions. Same key + same body returns the cached response. - I-9 Cursor pagination.
moxie_claimsList,moxie_positionsForClaimemit opaque base64 cursors. Offset pagination silently corrupts under mutation; cursors do not. - I-11 Typed scalars.
FixedPoint18-decimal strings,Hash256lowercase 0x hex,Addresschecksummed 20-byte hex,BlockNumberu64 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 (F135 + F142 + F144 unified).
- 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.
{
"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 mints 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. All 10 Moxie-side bridge sites are built and source-backed. Cross-repo Mass live smoke remains the only Mass-side residual.
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, F25 cryptographic epoch).
MassComplianceAttestation(M7 wired). Carries the full 23-coordinateL23Valuetensor under F25 composite-sig. Persisted inMassBridgeState::compliance_gate_attestation_metakeyed by(brand_id, target_stage); consumed byNativeTx::ComplianceAttestationReceived; revocation cascades throughNativeTx::ComplianceRevoke.MassClaimAttestation(proposed wire type, Mass-side residual). Carries(claim_id, legal_profile_id, ssb_attestation_root, instrument_id)under F25 composite-sig. Mass authority verifies, attests, and posts; Moxie admits via the AOT envelope.corridor_idbinding (I-5). Every claim-mutating envelope threadscorridor_idacross both kernels for cross-repo correlation. Derivation:blake3-derive("moxie/claim/corridor/v1", legal_profile_id ‖ holder ‖ effective_from_block)— theClaim.corridor_idfield carries this binding (Site 1).ObservationKind::PositionUpdateemission (Moxie-side wired). Moxie posts position deltas back to the Mass corpus viaMassObservationRelay::relayat/v1/kernel/market-signals, joiningAgentInvocationOutcomeas a typed observation kind. Mass-side ingestion smoke is residual.
pub struct MassClaimAttestation { // proposed; Mass-side residual
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-side admission via NativeTx::TerminalKernel is shipped.
// Cross-repo Mass live smoke ceremony remains residual.
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 1 —
Claim.corridor_idfield oncrates/moxie-types/src/claim.rs. Mass-bridge corridor binding on the typed-Claim primitive itself. - Site 2 —
KernelStatetyped-Claim fields:state.frozen_claim_positions: BTreeMap<(ClaimId, Address), FrozenClaimEntry>revocation-cascade scaffold. - Site 3 —
TxReceiptEvent::ClaimPositionFrozen+BlockExecutorError::{ClaimMassValidation, ClaimPositionFrozen}typed-error variants. - Site 4 — observation routing:
mass_bridge::market_signal_from_observationroutesPositionUpdatetoMarketSignalKind::BrandVolume;mass_observation_relay::observation_to_corpus_fieldsemitsdomain="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)walksstate.claimsfiltered byclaim.issuer == revoked_issuer, freezes non-zero positions viamass_bridge.frozen_claim_positions.insert(...). - Site 6 — AOT compliance cross-validation:
AdmissibleObligationTransition::validate_with_compliance_bindingcross-validates AOTcompliance.tensor_root+revocation_rootagainst typed-claim's legal profile + Mass-bridge's live revocation root. Integration testaot_compliance_bindingcovers 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 7 —
settlement_compliance_gate(claim_id, holder, current_block)runs BEFOREexec_claim_payoff_settleon everyNativeTx::ClaimPayoffSettle; gate failure surfaces typed-error in the receipt. - Site 8 —
validate_position_open(claim, holder, legal_profile, state)runsmeets_minimum_compliance(&gate_status); for SSB-tagged claims, queriesentity_gradesdirectly for the Sharia coordinate. - Site 9 —
AgentInvocationclaim_id route enforcement + composite-sig envelope for typed-Claim mutations. - Site 10 — snapshot-restore propagation:
KernelState.position_ledgerandKernelState.claimspropagated throughchain/mod.rssnapshot-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.
// 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.
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/token → mxat_* bearers. mTLS RFC 8705 + private_key_jwt RFC 7521. Use this for server-side claim definition, payoff declaration, position writes.
Profile 2 — Wallet-native player (SIWE EIP-4361)
POST /v1/auth/siwe/{nonce, verify} → mxs_player_* session scoped to Address. MPC-with-passkey wallet + ML-DSA-65 PQ seed. Players read positions, hold derivative claims, sign trade envelopes.
// Profile 3 — Delegated session key (macaroon-attenuated).
// Secondary secp256k1 keypair bound on-chain as a restricted signer.
// Caveats as first-party macaroon predicates: max_cost, persona, device.
// Attenuate-only; child ⊆ parent; depth ≤ 8.
// ERC-4337 paymasters live here; first-mint gasless.
// 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.
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, gas 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.
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 wallet.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]);
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?;
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.
// 5. Live standalone payoff registration
const unsigned = await moxie.payoffs.buildRegisterTransaction(
program,
registrar,
{ idempotencyKey: "payoff-001", nonce: 7 },
);
const signed = await wallet.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);
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 = wallet.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);
unsigned = moxie.payoffs.build_register_transaction(
program,
registrar,
nonce=7,
idempotency_key="payoff-001",
)
signed = wallet.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.
// 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);
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);
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.
// 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,
});
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?;
snap = moxie.price_vectors.canonical(at_block=0)
g = moxie.price_vectors.gradient(claim_id=cid, at_block=blk)
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.
$ npm install @moxie/sdk@rc # v1.0.0-rc.1
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.
[dependencies]
moxie-sdk = "1.0.0-rc.1"
serde_json = "1"
tokio = { version = "1", features = ["full"] }
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 install moxie-sdk==1.0.0rc1
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.
{
"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
}]
}
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.
$ 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.
$ 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. Tier-3 wrappers ship under the v1.x point-release contract; mainnet does NOT gate on the slowest engine wrapper.
# 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)
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.
# 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
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// 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));
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-wallet adapter that never leaves the adapter. Per CLAUDE.md §0.4: mainnet does NOT gate on the slowest engine wrapper.
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 wallet plugin (WalletConnect, Magic Link, MPC-with-passkey) 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.
{
"dependencies": {
"inc.moxie.sdk": "0.1.0",
"com.cysharp.unitask": "2.5.0"
}
}
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 wallet 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.
$ 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/
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.
$ 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
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 wallet/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-wallet 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.
[dependencies]
MoxieSdk = "moxie/moxie-sdk@1.0.0-rc.1"
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())
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.
$ 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.
Discipline gates that every PR must pass
Production discipline lives in CI. Every push and pull-request runs a fixed set of audit gates that reject canonical-convention drift before code lands.
Active CI gates
- Byte-order canonical convention —
tools/audit-byte-order.sh, workflow.github/workflows/byte-order-gate.yml. Rejects new big-endian byte-ordering call sites outside a documented six-category allowlist (fork-gated state-root migration, sortable RocksDB keys, sortable IDs, cross-language SDK content-addressing, pre-fork preimage canon, 32-byte address synthesis). - Canonical numbers ratchet —
tools/regenerate-canonical-numbers.sh, workflow.github/workflows/canonical-numbers-gate.yml. Rejects PRs that move LOC, tests, Kani harnesses, RPC method counts, NativeTx variants, fixtures, or LaTeX line counts without updatingCLAUDE.md§0.5. - SystemTime consensus-leak gate —
tools/audit-systemtime-consensus-leak.sh, workflow.github/workflows/systemtime-consensus-gate.yml. Rejects anySystemTime::now()(or equivalent host-time read) on a consensus-affecting code path; consensus reads block-proposer timestamps, never host clocks. - Stale-signal retrieval hygiene —
tools/audit-stale-signal.sh. Rejects active steering documents that revive retired framings (event-only clearing, ClaimGraph-as-terminal-consensus, IP Operating System, Heyting-on-tensor, retired NativeTx-per-app variants). - Mass cross-repo claim smoke (stub mode on every PR) —
tools/cross-repo-smoke-claim.sh, workflow.github/workflows/mass-bridge-claim-smoke.yml. Drives the typed-Claim Mass↔Moxie round-trip:moxie_claimsPreflight → NativeTx::ClaimRegister → moxie_getReceipt claim_registered → MassClaimAttestation (or stub) → NativeTx::ClaimAttestationReceived → moxie_getReceipt claim_attestation_applied → holder MassComplianceAttestation → NativeTx::ComplianceAttestationReceived → moxie_getReceipt compliance_attestation_applied → ClaimPayoffSettle compliance gate → moxie_getReceipt claim_payoff_settled → ObservationKind::PositionUpdate → Mass corpus. The live-smoke job is opt-in via workflow_dispatch; the stub-smoke job protects harness regressions on every push. - OpenAPI regen drift gate —
.github/workflows/openapi-regen-gate.yml. Re-runssdk/.codegen/regen-all.shagainstspecs/openapi/moxie-protocol-v1.yamland fails CI if any Tier-2 generated source drifts from the committed tree. - Forbidden-git-ops grep —
.github/workflows/forbidden-git-ops-grep.yml. Rejects commit messages that disclose destructive git operations (force-push, hard-reset, history rewrite); the operator-side hook attools/git-discipline-hook.shis the local counterpart.
$ bash tools/audit-byte-order.sh
$ bash tools/audit-systemtime-consensus-leak.sh
$ bash tools/audit-stale-signal.sh
$ bash tools/regenerate-canonical-numbers.sh
$ bash tools/cross-repo-smoke-claim.sh --stub-mode
Honest status: built, residual
The typed-Claim primitive surface is built and witnessable from the working tree. What remains is a thin band of cross-repo integration, formal-runtime witnesses, and external operator gates. Active control-plane rule: never claim universal ClaimGraph product coverage, terminal SDK/API resources, or product-specific compiler coverage until the corresponding witnesses exist.
Built — source-backed
- Typed-Claim primitive.
crates/moxie-types/src/claim.rs(Claim,ClaimId);crates/moxie-types/src/payoff.rs(PayoffProgram,PayoffOp,ClaimRef, bounds,RefClaimReduce,IndicatorPredicate::OpGteOp);crates/moxie-types/src/payoff_lib.rs(constructors);crates/moxie-types/src/sharia.rs(ShariaInstrumentClass). 47+ unit tests + 12 proptest properties at 256 cases each. SSB-attestation-iff-required enforced at the type level. - Position primitive.
crates/moxie-types/src/position.rs—Position,PositionLedger, conservation helpers, canonical root. 18 unit + 8 proptest at 256 cases each. - n-claim CPCAM solver.
crates/moxie-dex/src/reserves_n.rs—ClaimReservesN,ConvexPotentialNtrait,PairPotentialadapter,MahalanobisPotential.crates/moxie-dex/src/cpcam_n.rs—ConvexPotentialEngineNwithquote_n/swap_n, Mahalanobis closed-form fast path viaas_mahalanobis()trait dispatch (nodyn Any), ray-bisection for general convex phi.correlation_root()is the canonical Hash256 consumed byRiskGeneratorV1InputRoot.correlation_root. - SSA-flat per-op evaluator.
crates/moxie-execution/src/payoff_evaluator.rs— deterministic per-op evaluator over the 13-op Σ′: Const, OracleEvidence (32-byte little-endian rawU256decode), RefClaim, LinearCombine, Multiply, Cap, Floor, Indicator (incl.OpGteOp), IfElse, RefClaimReduce, SaturatingSub, Ln (deterministic fixed-point natural log), Sqrt (deterministic Newton-iteration square root). - ClaimGraph claims layer.
ClaimGraphextends withclaims: BTreeMap<ClaimId, Claim>,claims_root: Hash256,claims_layer_version: u32.terms_root_v1()domain-tagged composition.validate_claims_layer()+ cross-validation invalidate_for_program. First compiler vertical (parimutuel/product) lowers into AOT, preserves AOT as terminal consensus truth, and rejects missing assent/risk/evidence/reliance. - Production admit gate. Phase-1 dispatch arm for
NativeTx::ClaimPayoffSettlecallssettlement_compliance_gate(claim_id, holder, current_block)beforeexec_claim_payoff_settle; gate failure surfaces typed-errorTxReceipt::fail; success emitsClaimPayoffSettled; the legacy fail-closedHandlerNotImplementedarm is nowunreachable!(). - Tier-1 SDK fanout. Rust + TypeScript + Python client resources cover typed-Claim reads, preflight, payoffs, positions, price vectors, and live
claimRegister/payoffRegisterbuild/submit helpers. Live claim and standalone payoff registration now go through signed native transactions;moxie_claimsDefineandmoxie_payoffsDeclareremain compatibility/local-demo previews only. - OpenAPI 3.1 spec.
specs/openapi/moxie-protocol-v1.yaml+.generated.jsondocument the compatibility/v1/claims/defineroute plus the typed-Claim read/preflight resources. Public SDK docs must route live registration through the signed transaction builder. - Tier-2 SDK regen. Go + Java + C# + Kotlin + Swift regenerated via
openapi-generator-cli 7.10.0against the OpenAPI spec. - Tier-3 wrappers. Unity (UPM + UniTask + P/Invoke), Unreal (UCLASS +
TFuture), Godot (GDExtension + signals), Roblox (HttpService + Wally + signed envelopes). Signing keys never cross any FFI; conformance fixtures atspecs/sdk-conformance/tier3/{unity, unreal, godot, roblox}/. - Universality replay corpus.
crates/moxie-conformance-claim-universality/tests/replay_integration.rs— 8 baseline reductions + 4 product-family fixtures all active; 3 structural-products fixtures pin shape under Σ′; 1 residual marker (variance swap) awaitsLngraduation. - Cross-language wire parity.
specs/sdk-conformance/typed_claim_wire_parity/— 7 fixtures + 32 conformance tests (Rust 8 + TypeScript 8 + Python 16). TheSignedAmount {magnitude, is_negative}wire mirror is byte-equal across all three Tier-1 SDKs. - Frontend hooks + view.
web/src/lib/typed-claim-hooks.ts— TanStack Query v5 hooks at the 3s/5s/15s polling cadence;web/src/views/ClaimsTabView.tsxplaceholder registered inpage.tsxhash router. - Continuous-CPCAM n-claim extension.
crates/moxie-dex/src/cpcam_continuous.rsextends Continuous-CPCAM withquote_continuous_n/settle_continuous_noverClaimReservesN+dyn ConvexPotentialN. Criterion bench atcrates/moxie-dex/benches/cpcam_n.rs. - Mass-bridge integration — 10 of 10 sites. See §Mass Interface for the full site map.
- AOT terminal kernel.
crates/moxie-types/src/terminal_kernel.rs—NativeTx::TerminalKernel(variant 88), TemplatePack + ProductLegalProfile registries, recognized reliance instruments, plane roots, hot-market replay status. - SettlementBatch primitive.
NativeTx::SettlementBatch,exec_settlement_batch, receipt-root/event-root binding,moxie_estimateSettlementBatch,moxie_submitSettlementBatch, three Tier-1 settlement SDK resources, SDK→RPC E2E coverage, conformance fixtures, TLA+ refinement, liveNativeTx::PayoutReturned+ committedTxReceiptEvent::PayoutReturned. - F25 composite-sig admission. Ed25519 ‖ ML-DSA-65 ‖ SLH-DSA-SHA2-128s = 11,229-byte signature,
cryptographic_epoch: u32, monotonic regression check, replay protection. Mass key provisioning hardened. - M7 Mass-side compliance attestation pipeline.
MassComplianceAttestationcarries the full 23-coordinateL23Valuetensor;NativeTx::ComplianceAttestationReceived+NativeTx::ComplianceRevokewired;ComplianceGateAttestationMetapersisted inMassBridgeState. - Standalone whitepaper.
moxie-whitepaper/claim-as-primitive.texproves operator-set completeness, Hessian-as-correlation, and 8-reduction universality; bound intoMoxieWhitepaper.texmaster volume. - 3 Kani harnesses + Criterion bench.
cpcam_n_claim_convexity_preserved,cpcam_n_claim_pair_byte_equal_n2,cpcam_n_claim_gradient_first_order;crates/moxie-dex/benches/cpcam_n.rscovers the n-claim solver path.
$ cargo test -p moxie-types claim --lib
$ cargo test -p moxie-types payoff --lib
$ cargo test -p moxie-types position --lib
$ cargo test -p moxie-types --test claim_graph_compiler
$ cargo test -p moxie-types --test terminal_kernel_contract
$ cargo test -p moxie-types --test aot_compliance_binding
$ cargo test -p moxie-dex reserves_n --lib
$ cargo test -p moxie-dex --lib cpcam_n
$ cargo test -p moxie-execution payoff_evaluator --lib
$ cargo test -p moxie-execution --test terminal_kernel_runtime
$ cargo test -p moxie-rpc
$ cargo test --manifest-path sdk/rust/Cargo.toml
$ cargo test -p moxie-conformance-claim-universality
$ cargo test -p moxie-sdk-core
$ bash tools/regenerate-canonical-numbers.sh
Mainnet readiness — top operator-side residuals
The remaining mainnet gates are operator-side ceremony or external audit closure, not protocol code. The repo is launch-feasible from the engineering side; mainnet ships when these external gates close. See docs/runbooks/MAINNET_HITLIST.md for the canonical list.
- HSM trustee ceremony. CloudHSM / YubiHSM provisioning for the m-of-3 BLS-threshold trustee set + quarterly rotation runbook execution.
- Sub-400 ms p99 block-time witness. Documented healing target. Approach-4 cleartext-Phase-3 routing and Approach-5 validator-set-scoped encryption land;
cleartext_phase3.rs::SUB_400_MS_TARGET_MS = 400.0; full N=49 / 500 tx p99 witness pending the operator-sidemulti-node-fullCI dispatch. - External A4 (security) and A5 (economic) audits. External security audit scope at
docs/security/AUDIT_SCOPE.md; economic audit covers insurance-fund parameters, clearinghouse waterfall, and CPCAM solver bounds. - Genesis ceremony seal.
tools/genesis-builder seal+tools/genesis_provision.sh --sealrequire coordinator + validator-aggregate-BLS signatures; final ceremony bundle is operator-side. - Cross-repo Mass live smoke. Mass-issued composite-signed
MassClaimAttestationbinds to a Moxie-side typed Claim; public receipts must showclaim_attestation_appliedandclaim_payoff_settled, then the outcome lands in Mass corpus and hash-chains into F21. Moxie-side admission and 10/10 bridge sites are wired; FIPS-compatible Mass signing and live corpus/audit witnesses remain. Stub-mode CI gate runs on every push. - FIPS-206 final / epoch activation. Production FIPS-206 publication, dependency upgrade, and cryptographic-epoch activation through
NativeTx::CryptoSuiteUpgrade. - Real-runtime Kani witness collection. Multi-minute operator-side closure for
formal-cpcam-n-claim; the harness bodies are committed but the real-runtime CI invocation runs only on the nightlykani-full-nightlyworkflow.
# From docs/architecture/CLAIMGRAPH-AOT-SUPREMUM.md §Control-Plane Rule:
#
# Built: AOT + TerminalKernel + TemplatePack/ProductLegalProfile
# registries + commitment-style ObligationGraph + first typed
# ClaimProgram/ClaimGraph compiler vertical.
#
# Open: terminal SDK/API resources, recognized reliance instruments,
# formal terminal fixtures, broader product-family compiler
# coverage.
#
# Forbidden: saying ClaimGraph is the terminal consensus primitive, or
# saying a product is "contract compiled" without typed graph
# fixtures and a deterministic lowering witness for that
# product family.