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 ],
506 }
507 }
508}
509
510impl ActionGraph {
511 pub fn for_catalog(catalog: &CapabilityCatalog) -> Self {
515 let enabled = |required: &[&str]| {
516 required.iter().all(|id| {
517 catalog.capabilities.iter().any(|capability| {
518 capability.id == *id && capability.default_enabled && capability.public_sdk
519 })
520 })
521 };
522 let operation = |method: &str, path: &str, mcp_tool: Option<&str>| ActionOperation {
523 method: method.to_owned(),
524 path: path.to_owned(),
525 mcp_tool: mcp_tool.map(str::to_owned),
526 };
527 let node = |id: &str,
528 kind,
529 summary: &str,
530 required: &[&str],
531 operation: Option<ActionOperation>| ActionNode {
532 id: id.to_owned(),
533 kind,
534 summary: summary.to_owned(),
535 required_capabilities: required.iter().map(|value| (*value).to_owned()).collect(),
536 available: operation.is_none() || enabled(required),
537 operation,
538 };
539 let edge = |from: &str, to: &str, condition: &str| ActionEdge {
540 from: from.to_owned(),
541 to: to.to_owned(),
542 condition: condition.to_owned(),
543 };
544
545 Self {
546 schema_version: CONTRACT_MAJOR,
547 graph_version: ACTION_GRAPH_VERSION.to_owned(),
548 contract_version: CONTRACT_VERSION.to_owned(),
549 entry_node: "discover_capabilities".to_owned(),
550 authority: ActionAuthorityModel {
551 permission_source: "external_agent_owner".to_owned(),
552 signing_location: "external".to_owned(),
553 accepts_private_keys: false,
554 },
555 nodes: vec![
556 node(
557 "discover_capabilities",
558 ActionNodeKind::Discovery,
559 "Read the live capabilities that currently expose Strata operations.",
560 &[],
561 Some(operation("GET", "/sonar/capabilities", Some("strata_capabilities"))),
562 ),
563 node(
564 "discover_markets",
565 ActionNodeKind::Discovery,
566 "Discover ready markets, token decimals, and public operation paths.",
567 &["markets.read"],
568 Some(operation("GET", "/sonar/markets", Some("strata_markets"))),
569 ),
570 node(
571 "discover_action_graph",
572 ActionNodeKind::Discovery,
573 "Read the executable topology, live node availability, external signing steps, and transition conditions.",
574 &[],
575 Some(operation("GET", "/sonar/action-graph", Some("strata_action_graph"))),
576 ),
577 node(
578 "discover_platform_capabilities",
579 ActionNodeKind::Discovery,
580 "Read the versioned capabilities available through the official SDK.",
581 &[],
582 Some(operation("GET", "/v2/capabilities", None)),
583 ),
584 node(
585 "discover_platform_markets",
586 ActionNodeKind::Discovery,
587 "Discover opaque market IDs and current market status.",
588 &["markets.read"],
589 Some(operation("GET", "/v2/markets", None)),
590 ),
591 node(
592 "read_book",
593 ActionNodeKind::Read,
594 "Read a sequenced Strata book snapshot.",
595 &["books.read"],
596 Some(operation("GET", "/v2/markets/{market_id}/book", None)),
597 ),
598 node(
599 "read_market_status",
600 ActionNodeKind::Read,
601 "Read tick size, minimum order size, and current market status.",
602 &["books.read"],
603 Some(operation("GET", "/v2/markets/{market_id}/status", None)),
604 ),
605 node(
606 "read_best_bid_ask",
607 ActionNodeKind::Read,
608 "Read the current best bid and ask.",
609 &["books.read"],
610 Some(operation("GET", "/v2/markets/{market_id}/bbo", None)),
611 ),
612 node(
613 "read_fees",
614 ActionNodeKind::Read,
615 "Read the market fee schedule.",
616 &["books.read"],
617 Some(operation("GET", "/v2/markets/{market_id}/fees", None)),
618 ),
619 node(
620 "read_trades",
621 ActionNodeKind::Read,
622 "Read recent anonymized trades.",
623 &["books.read"],
624 Some(operation("GET", "/v2/markets/{market_id}/trades", None)),
625 ),
626 node(
627 "stream_market",
628 ActionNodeKind::Read,
629 "Subscribe to book changes, trades, and heartbeats with automatic recovery.",
630 &["books.read"],
631 Some(operation("WEBSOCKET", "/v2/markets/{market_id}/stream", None)),
632 ),
633 node(
634 "authorize_account_read",
635 ActionNodeKind::ExternalSignature,
636 "The agent owner's configured signer authorizes the exact account request or stream challenge.",
637 &[],
638 None,
639 ),
640 node(
641 "read_account",
642 ActionNodeKind::Read,
643 "Read the owner's sanitized open orders and fills for a Strata market.",
644 &["account.read"],
645 Some(operation(
646 "GET",
647 "/v2/markets/{market_id}/account/{wallet_address}",
648 None,
649 )),
650 ),
651 node(
652 "stream_account",
653 ActionNodeKind::Read,
654 "Subscribe to signed, sequenced order and fill state for the owner.",
655 &["account.read"],
656 Some(operation(
657 "WEBSOCKET",
658 "/v2/markets/{market_id}/account/{wallet_address}/stream",
659 None,
660 )),
661 ),
662 node(
663 "request_quote",
664 ActionNodeKind::Read,
665 "Request economics bound to a market, side, exact input atoms, and tolerance.",
666 &["quotes.read"],
667 Some(operation(
668 "POST",
669 "/sonar/markets/{market}/quote",
670 Some("strata_quote"),
671 )),
672 ),
673 node(
674 "request_execution_challenge",
675 ActionNodeKind::Prepare,
676 "Request canonical authorization bytes for an unexpired quote and external signer.",
677 &["trade.prepare"],
678 Some(operation(
679 "POST",
680 "/sonar/markets/{market}/execution/challenge",
681 Some("strata_execution_challenge"),
682 )),
683 ),
684 node(
685 "sign_authorization",
686 ActionNodeKind::ExternalSignature,
687 "The agent owner's configured signer signs the returned authorization bytes externally.",
688 &[],
689 None,
690 ),
691 node(
692 "prepare_execution",
693 ActionNodeKind::Prepare,
694 "Exchange the authorization signature for a quote-bound partially signed transaction.",
695 &["trade.prepare"],
696 Some(operation(
697 "POST",
698 "/sonar/markets/{market}/execution/prepare",
699 Some("strata_execution_prepare"),
700 )),
701 ),
702 node(
703 "sign_transaction",
704 ActionNodeKind::ExternalSignature,
705 "The external signer verifies and fills its signature slot without sending key material to Strata.",
706 &[],
707 None,
708 ),
709 node(
710 "submit_execution",
711 ActionNodeKind::Submit,
712 "Submit the signed transaction with an idempotency key.",
713 &["trade.submit"],
714 Some(operation(
715 "POST",
716 "/sonar/markets/{market}/execution/submit",
717 Some("strata_execution_submit"),
718 )),
719 ),
720 node(
721 "receive_receipt",
722 ActionNodeKind::Receipt,
723 "Receive the execution ID, Solana signature, and submitted status.",
724 &[],
725 None,
726 ),
727 node(
728 "request_order_challenge",
729 ActionNodeKind::Prepare,
730 "Bind a product-level place, cancel, bounded cancel-all, atomic replace, or atomic batch operation to canonical authorization bytes.",
731 &["orders.prepare"],
732 Some(operation(
733 "POST",
734 "/v2/markets/{market_id}/orders/challenge",
735 Some("strata_order_challenge"),
736 )),
737 ),
738 node(
739 "sign_order_authorization",
740 ActionNodeKind::ExternalSignature,
741 "The agent owner's configured session signer verifies the exact order set and signs externally.",
742 &[],
743 None,
744 ),
745 node(
746 "prepare_order_control",
747 ActionNodeKind::Prepare,
748 "Exchange the order authorization signature for a partially signed transaction.",
749 &["orders.prepare"],
750 Some(operation(
751 "POST",
752 "/v2/markets/{market_id}/orders/prepare",
753 Some("strata_order_prepare"),
754 )),
755 ),
756 node(
757 "sign_order_transaction",
758 ActionNodeKind::ExternalSignature,
759 "The external session signer verifies and fills only its transaction signature slot.",
760 &[],
761 None,
762 ),
763 node(
764 "submit_order_control",
765 ActionNodeKind::Submit,
766 "Submit the unchanged signed order transaction with an idempotency key.",
767 &["orders.submit"],
768 Some(operation(
769 "POST",
770 "/v2/markets/{market_id}/orders/submit",
771 Some("strata_order_submit"),
772 )),
773 ),
774 node(
775 "receive_order_receipt",
776 ActionNodeKind::Receipt,
777 "Receive the opaque order IDs, transaction signature, and submitted status.",
778 &[],
779 None,
780 ),
781 node(
782 "open_order_command_stream",
783 ActionNodeKind::Prepare,
784 "Authenticate one persistent sequenced order channel for low-latency commands, explicit self-trade policy, and pushed confirmation.",
785 &["orders.prepare", "orders.submit"],
786 Some(operation(
787 "WEBSOCKET",
788 "/v2/markets/{market_id}/orders/stream",
789 None,
790 )),
791 ),
792 node(
793 "maintain_dead_man",
794 ActionNodeKind::Submit,
795 "Arm and heartbeat an exact pre-signed cancel-all that executes if the agent stops responding.",
796 &["orders.prepare", "orders.submit"],
797 Some(operation(
798 "WEBSOCKET",
799 "/v2/markets/{market_id}/orders/stream",
800 None,
801 )),
802 ),
803 node(
804 "certify_order_command_slo",
805 ActionNodeKind::Read,
806 "Measure authenticated command latency, concurrency, sequence integrity, and error rate without submitting a trade.",
807 &["orders.prepare", "orders.submit"],
808 Some(operation(
809 "WEBSOCKET",
810 "/v2/markets/{market_id}/orders/stream",
811 None,
812 )),
813 ),
814 node(
815 "recover_order_status",
816 ActionNodeKind::Read,
817 "Recover durable submitting, submitted, or failed status after a timeout or restart.",
818 &["orders.submit"],
819 Some(operation(
820 "POST",
821 "/v2/markets/{market_id}/orders/status",
822 Some("strata_order_status"),
823 )),
824 ),
825 ],
826 edges: vec![
827 edge("discover_capabilities", "discover_action_graph", "the returned contract version is supported"),
828 edge("discover_action_graph", "discover_markets", "markets.read is enabled"),
829 edge("discover_action_graph", "discover_platform_capabilities", "the versioned SDK contract is supported"),
830 edge("discover_platform_capabilities", "discover_platform_markets", "markets.read is enabled"),
831 edge("discover_platform_markets", "read_book", "books.read is enabled and the market is active"),
832 edge("discover_platform_markets", "read_market_status", "books.read is enabled"),
833 edge("discover_platform_markets", "read_best_bid_ask", "books.read is enabled"),
834 edge("discover_platform_markets", "read_fees", "books.read is enabled"),
835 edge("discover_platform_markets", "read_trades", "books.read is enabled"),
836 edge("read_book", "stream_market", "books.read is enabled and the snapshot sequence is accepted"),
837 edge("discover_platform_markets", "authorize_account_read", "account.read is enabled and the owner-configured signer is available"),
838 edge("authorize_account_read", "read_account", "the signature binds the wallet, market, request time, and fill limit"),
839 edge("read_account", "stream_account", "the stream challenge is signed by the same owner-configured signer"),
840 edge("discover_markets", "request_quote", "quotes.read is enabled and the market is ready"),
841 edge("request_quote", "request_execution_challenge", "trade.prepare is enabled and the quote is unexpired"),
842 edge("request_execution_challenge", "sign_authorization", "the challenge bindings match the quote and signer"),
843 edge("sign_authorization", "prepare_execution", "a valid external authorization signature is available"),
844 edge("prepare_execution", "sign_transaction", "the prepared transaction preserves the signed bindings"),
845 edge("sign_transaction", "submit_execution", "trade.submit is enabled and the signed transaction is unmodified"),
846 edge("submit_execution", "receive_receipt", "the execution ID and idempotency key match"),
847 edge("discover_platform_markets", "open_order_command_stream", "orders.prepare and orders.submit advertise websocket transport and the owner-configured session signer is available"),
848 edge("open_order_command_stream", "request_order_challenge", "signed socket authentication succeeds and an explicit self-trade prevention policy is selected"),
849 edge("open_order_command_stream", "maintain_dead_man", "the exact cancel-all authorization and transaction are externally verified and signed"),
850 edge("open_order_command_stream", "certify_order_command_slo", "a release or recurring production load certificate is required"),
851 edge("discover_platform_markets", "request_order_challenge", "orders.prepare is enabled and the market accepts order control"),
852 edge("request_order_challenge", "sign_order_authorization", "the action and exact opaque order set match owner intent"),
853 edge("sign_order_authorization", "prepare_order_control", "a valid external authorization signature is available"),
854 edge("prepare_order_control", "sign_order_transaction", "the prepared transaction preserves the signed order bindings"),
855 edge("sign_order_transaction", "submit_order_control", "orders.submit is enabled and the signed transaction is unmodified"),
856 edge("submit_order_control", "receive_order_receipt", "the control ID and idempotency key match"),
857 edge("submit_order_control", "recover_order_status", "the submission result is ambiguous or either process restarted"),
858 edge("submit_order_control", "maintain_dead_man", "the agent has resting exposure that must fail closed on disconnect"),
859 edge("recover_order_status", "receive_order_receipt", "durable status is submitted"),
860 ],
861 }
862 }
863}
864
865#[cfg(test)]
866mod tests {
867 use super::*;
868
869 #[test]
870 fn public_quote_field_set_is_sealed() {
871 let quote: QuoteResponse = serde_json::from_str(contract_fixtures::QUOTE).unwrap();
872 let value = serde_json::to_value(quote).unwrap();
873 let object = value.as_object().unwrap();
874 let mut actual = object.keys().map(String::as_str).collect::<Vec<_>>();
875 actual.sort_unstable();
876 let mut expected = vec![
877 "amount_in_atoms",
878 "amount_in_consumed_atoms",
879 "amount_out_atoms",
880 "contract_version",
881 "expires_at_ms",
882 "input_fee_atoms",
883 "market_id",
884 "maximum_tolerance_bps",
885 "minimum_output_atoms",
886 "output_fee_atoms",
887 "price_impact_pct",
888 "provider",
889 "quote_id",
890 "reference_price",
891 "schema_version",
892 "server_time_ms",
893 "side",
894 ];
895 expected.sort_unstable();
896 assert_eq!(actual, expected, "public quote fields must remain sealed");
897 assert_eq!(object["amount_out_atoms"], "1990000");
898 assert_eq!(object["minimum_output_atoms"], "1980050");
899 assert_eq!(object["maximum_tolerance_bps"], 50);
900 assert_eq!(object["provider"], "Sonar");
901
902 let legacy: QuoteRequest = serde_json::from_value(serde_json::json!({
905 "market_id": "11111111111111111111111111111111",
906 "side": "sell",
907 "amount_in_atoms": "10000000",
908 "slippage_bps": 25
909 }))
910 .unwrap();
911 assert_eq!(legacy.maximum_tolerance_bps, 25);
912 assert!(serde_json::to_string(&legacy)
913 .unwrap()
914 .contains("\"maximum_tolerance_bps\":25"));
915 }
916
917 #[test]
918 fn reviewed_action_capabilities_are_public_and_typed() {
919 let catalog = CapabilityCatalog::foundation();
920 let prepare = catalog
921 .capabilities
922 .iter()
923 .find(|item| item.id == "trade.prepare")
924 .unwrap();
925 let submit = catalog
926 .capabilities
927 .iter()
928 .find(|item| item.id == "trade.submit")
929 .unwrap();
930 assert!(prepare.default_enabled && prepare.public_sdk);
931 assert_eq!(prepare.risk, CapabilityRisk::Prepare);
932 assert_eq!(prepare.mcp_exposure, McpExposure::Prepare);
933 assert!(submit.default_enabled && submit.public_sdk);
934 assert_eq!(submit.risk, CapabilityRisk::Submit);
935 assert_eq!(submit.mcp_exposure, McpExposure::Submit);
936 }
937
938 #[test]
939 fn shared_v1_fixtures_decode_strictly() {
940 let quote: QuoteResponse = serde_json::from_str(contract_fixtures::QUOTE).unwrap();
941 let markets: MarketsResponse = serde_json::from_str(contract_fixtures::MARKETS).unwrap();
942 let capabilities: CapabilityCatalog =
943 serde_json::from_str(contract_fixtures::CAPABILITIES).unwrap();
944 let action_graph: ActionGraph =
945 serde_json::from_str(contract_fixtures::ACTION_GRAPH).unwrap();
946
947 assert_eq!(quote.contract_version, CONTRACT_VERSION);
948 assert_eq!(markets.contract_version, CONTRACT_VERSION);
949 assert_eq!(capabilities, CapabilityCatalog::foundation());
950 assert_eq!(action_graph, ActionGraph::for_catalog(&capabilities));
951 }
952
953 #[test]
954 fn strict_contract_rejects_unreviewed_quote_fields() {
955 let mut value: serde_json::Value = serde_json::from_str(contract_fixtures::QUOTE).unwrap();
956 value
957 .as_object_mut()
958 .unwrap()
959 .insert("unexpected_field".to_owned(), serde_json::json!("hidden"));
960
961 assert!(serde_json::from_value::<QuoteResponse>(value).is_err());
962 }
963
964 #[test]
965 fn execution_contract_exposes_only_minimum_output_protection() {
966 let challenge: ExecutionChallengeResponse =
967 serde_json::from_str(contract_fixtures::EXECUTION_CHALLENGE).unwrap();
968 let prepared: ExecutionPrepareResponse =
969 serde_json::from_str(contract_fixtures::EXECUTION_PREPARE).unwrap();
970 let submitted: ExecutionSubmitResponse =
971 serde_json::from_str(contract_fixtures::EXECUTION_SUBMIT).unwrap();
972
973 assert_eq!(
974 challenge.minimum_output_atoms,
975 prepared.minimum_output_atoms
976 );
977 assert_eq!(challenge.quote_id, prepared.quote_id);
978 assert_eq!(challenge.market_id, prepared.market_id);
979 assert_eq!(submitted.execution_id, prepared.execution_id);
980
981 for fixture in [
982 contract_fixtures::EXECUTION_CHALLENGE,
983 contract_fixtures::EXECUTION_PREPARE,
984 contract_fixtures::EXECUTION_SUBMIT,
985 ] {
986 let value: serde_json::Value = serde_json::from_str(fixture).unwrap();
987 let keys = value.as_object().unwrap().keys().collect::<Vec<_>>();
988 for forbidden in [
989 "route",
990 "venue",
991 "layer",
992 "plan",
993 "collar",
994 "limit_price",
995 "internal",
996 "l3",
997 "footprint",
998 ] {
999 assert!(
1000 keys.iter().all(|key| !key.contains(forbidden)),
1001 "execution contract exposed forbidden field containing {forbidden}"
1002 );
1003 }
1004 }
1005 }
1006}