### Start Intent Relay Service and Submit Intent via HTTP API (Rust) Source: https://context7.com/splashprotocol/splash-offchain-multiplatform/llms.txt This snippet demonstrates how to start the intent relay service and submit an intent using an HTTP POST request. The service forwards authenticated intents to execution engines. It requires a configuration file and accepts hex-encoded intent data, prefix, postfix, signature, and a credential. ```bash cargo run --bin intent-relay --release -- --config-path ./conf.json --log4rs-path ./log4rs.yaml --host 0.0.0.0 --port 8080 ``` ```json { "baseDataPath": "/var/app/index", "endpoints": [ "execution-engine-1:9080", "execution-engine-2:9080", "execution-engine-3:9080" ] } ``` ```http POST /intent/submit Content-Type: application/json { "intent": "a200581c3...", "prefix": "5840f1a2...", "postfix": "584f2b3...", "signature": "5840abc...", "credential": "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff" } ``` ```text Response: HTTP 200 OK The service queues the intent in RocksDB and asynchronously forwards it to configured endpoints ``` -------------------------------- ### Temporal Liquidity Book: Market Matching Example in Rust Source: https://context7.com/splashprotocol/splash-offchain-multiplatform/llms.txt Demonstrates how the Temporal Liquidity Book aggregates liquidity and matches market taker orders against market maker liquidity sources like AMM pools. It defines custom order and pool structs implementing the necessary traits and shows the process of adding liquidity and matching an order. ```rust use bloom_offchain::execution_engine::liquidity_book::core::LiquidityBook; use bloom_offchain::execution_engine::liquidity_book::market_taker::MarketTaker; use bloom_offchain::execution_engine::liquidity_book::market_maker::MarketMaker; use bloom_offchain::execution_engine::liquidity_book::types::{InputAsset, OutputAsset, FeeAsset}; // Define a market taker (order) struct MyOrder { input_amount: u64, min_output: u64, budget: u64, } impl MarketTaker for MyOrder { fn get_input(&self) -> InputAsset { InputAsset::new(self.input_amount) } fn get_budget(&self) -> FeeAsset { FeeAsset::new(self.budget) } } // Define a market maker (AMM pool) struct MyPool { reserve_x: u64, reserve_y: u64, } impl MarketMaker for MyPool { fn get_spot_price(&self, side: Side) -> SpotPrice { // Constant product pricing: p = y/x SpotPrice::from_reserves(self.reserve_x, self.reserve_y) } fn quote(&self, input: InputAsset) -> OutputAsset { // xy = k formula let k = self.reserve_x * self.reserve_y; let new_x = self.reserve_x + input.amount; let new_y = k / new_x; OutputAsset::new(self.reserve_y - new_y) } } // Create liquidity book and add makers let mut book = LiquidityBook::new(); book.insert_maker(MyPool { reserve_x: 1_000_000, reserve_y: 2_000_000 }); book.insert_maker(MyPool { reserve_x: 500_000, reserve_y: 1_100_000 }); // Match order against available liquidity let order = MyOrder { input_amount: 10_000, min_output: 19_000, budget: 2_000 }; let result = book.match_taker(order); match result { Next::Term(terminal) => { println!("Order filled! Output: {}", terminal.accumulated_output); println!("Remaining input: {}", terminal.remaining_input); }, Next::Succ(partial) => { println!("Partial fill, continuing..."); }, } ``` -------------------------------- ### Cardano Mempool Proxy: Configuration Example in JSON Source: https://context7.com/splashprotocol/splash-offchain-multiplatform/llms.txt Provides the configuration structure for the cardano-mempool-proxy, which proxies mempool transactions from a Cardano node. It includes settings for the node connection, transaction limits, and buffer sizes. ```json { "node": { "path": "/data/cardano-node/ipc/node.socket", // Path to node IPC socket "magic": 764824073 // Network magic (preprod: 1, mainnet: 764824073) }, "limits": { "maxPayloadLenBytes": 25000000 // Max transaction size (25MB) }, "txSubmissionBufferSize": 8192 // Buffer size for queuing transactions } ``` -------------------------------- ### Fetch Cardano UTXO by Reference using Explorer API (Rust) Source: https://context7.com/splashprotocol/splash-offchain-multiplatform/llms.txt This example demonstrates how to retrieve a specific unspent transaction output (UTXO) on the Cardano blockchain using its transaction hash and output index. It utilizes the `cardano-explorer` crate, supporting APIs like Blockfrost. The `utxo_by_ref` function takes an `OutputRef` (containing transaction hash and index) and returns the UTXO details if found and unspent. It also shows how to access the UTXO's address, lovelace amount, and check for attached datum or reference scripts. Dependencies include `cardano-explorer`, `spectrum-cardano-lib`, and `cml-crypto`. ```rust use cardano_explorer::{CardanoNetwork, Blockfrost}; use spectrum_cardano_lib::OutputRef; use cml_crypto::TransactionHash; // Initialize Blockfrost client let blockfrost = Blockfrost::new("./blockfrost-project-id.txt").await.unwrap(); // Create output reference let tx_hash = TransactionHash::from_hex( "abc123...def456" ).unwrap(); let output_ref = OutputRef::new(tx_hash, 0); // index 0 // Fetch the UTXO match blockfrost.utxo_by_ref(output_ref).await { Some(utxo) => { println!("Found UTXO at {}#2%", utxo.input.transaction_id.to_hex(), utxo.input.index ); // Access output details let output = &utxo.output; println!("Address: {}", output.address().to_bech32(None).unwrap()); println!("Lovelace: {}", output.amount().coin()); // Check for datum if let Some(datum_option) = output.datum() { println!("Has datum attached"); } // Check for reference script if let Some(script) = output.script_ref() { println!("Has reference script"); } }, None => println!("UTXO not found or already spent"), } ``` -------------------------------- ### Run Splash Intent Relay from Sources Source: https://github.com/splashprotocol/splash-offchain-multiplatform/blob/develop/intent-relay/Readme.md Executes the Splash Intent Relay service from its source code. Requires specifying paths for configuration and logging, along with host and port details. ```shell cargo run --bin intent-relay --release -- --config-path --log4rs-path --host --port ``` -------------------------------- ### Bloom Execution Engine: Partitioning Strategy in Rust Source: https://context7.com/splashprotocol/splash-offchain-multiplatform/llms.txt Illustrates the partitioning strategy for the Bloom Execution Engine, which distributes orders across multiple threads for parallel processing while ensuring consistency. It defines a custom partition key and shows how to assign orders to partitions. ```rust use bloom_offchain::partitioning::{Partitioner, PartitionKey}; use std::collections::HashMap; // Define partition key for your domain #[derive(Hash, Eq, PartialEq, Clone)] enum TradingPair { AdaUsdc, AdaUsdt, UsdcUsdt, } impl PartitionKey for TradingPair { fn partition_id(&self) -> u64 { // Hash to partition ID match self { TradingPair::AdaUsdc => 0, TradingPair::AdaUsdt => 1, TradingPair::UsdcUsdt => 2, } } } // Create partitioner with 4 worker threads let partitioner = Partitioner::new(4); // Distribute orders to partitions let orders = vec![ (TradingPair::AdaUsdc, order1), (TradingPair::AdaUsdt, order2), (TradingPair::AdaUsdc, order3), ]; for (pair, order) in orders { let partition = partitioner.assign(&pair); partition.send(order).await; } // Each partition processes its orders independently // Orders for the same pair are guaranteed to be processed sequentially // Different pairs can be processed in parallel for maximum throughput ``` -------------------------------- ### Build Project with Cargo Source: https://github.com/splashprotocol/splash-offchain-multiplatform/blob/develop/intent-relay/Readme.md Compiles the Splash Intent Relay project in release mode, generating an optimized executable binary. This command is used for production deployments. ```shell cargo build --release ``` -------------------------------- ### Submit Signed Cardano Transaction with Explorer API (Rust) Source: https://context7.com/splashprotocol/splash-offchain-multiplatform/llms.txt This snippet shows how to submit a signed Cardano transaction to the network using the Maestro API via the `cardano-explorer` crate. It also includes functionality to optionally wait for the transaction's confirmation on-chain. The code first initializes a Maestro client, serializes the signed transaction to CBOR, submits it, and then polls for confirmation. It also demonstrates fetching the current chain tip slot number. Dependencies include `cardano-explorer` and `cml-core`. ```rust use cardano_explorer::{ExtendedCardanoNetwork, Maestro}; use cml_chain::transaction::Transaction; use cml_core::serialization::Serialize; // Initialize Maestro client let maestro = Maestro::new("./maestro-api-key.txt", Network::Mainnet).await.unwrap(); // Prepare signed transaction let signed_tx: Transaction = /* ... your transaction ... */; let tx_cbor = signed_tx.to_cbor_bytes(); let tx_hash = signed_tx.body().transaction_hash(); // Submit transaction match maestro.submit_tx(&tx_cbor).await { Ok(_) => { println!("Transaction submitted: {}", tx_hash.to_hex()); // Wait for confirmation (polls every 30 seconds) match maestro.wait_for_transaction_confirmation(tx_hash).await { Ok(_) => println!("Transaction confirmed on-chain"), Err(e) => eprintln!("Confirmation timeout: {}", e), } }, Err(e) => eprintln!("Submission failed: {}", e), } // Check current chain tip let current_slot = maestro.chain_tip_slot_number().await.unwrap(); println!("Current chain slot: {}", current_slot); ``` -------------------------------- ### Query Cardano UTXOs by Address using Explorer APIs (Rust) Source: https://context7.com/splashprotocol/splash-offchain-multiplatform/llms.txt This code fetches unspent transaction outputs (UTXOs) for a given Cardano address. It supports using either Blockfrost or Maestro APIs via the `cardano-explorer` crate. The function `utxos_by_address` takes an address, offset, and limit as input. An alternative method `utxos_by_pay_cred` is provided for querying by payment credential, which is faster for script addresses. Dependencies include `cardano-explorer`, `spectrum-cardano-lib`, and `cml-chain`. ```rust use cardano_explorer::{CardanoNetwork, AnyExplorer, config::ExplorerConfig}; use spectrum_cardano_lib::NetworkId; use cml_chain::address::Address; // Initialize explorer with Maestro let config = ExplorerConfig::MaestroKeyPath("./maestro-api-key.txt".into()); let network_id = NetworkId::mainnet(); let explorer = AnyExplorer::new(&config, network_id).await.unwrap(); // Query UTXOs for an address let address = Address::from_bech32( "addr1q9xyz...abc123" ).unwrap(); let utxos = explorer.utxos_by_address( address, 0, // offset 100 // limit ).await; for utxo in utxos { println!("TxHash: {}, Index: 2%", utxo.input.transaction_id.to_hex(), utxo.input.index ); println!("Value: {} lovelace", utxo.output.amount().coin()); } // Alternative: Query by payment credential (faster for script addresses) use spectrum_cardano_lib::PaymentCredential; let pay_cred = PaymentCredential::from_script_hash(/* script hash */); let script_utxos = explorer.utxos_by_pay_cred(pay_cred, 0, 100).await; ``` -------------------------------- ### Run Tests with Cargo Source: https://github.com/splashprotocol/splash-offchain-multiplatform/blob/develop/intent-relay/Readme.md Executes all unit and integration tests within the Splash Intent Relay project. Ensures the codebase is functioning as expected. ```shell cargo test ``` -------------------------------- ### RocksDB Key Format for Pre-Activated Gauges Source: https://github.com/splashprotocol/splash-offchain-multiplatform/blob/develop/doc/adr/0001-handle-pre-activated-gauges-and-missing-pools-in-lp-indexer.md Defines a new RocksDB key format to temporarily store gauge IDs for pre-activated gauges. This allows the system to track gauges whose activation event is received before the gauge entity is created, ensuring they are processed later. The key format is a concatenation of the string 'pre-activated' and the gauge_id. ```plaintext "pre-activated" || gauge_id ``` -------------------------------- ### Stream Cardano Chain Updates with Chain-Sync Mini-Protocol (Rust) Source: https://context7.com/splashprotocol/splash-offchain-multiplatform/llms.txt This snippet demonstrates how to create an asynchronous stream of Cardano blockchain updates using the chain-sync mini-protocol. It utilizes the `cardano-chain-sync` crate to receive real-time block and transaction data, handling both forward roll events (new blocks) and backward roll events (chain reorganizations). Dependencies include `cardano-chain-sync`, `async-primitives`, and `futures`. ```rust use cardano_chain_sync::{chain_sync_stream, client::ChainSyncClient}; use async_primitives::beacon::Beacon; use futures::StreamExt; // Initialize chain sync client (implementation depends on node connection) let client = ChainSyncClient::new(/* node connection params */); let sync_beacon = Beacon::new(); // Create stream of chain upgrades (new blocks) let mut stream = chain_sync_stream(client, sync_beacon.clone()); // Process blocks as they arrive while let Some(chain_upgrade) = stream.next().await { match chain_upgrade { ChainUpgrade::RollForward(block) => { println!("New block received: slot {}", block.slot); // Process block transactions }, ChainUpgrade::RollBackward(point) => { println!("Chain rollback to: {:?}", point); // Handle chain reorganization } } } // When tip is reached, stream throttles for 1 second before checking again // sync_beacon indicates when initial sync is complete ``` -------------------------------- ### Transaction Reference Inputs Source: https://github.com/splashprotocol/splash-offchain-multiplatform/blob/develop/splash-testing-cardano/tx.txt Defines the reference inputs for a transaction, specifying the transaction ID and index for each referenced input. These are used to access UTXOs without spending them. ```json [ { "transaction_id": "ca99a1010ac6ebcede04007f9713c130281703cbb26f870a3874e85569f0ce3e", "index": "0" }, { "transaction_id": "ca99a1010ac6ebcede04007f9713c130281703cbb26f870a3874e85569f0ce3e", "index": "1" } ] ``` -------------------------------- ### Intent Relay HTTP API Source: https://context7.com/splashprotocol/splash-offchain-multiplatform/llms.txt The Intent Relay HTTP API accepts authenticated intents from clients and forwards them to execution engines via TCP. It acts as middleware between end users and order execution infrastructure. ```APIDOC ## POST /intent/submit ### Description Submits an intent to the intent relay service for processing and forwarding to execution engines. ### Method POST ### Endpoint /intent/submit ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **intent** (string) - Required - Hex-encoded intent CBOR. - **prefix** (string) - Required - Hex-encoded prefix. - **postfix** (string) - Required - Hex-encoded postfix. - **signature** (string) - Required - Hex-encoded signature. - **credential** (string) - Required - 32-byte hex credential. ### Request Example ```json { "intent": "a200581c3...", "prefix": "5840f1a2...", "postfix": "584f2b3...", "signature": "5840abc...", "credential": "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates that the intent has been successfully queued and will be forwarded asynchronously. #### Response Example ```json { "message": "Intent received and queued for processing." } ``` ``` -------------------------------- ### StableSwap Invariant Calculation Source: https://context7.com/splashprotocol/splash-offchain-multiplatform/llms.txt Computes the StableSwap invariant value for n-asset pools using numerical methods. This is essential for pricing and liquidity operations in stablecoin pools. ```APIDOC ## POST /stableswap/invariant/calculate ### Description Calculates the StableSwap invariant for a given set of asset balances, number of assets, and amplification coefficient. ### Method POST ### Endpoint /stableswap/invariant/calculate ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **balances** (array of U512) - Required - Array of current balances for each asset in the pool. - **n_assets** (integer) - Required - The number of assets in the pool. - **ampl_coefficient** (integer) - Required - The amplification factor for the StableSwap curve. ### Request Example ```json { "balances": [ "1000000000000", "1050000000000", "980000000000" ], "n_assets": 3, "ampl_coefficient": 100 } ``` ### Response #### Success Response (200) - **invariant** (string) - The calculated StableSwap invariant value as a U512 string. #### Response Example ```json { "invariant": "3010000000000" } ``` ``` -------------------------------- ### Calculate StableSwap Invariant Value (Rust) Source: https://context7.com/splashprotocol/splash-offchain-multiplatform/llms.txt This Rust code calculates the StableSwap invariant for n-asset pools using numerical methods. It's crucial for pricing and liquidity operations in stablecoin pools. The function takes balances, the number of assets, and an amplification coefficient as input. ```rust use primitive_types::U512; use cardano_offchain_stableswap::stable_swap_invariant::calculate_invariant; // Calculate invariant for a 3-asset stableswap pool let balances = vec![ U512::from(1_000_000_000_000u64), U512::from(1_050_000_000_000u64), U512::from(980_000_000_000u64), ]; let n_assets = 3u32; let ampl_coefficient = 100u32; let invariant = calculate_invariant(&balances, &n_assets, &l_coefficient); // invariant ≈ U512(3_010_000_000_000) // This value is used to determine output amounts for swaps and liquidity operations // Higher amplification makes the pool behave more like a constant-sum (x+y+z=k) // Lower amplification approaches constant-product behavior (x*y*z=k) ``` -------------------------------- ### Witness Set Public Key and Signature Source: https://github.com/splashprotocol/splash-offchain-multiplatform/blob/develop/splash-testing-cardano/tx.txt Contains a public key and its corresponding signature, likely used for transaction authentication. This is a common component in blockchain transaction witness sets. ```json { "vkey": "ed25519_pk1e2g669epef843uedue39dw502mrallw5lp56hqlf23ypq8zgu87qxad9df", "signature": "57a11588e7704ae268a7e54e8ca450d299666ff790c774c9f3a9e4e7934ef56bea8d88979d759897795ded0082dfb4da81c14f0317a99228d4d072c157d2b900" } ``` -------------------------------- ### StableSwap Invariant Error Checking Source: https://context7.com/splashprotocol/splash-offchain-multiplatform/llms.txt Validates that calculated invariant values satisfy the StableSwap equation within acceptable error bounds, and checks if the invariant is at the extremum. ```APIDOC ## POST /stableswap/invariant/check ### Description Validates the StableSwap invariant value against the balances and checks if it represents the correct extremum. ### Method POST ### Endpoint /stableswap/invariant/check ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **balances** (array of U512) - Required - Array of current balances for each asset in the pool. - **n_assets** (integer) - Required - The number of assets in the pool. - **ampl_coefficient** (integer) - Required - The amplification factor for the StableSwap curve. - **invariant** (string) - Required - The StableSwap invariant value to validate (as a U512 string). ### Request Example ```json { "balances": [ "1000000", "1000000" ], "n_assets": 2, "ampl_coefficient": 85, "invariant": "3000000" } ``` ### Response #### Success Response (200) - **error** (string) - The calculated invariant error, a measure of how well the invariant satisfies the equation (as a U512 string). - **is_valid** (boolean) - True if the provided invariant is the correct extremum value, false otherwise. #### Response Example ```json { "error": "0", "is_valid": true } ``` ``` -------------------------------- ### Plutus Smart Contract Redeemer Data Source: https://github.com/splashprotocol/splash-offchain-multiplatform/blob/develop/splash-testing-cardano/tx.txt Represents redeemer data for a Plutus smart contract, including the tag (Spend), index, datum, and execution units (memory and steps). This is crucial for interacting with on-chain logic. ```json { "tag": "Spend", "index": "0", "data": { "datum": { "ConstrPlutusData": { "alternative": "1", "data": { "elems": [], "definite_encoding": true } } }, "original_bytes": [ 216, 122, 128 ] }, "ex_units": { "mem": "500000", "steps": "200000000" } } ``` ```json { "tag": "Spend", "index": "1", "data": { "datum": { "ConstrPlutusData": { "alternative": "1", "data": { "elems": [], "definite_encoding": true } } }, "original_bytes": [ 216, 122, 128 ] }, "ex_units": { "mem": "500000", "steps": "200000000" } } ``` ```json { "tag": "Reward", "index": "0", "data": { "datum": { "List": { "elems": [], "definite_encoding": true } }, "original_bytes": [ 128 ] } ``` -------------------------------- ### Validate StableSwap Invariant Error (Rust) Source: https://context7.com/splashprotocol/splash-offchain-multiplatform/llms.txt This Rust snippet validates calculated StableSwap invariant values against the StableSwap equation, checking for acceptable error bounds. It uses `calculate_invariant_error_from_balances` and `check_invariant_extremum` to ensure the invariant is correct and at its minimum error. ```rust use primitive_types::U512; use cardano_offchain_stableswap::stable_swap_invariant::{ calculate_invariant, calculate_invariant_error_from_balances, check_invariant_extremum }; let balances = vec![U512::from(1_000_000u64), U512::from(1_000_000u64)]; let n_assets = 2u32; let ampl_coefficient = 85u32; let ann = U512::from(ampl_coefficient) * U512::from(n_assets.pow(n_assets)); let d = calculate_invariant(&balances, &n_assets, &l_coefficient); // Check if the invariant satisfies the equation let error = calculate_invariant_error_from_balances(&n_assets, &ann, &balances, &d); println!("Invariant error: {}", error); // Verify we're at the minimum of the error function let is_valid = check_invariant_extremum(&n_assets, &ann, &balances, &d); assert!(is_valid); ``` -------------------------------- ### Plutus Data Encoding (Haskell) Source: https://github.com/splashprotocol/splash-offchain-multiplatform/blob/develop/splash-testing-cardano/tx.txt This snippet demonstrates the structure of Plutus data, specifically the 'ConstrPlutusData' type, which is used for representing algebraic data types in Haskell. It shows nested 'alternative' and 'data' fields, along with 'elems' for lists of other Plutus data. The 'definite_encoding' field indicates whether the encoding is definitive. ```json { "datum": { "ConstrPlutusData": { "alternative": "0", "data": { "elems": [ { "datum": { "ConstrPlutusData": { "alternative": "0", "data": { "elems": [ { "datum": { "Bytes": [ 75, 228, 250, 37, 240, 41, 209, 76, 13, 114, 58, 244, 161, 230, 250, 113, 51, 252, 58, 97, 15, 136, 3, 54, 173, 104, 92, 186 ] }, "original_bytes": [ 88, 28, 75, 228, 250, 37, 240, 41, 209, 76, 13, 114, 58, 244, 161, 230, 250, 113, 51, 252, 58, 97, 15, 136, 3, 54, 173, 104, 92, 186 ] } ], "definite_encoding": false } } }, "original_bytes": [ 216, 121, 159, 88, 28, 75, 228, 250, 37, 240, 41, 209, 76, 13, 114, 58, 244, 161, 230, 250, 113 ] } ], "definite_encoding": false } } } } ``` -------------------------------- ### Transaction Outputs Data Representation Source: https://github.com/splashprotocol/splash-offchain-multiplatform/blob/develop/splash-testing-cardano/tx.txt This snippet shows a hexadecimal representation of data associated with transaction outputs. It includes byte arrays that likely define asset values or metadata within the transaction. ```hexadecimal [ 232, 1, 255, 26, 0, 7, 161, 32, 216, 121, 159, 216, 121, 159, 88, 28, 75, 228, 250, 37, 240, 41, 209, 76, 13, 114, 58, 244, 161, 230, 250, 113, 51, 252, 58, 97, 15, 136, 3, 54, 173, 104, 92, 186, 255, 216, 121, 159, 216, 121, 159, 216, 121, 159, 88, 28, 91, 218, 115, 4, 61, 67, 173, 141, 245, 206, 117, 99, 156, 244, 142, 31, 43, 69, 69, 64, 59, 233, 47, 1, 19, 227, 117, 55, 255, 255, 255, 255, 88, 28, 75, 228, 250, 37, 240, 41, 209, 76, 13, 114, 58, 244, 161, 230, 250, 113, 51, 252, 58, 97, 15, 136, 3, 54, 173, 104, 92, 186, 128, 255 ] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.