1use serde::{Deserialize, Serialize};
9
10pub mod platform;
11
12pub const CONTRACT_MAJOR: u16 = 1;
13pub const CONTRACT_VERSION: &str = "1.1";
14pub const DEFAULT_MAXIMUM_TOLERANCE_BPS: u16 = 0;
17pub const DEFAULT_SLIPPAGE_BPS: u16 = DEFAULT_MAXIMUM_TOLERANCE_BPS;
19
20#[cfg(any(test, feature = "fixtures"))]
25#[doc(hidden)]
26pub mod contract_fixtures {
27 pub const ACTION_GRAPH: &str = include_str!("../fixtures/v1/action-graph.json");
28 pub const CAPABILITIES: &str = include_str!("../fixtures/v1/capabilities.json");
29 pub const EXECUTION_CHALLENGE: &str = include_str!("../fixtures/v1/execution-challenge.json");
30 pub const EXECUTION_PREPARE: &str = include_str!("../fixtures/v1/execution-prepare.json");
31 pub const EXECUTION_SUBMIT: &str = include_str!("../fixtures/v1/execution-submit.json");
32 pub const MARKETS: &str = include_str!("../fixtures/v1/markets.json");
33 pub const QUOTE: &str = include_str!("../fixtures/v1/quote.json");
34}
35
36pub const ACTION_GRAPH_VERSION: &str = "1.0";
37
38#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
39#[serde(rename_all = "snake_case")]
40pub enum ActionNodeKind {
41 Discovery,
42 Read,
43 Prepare,
44 ExternalSignature,
45 Submit,
46 Receipt,
47}
48
49#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
50#[serde(deny_unknown_fields)]
51pub struct ActionAuthorityModel {
52 pub permission_source: String,
54 pub signing_location: String,
56 pub accepts_private_keys: bool,
58}
59
60#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
61#[serde(deny_unknown_fields)]
62pub struct ActionOperation {
63 pub method: String,
64 pub path: String,
65 #[serde(skip_serializing_if = "Option::is_none")]
66 pub mcp_tool: Option<String>,
67}
68
69#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
70#[serde(deny_unknown_fields)]
71pub struct ActionNode {
72 pub id: String,
73 pub kind: ActionNodeKind,
74 pub summary: String,
75 pub required_capabilities: Vec<String>,
76 pub available: bool,
78 #[serde(skip_serializing_if = "Option::is_none")]
79 pub operation: Option<ActionOperation>,
80}
81
82#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
83#[serde(deny_unknown_fields)]
84pub struct ActionEdge {
85 pub from: String,
86 pub to: String,
87 pub condition: String,
88}
89
90#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
91#[serde(deny_unknown_fields)]
92pub struct ActionGraph {
93 pub schema_version: u16,
94 pub graph_version: String,
95 pub contract_version: String,
96 pub entry_node: String,
97 pub authority: ActionAuthorityModel,
98 pub nodes: Vec<ActionNode>,
99 pub edges: Vec<ActionEdge>,
100}
101
102#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
103#[serde(rename_all = "snake_case")]
104pub enum QuoteSide {
105 Buy,
106 Sell,
107}
108
109#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
110#[serde(deny_unknown_fields)]
111pub struct QuoteRequest {
112 pub market_id: String,
113 pub side: QuoteSide,
114 #[serde(default, skip_serializing_if = "Option::is_none")]
118 pub amount_in_atoms: Option<String>,
119 #[serde(default, skip_serializing_if = "Option::is_none")]
126 pub amount_out_atoms: Option<String>,
127 #[serde(alias = "slippage_bps")]
133 pub maximum_tolerance_bps: u16,
134}
135
136#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
137#[serde(deny_unknown_fields)]
138pub struct QuoteResponse {
139 pub schema_version: u16,
140 pub contract_version: String,
141 pub quote_id: String,
144 pub server_time_ms: u64,
145 pub expires_at_ms: u64,
146 pub market_id: String,
147 pub side: QuoteSide,
148 pub amount_in_atoms: String,
149 pub amount_in_consumed_atoms: String,
151 pub amount_out_atoms: String,
154 pub minimum_output_atoms: String,
158 pub input_fee_atoms: String,
161 pub output_fee_atoms: String,
164 pub maximum_tolerance_bps: u16,
168 pub reference_price: String,
174 pub price_impact_pct: String,
175 pub provider: String,
176}
177
178#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
182#[serde(deny_unknown_fields)]
183pub struct ExecutionChallengeRequest {
184 pub quote_id: String,
185 pub owner_wallet: String,
186 pub session_public_key: String,
187 #[serde(default, skip_serializing_if = "Option::is_none")]
192 pub account_sequence: Option<String>,
193}
194
195#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
196#[serde(deny_unknown_fields)]
197pub struct ExecutionChallengeResponse {
198 pub schema_version: u16,
199 pub contract_version: String,
200 pub challenge_id: String,
201 pub quote_id: String,
202 pub market_id: String,
203 pub side: QuoteSide,
204 pub amount_in_atoms: String,
205 pub minimum_output_atoms: String,
207 pub authorization_payload_base64: String,
209 pub server_time_ms: u64,
210 pub expires_at_ms: u64,
211}
212
213#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
215#[serde(deny_unknown_fields)]
216pub struct ExecutionPrepareAuthorization {
217 pub challenge_id: String,
218 pub authorization_signature: String,
220}
221
222#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
227#[serde(untagged)]
228pub enum ExecutionPrepareRequest {
229 Authorized(ExecutionPrepareAuthorization),
230 Direct(ExecutionChallengeRequest),
231}
232
233#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
234#[serde(deny_unknown_fields)]
235pub struct ExecutionPrepareResponse {
236 pub schema_version: u16,
237 pub contract_version: String,
238 pub execution_id: String,
239 pub quote_id: String,
240 pub market_id: String,
241 pub side: QuoteSide,
242 pub amount_in_atoms: String,
243 pub minimum_output_atoms: String,
246 pub transaction_base64: String,
249 pub recent_blockhash: String,
250 pub last_valid_block_height: u64,
251 pub expires_at_ms: u64,
252}
253
254#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
255#[serde(deny_unknown_fields)]
256pub struct ExecutionSubmitRequest {
257 pub execution_id: String,
258 pub signed_transaction_base64: String,
259 pub idempotency_key: String,
262}
263
264#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
265#[serde(deny_unknown_fields)]
266pub struct ExecutionSubmitResponse {
267 pub schema_version: u16,
268 pub contract_version: String,
269 pub execution_id: String,
270 pub signature: String,
271 pub status: ExecutionStatus,
272}
273
274#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
275#[serde(rename_all = "snake_case")]
276pub enum ExecutionStatus {
277 Submitted,
278}
279
280#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
281#[serde(deny_unknown_fields)]
282pub struct Market {
283 pub base: String,
284 pub quote: String,
285 pub market_pda: Option<String>,
286 pub label: String,
287 pub ready: bool,
291 pub base_decimals: u8,
292 pub quote_decimals: u8,
293 pub quote_path: Option<String>,
296}
297
298#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
299#[serde(deny_unknown_fields)]
300pub struct MarketsResponse {
301 pub schema_version: u16,
302 pub contract_version: String,
303 pub markets: Vec<Market>,
304}
305
306impl MarketsResponse {
307 pub fn new(markets: Vec<Market>) -> Self {
308 Self {
309 schema_version: CONTRACT_MAJOR,
310 contract_version: CONTRACT_VERSION.to_owned(),
311 markets,
312 }
313 }
314}
315
316#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
317#[serde(deny_unknown_fields)]
318pub struct ErrorDetail {
319 pub code: String,
320 pub message: String,
321 pub retryable: bool,
322}
323
324#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
325#[serde(deny_unknown_fields)]
326pub struct ErrorResponse {
327 pub schema_version: u16,
328 pub contract_version: String,
329 pub error: ErrorDetail,
330}
331
332impl ErrorResponse {
333 pub fn new(code: impl Into<String>, message: impl Into<String>, retryable: bool) -> Self {
334 Self {
335 schema_version: CONTRACT_MAJOR,
336 contract_version: CONTRACT_VERSION.to_owned(),
337 error: ErrorDetail {
338 code: code.into(),
339 message: message.into(),
340 retryable,
341 },
342 }
343 }
344}
345
346#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
347#[serde(rename_all = "snake_case")]
348pub enum CapabilityStability {
349 Internal,
350 Beta,
351 Stable,
352}
353
354#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
355#[serde(rename_all = "snake_case")]
356pub enum CapabilityRisk {
357 Read,
358 Prepare,
359 Submit,
360 Destructive,
361}
362
363#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
364#[serde(rename_all = "snake_case")]
365pub enum McpExposure {
366 None,
367 Read,
368 Prepare,
369 Submit,
370}
371
372#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
373#[serde(deny_unknown_fields)]
374pub struct CapabilityDescriptor {
375 pub id: String,
376 pub introduced_in: String,
377 pub stability: CapabilityStability,
378 pub required_scope: String,
379 pub risk: CapabilityRisk,
380 pub default_enabled: bool,
381 pub public_sdk: bool,
382 pub mcp_exposure: McpExposure,
383}
384
385#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
386#[serde(deny_unknown_fields)]
387pub struct CapabilityCatalog {
388 pub schema_version: u16,
389 pub contract_version: String,
390 pub capabilities: Vec<CapabilityDescriptor>,
391}
392
393impl CapabilityCatalog {
394 pub fn foundation() -> Self {
395 use CapabilityRisk::{Prepare, Read, Submit};
396 use CapabilityStability::{Beta, Stable};
397 use McpExposure::{
398 None as McpNone, Prepare as McpPrepare, Read as McpRead, Submit as McpSubmit,
399 };
400
401 let capability = |id: &str,
402 introduced_in: &str,
403 stability,
404 scope: &str,
405 risk,
406 default_enabled,
407 public_sdk,
408 mcp_exposure| {
409 CapabilityDescriptor {
410 id: id.to_owned(),
411 introduced_in: introduced_in.to_owned(),
412 stability,
413 required_scope: scope.to_owned(),
414 risk,
415 default_enabled,
416 public_sdk,
417 mcp_exposure,
418 }
419 };
420
421 Self {
422 schema_version: CONTRACT_MAJOR,
423 contract_version: CONTRACT_VERSION.to_owned(),
424 capabilities: vec![
425 capability(
426 "markets.read",
427 "1.0",
428 Stable,
429 "market:read",
430 Read,
431 true,
432 true,
433 McpRead,
434 ),
435 capability(
436 "books.read",
437 "1.1",
438 Beta,
439 "market:read",
440 Read,
441 true,
442 true,
443 McpNone,
444 ),
445 capability(
446 "quotes.read",
447 "1.0",
448 Beta,
449 "market:read",
450 Read,
451 true,
452 true,
453 McpRead,
454 ),
455 capability(
456 "account.read",
457 "1.1",
458 Beta,
459 "account:read",
460 Read,
461 true,
462 true,
463 McpNone,
464 ),
465 capability(
466 "trade.prepare",
467 "1.1",
468 Beta,
469 "trade:prepare",
470 Prepare,
471 true,
472 true,
473 McpPrepare,
474 ),
475 capability(
476 "trade.submit",
477 "1.1",
478 Beta,
479 "trade:submit",
480 Submit,
481 true,
482 true,
483 McpSubmit,
484 ),
485 capability(
486 "orders.prepare",
487 "1.1",
488 Beta,
489 "orders:prepare",
490 Prepare,
491 false,
492 true,
493 McpPrepare,
494 ),
495 capability(
496 "orders.submit",
497 "1.1",
498 Beta,
499 "orders:submit",
500 Submit,
501 false,
502 true,
503 McpSubmit,
504 ),
505 capability(
506 "mm.strand.manage",
507 "1.1",
508 Beta,
509 "mm:write",
510 Submit,
511 false,
512 true,
513 McpSubmit,
514 ),
515 capability(
516 "mm.current.manage",
517 "1.1",
518 Beta,
519 "mm:write",
520 Submit,
521 false,
522 true,
523 McpSubmit,
524 ),
525 ],
526 }
527 }
528}
529
530impl ActionGraph {
531 pub fn for_catalog(catalog: &CapabilityCatalog) -> Self {
535 let enabled = |required: &[&str]| {
536 required.iter().all(|id| {
537 catalog.capabilities.iter().any(|capability| {
538 capability.id == *id && capability.default_enabled && capability.public_sdk
539 })
540 })
541 };
542 let operation = |method: &str, path: &str, mcp_tool: Option<&str>| ActionOperation {
543 method: method.to_owned(),
544 path: path.to_owned(),
545 mcp_tool: mcp_tool.map(str::to_owned),
546 };
547 let node = |id: &str,
548 kind,
549 summary: &str,
550 required: &[&str],
551 operation: Option<ActionOperation>| ActionNode {
552 id: id.to_owned(),
553 kind,
554 summary: summary.to_owned(),
555 required_capabilities: required.iter().map(|value| (*value).to_owned()).collect(),
556 available: operation.is_none() || enabled(required),
557 operation,
558 };
559 let edge = |from: &str, to: &str, condition: &str| ActionEdge {
560 from: from.to_owned(),
561 to: to.to_owned(),
562 condition: condition.to_owned(),
563 };
564
565 Self {
566 schema_version: CONTRACT_MAJOR,
567 graph_version: ACTION_GRAPH_VERSION.to_owned(),
568 contract_version: CONTRACT_VERSION.to_owned(),
569 entry_node: "discover_capabilities".to_owned(),
570 authority: ActionAuthorityModel {
571 permission_source: "external_agent_owner".to_owned(),
572 signing_location: "external".to_owned(),
573 accepts_private_keys: false,
574 },
575 nodes: vec![
576 node(
577 "discover_capabilities",
578 ActionNodeKind::Discovery,
579 "Read the live capabilities that currently expose Strata operations.",
580 &[],
581 Some(operation("GET", "/sonar/capabilities", Some("strata_capabilities"))),
582 ),
583 node(
584 "discover_markets",
585 ActionNodeKind::Discovery,
586 "Discover ready markets, token decimals, and public operation paths.",
587 &["markets.read"],
588 Some(operation("GET", "/sonar/markets", Some("strata_markets"))),
589 ),
590 node(
591 "discover_action_graph",
592 ActionNodeKind::Discovery,
593 "Read the executable topology, live node availability, external signing steps, and transition conditions.",
594 &[],
595 Some(operation("GET", "/sonar/action-graph", Some("strata_action_graph"))),
596 ),
597 node(
598 "discover_platform_capabilities",
599 ActionNodeKind::Discovery,
600 "Read the versioned capabilities available through the official SDK.",
601 &[],
602 Some(operation("GET", "/v2/capabilities", None)),
603 ),
604 node(
605 "discover_platform_markets",
606 ActionNodeKind::Discovery,
607 "Discover opaque market IDs and current market status.",
608 &["markets.read"],
609 Some(operation("GET", "/v2/markets", None)),
610 ),
611 node(
612 "read_book",
613 ActionNodeKind::Read,
614 "Read a sequenced Strata book snapshot.",
615 &["books.read"],
616 Some(operation("GET", "/v2/markets/{market_id}/book", None)),
617 ),
618 node(
619 "read_market_status",
620 ActionNodeKind::Read,
621 "Read tick size, the smallest valid base-atom size, and current market status.",
622 &["books.read"],
623 Some(operation("GET", "/v2/markets/{market_id}/status", None)),
624 ),
625 node(
626 "read_best_bid_ask",
627 ActionNodeKind::Read,
628 "Read the current best bid and ask.",
629 &["books.read"],
630 Some(operation("GET", "/v2/markets/{market_id}/bbo", None)),
631 ),
632 node(
633 "read_fees",
634 ActionNodeKind::Read,
635 "Read the market fee schedule.",
636 &["books.read"],
637 Some(operation("GET", "/v2/markets/{market_id}/fees", None)),
638 ),
639 node(
640 "read_trades",
641 ActionNodeKind::Read,
642 "Read recent anonymized trades.",
643 &["books.read"],
644 Some(operation("GET", "/v2/markets/{market_id}/trades", None)),
645 ),
646 node(
647 "stream_market",
648 ActionNodeKind::Read,
649 "Subscribe to book changes, trades, and heartbeats with automatic recovery.",
650 &["books.read"],
651 Some(operation("WEBSOCKET", "/v2/markets/{market_id}/stream", None)),
652 ),
653 node(
654 "authorize_account_read",
655 ActionNodeKind::ExternalSignature,
656 "The agent owner's configured signer authorizes the exact account request or stream challenge.",
657 &[],
658 None,
659 ),
660 node(
661 "read_account",
662 ActionNodeKind::Read,
663 "Read the owner's sanitized open orders and fills for a Strata market.",
664 &["account.read"],
665 Some(operation(
666 "GET",
667 "/v2/markets/{market_id}/account/{wallet_address}",
668 None,
669 )),
670 ),
671 node(
672 "stream_account",
673 ActionNodeKind::Read,
674 "Subscribe to signed, sequenced order and fill state for the owner.",
675 &["account.read"],
676 Some(operation(
677 "WEBSOCKET",
678 "/v2/markets/{market_id}/account/{wallet_address}/stream",
679 None,
680 )),
681 ),
682 node(
683 "request_quote",
684 ActionNodeKind::Read,
685 "Request economics bound to a market, side, exact input atoms, and tolerance.",
686 &["quotes.read"],
687 Some(operation(
688 "POST",
689 "/sonar/markets/{market}/quote",
690 Some("strata_quote"),
691 )),
692 ),
693 node(
694 "request_execution_challenge",
695 ActionNodeKind::Prepare,
696 "Request canonical authorization bytes for an unexpired quote and external signer.",
697 &["trade.prepare"],
698 Some(operation(
699 "POST",
700 "/sonar/markets/{market}/execution/challenge",
701 Some("strata_execution_challenge"),
702 )),
703 ),
704 node(
705 "sign_authorization",
706 ActionNodeKind::ExternalSignature,
707 "The agent owner's configured signer signs the returned authorization bytes externally.",
708 &[],
709 None,
710 ),
711 node(
712 "prepare_execution",
713 ActionNodeKind::Prepare,
714 "Exchange the authorization signature for a quote-bound partially signed transaction.",
715 &["trade.prepare"],
716 Some(operation(
717 "POST",
718 "/sonar/markets/{market}/execution/prepare",
719 Some("strata_execution_prepare"),
720 )),
721 ),
722 node(
723 "sign_transaction",
724 ActionNodeKind::ExternalSignature,
725 "The external signer verifies and fills its signature slot without sending key material to Strata.",
726 &[],
727 None,
728 ),
729 node(
730 "submit_execution",
731 ActionNodeKind::Submit,
732 "Submit the signed transaction with an idempotency key.",
733 &["trade.submit"],
734 Some(operation(
735 "POST",
736 "/sonar/markets/{market}/execution/submit",
737 Some("strata_execution_submit"),
738 )),
739 ),
740 node(
741 "receive_receipt",
742 ActionNodeKind::Receipt,
743 "Receive the execution ID, Solana signature, and submitted status.",
744 &[],
745 None,
746 ),
747 node(
748 "request_order_challenge",
749 ActionNodeKind::Prepare,
750 "Bind a product-level place, cancel, bounded cancel-all, atomic replace, or atomic batch operation to canonical authorization bytes.",
751 &["orders.prepare"],
752 Some(operation(
753 "POST",
754 "/v2/markets/{market_id}/orders/challenge",
755 Some("strata_order_challenge"),
756 )),
757 ),
758 node(
759 "sign_order_authorization",
760 ActionNodeKind::ExternalSignature,
761 "The agent owner's configured session signer verifies the exact order set and signs externally.",
762 &[],
763 None,
764 ),
765 node(
766 "prepare_order_control",
767 ActionNodeKind::Prepare,
768 "Exchange the order authorization signature for a partially signed transaction.",
769 &["orders.prepare"],
770 Some(operation(
771 "POST",
772 "/v2/markets/{market_id}/orders/prepare",
773 Some("strata_order_prepare"),
774 )),
775 ),
776 node(
777 "sign_order_transaction",
778 ActionNodeKind::ExternalSignature,
779 "The external session signer verifies and fills only its transaction signature slot.",
780 &[],
781 None,
782 ),
783 node(
784 "submit_order_control",
785 ActionNodeKind::Submit,
786 "Submit the unchanged signed order transaction with an idempotency key.",
787 &["orders.submit"],
788 Some(operation(
789 "POST",
790 "/v2/markets/{market_id}/orders/submit",
791 Some("strata_order_submit"),
792 )),
793 ),
794 node(
795 "receive_order_receipt",
796 ActionNodeKind::Receipt,
797 "Receive the opaque order IDs, transaction signature, and submitted status.",
798 &[],
799 None,
800 ),
801 node(
802 "open_order_command_stream",
803 ActionNodeKind::Prepare,
804 "Authenticate one persistent sequenced order channel for low-latency commands, explicit self-trade policy, and pushed confirmation.",
805 &["orders.prepare", "orders.submit"],
806 Some(operation(
807 "WEBSOCKET",
808 "/v2/markets/{market_id}/orders/stream",
809 None,
810 )),
811 ),
812 node(
813 "maintain_dead_man",
814 ActionNodeKind::Submit,
815 "Arm and heartbeat an exact pre-signed cancel-all that executes if the agent stops responding.",
816 &["orders.prepare", "orders.submit"],
817 Some(operation(
818 "WEBSOCKET",
819 "/v2/markets/{market_id}/orders/stream",
820 None,
821 )),
822 ),
823 node(
824 "certify_order_command_slo",
825 ActionNodeKind::Read,
826 "Measure authenticated command latency, concurrency, sequence integrity, and error rate without submitting a trade.",
827 &["orders.prepare", "orders.submit"],
828 Some(operation(
829 "WEBSOCKET",
830 "/v2/markets/{market_id}/orders/stream",
831 None,
832 )),
833 ),
834 node(
835 "recover_order_status",
836 ActionNodeKind::Read,
837 "Recover durable submitting, submitted, or failed status after a timeout or restart.",
838 &["orders.submit"],
839 Some(operation(
840 "POST",
841 "/v2/markets/{market_id}/orders/status",
842 Some("strata_order_status"),
843 )),
844 ),
845 ],
846 edges: vec![
847 edge("discover_capabilities", "discover_action_graph", "the returned contract version is supported"),
848 edge("discover_action_graph", "discover_markets", "markets.read is enabled"),
849 edge("discover_action_graph", "discover_platform_capabilities", "the versioned SDK contract is supported"),
850 edge("discover_platform_capabilities", "discover_platform_markets", "markets.read is enabled"),
851 edge("discover_platform_markets", "read_book", "books.read is enabled and the market is active"),
852 edge("discover_platform_markets", "read_market_status", "books.read is enabled"),
853 edge("discover_platform_markets", "read_best_bid_ask", "books.read is enabled"),
854 edge("discover_platform_markets", "read_fees", "books.read is enabled"),
855 edge("discover_platform_markets", "read_trades", "books.read is enabled"),
856 edge("read_book", "stream_market", "books.read is enabled and the snapshot sequence is accepted"),
857 edge("discover_platform_markets", "authorize_account_read", "account.read is enabled and the owner-configured signer is available"),
858 edge("authorize_account_read", "read_account", "the signature binds the wallet, market, request time, and fill limit"),
859 edge("read_account", "stream_account", "the stream challenge is signed by the same owner-configured signer"),
860 edge("discover_markets", "request_quote", "quotes.read is enabled and the market is ready"),
861 edge("request_quote", "request_execution_challenge", "trade.prepare is enabled and the quote is unexpired"),
862 edge("request_execution_challenge", "sign_authorization", "the challenge bindings match the quote and signer"),
863 edge("sign_authorization", "prepare_execution", "a valid external authorization signature is available"),
864 edge("prepare_execution", "sign_transaction", "the prepared transaction preserves the signed bindings"),
865 edge("sign_transaction", "submit_execution", "trade.submit is enabled and the signed transaction is unmodified"),
866 edge("submit_execution", "receive_receipt", "the execution ID and idempotency key match"),
867 edge("discover_platform_markets", "open_order_command_stream", "orders.prepare and orders.submit advertise websocket transport and the owner-configured session signer is available"),
868 edge("open_order_command_stream", "request_order_challenge", "signed socket authentication succeeds and an explicit self-trade prevention policy is selected"),
869 edge("open_order_command_stream", "maintain_dead_man", "the exact cancel-all authorization and transaction are externally verified and signed"),
870 edge("open_order_command_stream", "certify_order_command_slo", "a release or recurring production load certificate is required"),
871 edge("discover_platform_markets", "request_order_challenge", "orders.prepare is enabled and the market accepts order control"),
872 edge("request_order_challenge", "sign_order_authorization", "the action and exact opaque order set match owner intent"),
873 edge("sign_order_authorization", "prepare_order_control", "a valid external authorization signature is available"),
874 edge("prepare_order_control", "sign_order_transaction", "the prepared transaction preserves the signed order bindings"),
875 edge("sign_order_transaction", "submit_order_control", "orders.submit is enabled and the signed transaction is unmodified"),
876 edge("submit_order_control", "receive_order_receipt", "the control ID and idempotency key match"),
877 edge("submit_order_control", "recover_order_status", "the submission result is ambiguous or either process restarted"),
878 edge("submit_order_control", "maintain_dead_man", "the agent has resting exposure that must fail closed on disconnect"),
879 edge("recover_order_status", "receive_order_receipt", "durable status is submitted"),
880 ],
881 }
882 }
883}
884
885#[cfg(test)]
886mod tests {
887 use super::*;
888
889 #[test]
890 fn public_quote_field_set_is_sealed() {
891 let quote: QuoteResponse = serde_json::from_str(contract_fixtures::QUOTE).unwrap();
892 let value = serde_json::to_value(quote).unwrap();
893 let object = value.as_object().unwrap();
894 let mut actual = object.keys().map(String::as_str).collect::<Vec<_>>();
895 actual.sort_unstable();
896 let mut expected = vec![
897 "amount_in_atoms",
898 "amount_in_consumed_atoms",
899 "amount_out_atoms",
900 "contract_version",
901 "expires_at_ms",
902 "input_fee_atoms",
903 "market_id",
904 "maximum_tolerance_bps",
905 "minimum_output_atoms",
906 "output_fee_atoms",
907 "price_impact_pct",
908 "provider",
909 "quote_id",
910 "reference_price",
911 "schema_version",
912 "server_time_ms",
913 "side",
914 ];
915 expected.sort_unstable();
916 assert_eq!(actual, expected, "public quote fields must remain sealed");
917 assert_eq!(object["amount_out_atoms"], "1990000");
918 assert_eq!(object["minimum_output_atoms"], "1980050");
919 assert_eq!(object["maximum_tolerance_bps"], 50);
920 assert_eq!(object["provider"], "Sonar");
921
922 let legacy: QuoteRequest = serde_json::from_value(serde_json::json!({
925 "market_id": "11111111111111111111111111111111",
926 "side": "sell",
927 "amount_in_atoms": "10000000",
928 "slippage_bps": 25
929 }))
930 .unwrap();
931 assert_eq!(legacy.maximum_tolerance_bps, 25);
932 assert!(serde_json::to_string(&legacy)
933 .unwrap()
934 .contains("\"maximum_tolerance_bps\":25"));
935 }
936
937 #[test]
938 fn reviewed_action_capabilities_are_public_and_typed() {
939 let catalog = CapabilityCatalog::foundation();
940 let prepare = catalog
941 .capabilities
942 .iter()
943 .find(|item| item.id == "trade.prepare")
944 .unwrap();
945 let submit = catalog
946 .capabilities
947 .iter()
948 .find(|item| item.id == "trade.submit")
949 .unwrap();
950 assert!(prepare.default_enabled && prepare.public_sdk);
951 assert_eq!(prepare.risk, CapabilityRisk::Prepare);
952 assert_eq!(prepare.mcp_exposure, McpExposure::Prepare);
953 assert!(submit.default_enabled && submit.public_sdk);
954 assert_eq!(submit.risk, CapabilityRisk::Submit);
955 assert_eq!(submit.mcp_exposure, McpExposure::Submit);
956 }
957
958 #[test]
959 fn shared_v1_fixtures_decode_strictly() {
960 let quote: QuoteResponse = serde_json::from_str(contract_fixtures::QUOTE).unwrap();
961 let markets: MarketsResponse = serde_json::from_str(contract_fixtures::MARKETS).unwrap();
962 let capabilities: CapabilityCatalog =
963 serde_json::from_str(contract_fixtures::CAPABILITIES).unwrap();
964 let action_graph: ActionGraph =
965 serde_json::from_str(contract_fixtures::ACTION_GRAPH).unwrap();
966
967 assert_eq!(quote.contract_version, CONTRACT_VERSION);
968 assert_eq!(markets.contract_version, CONTRACT_VERSION);
969 assert_eq!(capabilities, CapabilityCatalog::foundation());
970 assert_eq!(action_graph, ActionGraph::for_catalog(&capabilities));
971 }
972
973 #[test]
974 fn strict_contract_rejects_unreviewed_quote_fields() {
975 let mut value: serde_json::Value = serde_json::from_str(contract_fixtures::QUOTE).unwrap();
976 value
977 .as_object_mut()
978 .unwrap()
979 .insert("unexpected_field".to_owned(), serde_json::json!("hidden"));
980
981 assert!(serde_json::from_value::<QuoteResponse>(value).is_err());
982 }
983
984 #[test]
985 fn execution_contract_exposes_only_minimum_output_protection() {
986 let challenge: ExecutionChallengeResponse =
987 serde_json::from_str(contract_fixtures::EXECUTION_CHALLENGE).unwrap();
988 let prepared: ExecutionPrepareResponse =
989 serde_json::from_str(contract_fixtures::EXECUTION_PREPARE).unwrap();
990 let submitted: ExecutionSubmitResponse =
991 serde_json::from_str(contract_fixtures::EXECUTION_SUBMIT).unwrap();
992
993 assert_eq!(
994 challenge.minimum_output_atoms,
995 prepared.minimum_output_atoms
996 );
997 assert_eq!(challenge.quote_id, prepared.quote_id);
998 assert_eq!(challenge.market_id, prepared.market_id);
999 assert_eq!(submitted.execution_id, prepared.execution_id);
1000
1001 for fixture in [
1002 contract_fixtures::EXECUTION_CHALLENGE,
1003 contract_fixtures::EXECUTION_PREPARE,
1004 contract_fixtures::EXECUTION_SUBMIT,
1005 ] {
1006 let value: serde_json::Value = serde_json::from_str(fixture).unwrap();
1007 let keys = value.as_object().unwrap().keys().collect::<Vec<_>>();
1008 for forbidden in [
1009 "route",
1010 "venue",
1011 "layer",
1012 "plan",
1013 "collar",
1014 "limit_price",
1015 "internal",
1016 "l3",
1017 "footprint",
1018 ] {
1019 assert!(
1020 keys.iter().all(|key| !key.contains(forbidden)),
1021 "execution contract exposed forbidden field containing {forbidden}"
1022 );
1023 }
1024 }
1025 }
1026}