# Spark on miden To develop Spark on the Polygon Miden platform, it's essential to consider the unique features and architecture of Miden. Here's a basic plan for the architecture of Spark on Miden: ### What is Spark and its Purpose Spark is a cross-margin oracle-based perpetual order book exchange. Its key features include a high-performance order book, cross-margin trading, partial liquidations, and an advanced risk engine. On Miden, these features would be adapted to leverage Miden's concurrent transaction execution and enhanced privacy properties. ### Core Accounts (Contracts) to be Developed on Miden 1. **Clearing House Account**: This account would handle user interactions for creating positions and manage the logic for funding. 2. **Account Balance Account**: Responsible for storing information about user positions and PnL. 3. **Insurance Fund Account**: Functions as the exchange's risk mitigation pool. 4. **Perpetual Market Account**: The order book account on which the perpetual exchange operates. 5. **Vault Account**: Holds all funds; trading on Spark begins with deposits into this account. ### Supporting Services for System Operation - **Liquidator Service**: Liquidates positions eligible for liquidation and removes undercollateralized orders. - **Matching Engine**: Matches orders in the order book. - **Risk Engine**: Calculates and updates risk parameters. ### External Services Required for Spark’s Operation - **Oracles (e.g., Pyth Network)**: Provides reliable and timely market data for asset pricing. - **Indexing Services (e.g., The Graph)**: Facilitates efficient data retrieval and indexing for the platform. ### About oracles Spark currently utilizes the Pyth oracle in the following functions: **Vault** - `withdraw_all` and `withdraw_collateral`: These are used for funding since they internally call `clearing_house_contract.settle_all_funding`. **Clearing House** - `liquidate`: Used for `settle_all_funding`, `settle_bad_debt`, and checking `require_enough_free_collateral` to determine if liquidation is possible. - `open_order`: Used for `settle_funding` and checking `require_enough_free_collateral` to ensure the user has sufficient free collateral. - `pause_market`: Used to record the price at which a market is paused. **Perp Market (Orderbook)** - `match_orders`: Utilized for `settle_funding` and checking `require_enough_free_collateral` - it verifies if the user has enough free collateral. - `remove_uncollaterised_orders`: Used in `get_free_collateral` to understand if the orders are genuinely uncollateralized. **Insurance Fund** - `distribute_fee`: Uses `get_free_collateral` and `get_insurance_fund_capacity`. - `repay`: Executes the repayment process for the insurance fund from the contract's balance, using `vault_contract.get_account_value_and_total_collateral_value(insurance_fund_address)`. Currently, Spark uses the Pyth oracle, which is an on-demand oracle. Spark can also use Chainlink as an oracle, but the price update frequency should not be less than every 2 minutes, otherwise, Spark could be vulnerable to various attacks. ### Architecture Adaptations for Miden - **Parallel Transaction Execution**: Leverage Miden’s ability for parallel processing to enhance the order book's performance and efficiency. - **Privacy Enhancements**: Utilize Miden’s privacy features to secure transaction details and user positions. - **Actor-based State Model**: Implement accounts as actors responsible for their state, communicating via messages (notes), enhancing the system’s modularity and scalability. - **Stark Proofs for Transaction Validation**: Each account (actor) would independently prove the validity of their state transitions, ensuring integrity and compliance with the network rules. ### Conclusion Adapting Spark for Miden involves leveraging Miden's unique capabilities, such as parallel processing and enhanced privacy, while maintaining the core functionalities of Spark. The development would require a careful redesign of Spark’s contracts (accounts) and services to fit into Miden's actor-based model and its hybrid state management approach. The integration of external services like oracles and indexing solutions would also be crucial to ensure a robust and efficient perpetual exchange platform on Polygon Miden. ## Spark docs ![image](https://hackmd.io/_uploads/rJtdkl8Fp.png) ## ClearingHouseContract Documentation #### Overview The `ClearingHouseContract` is a comprehensive contract covering various functionalities like order placement, position management, market operations, funding processes, liquidation, and administrative tasks in a decentralized trading platform. #### ABI Functions #### debug_increment_timestamp() Description: Increments the internal timestamp for debugging purposes. Implementation: Adjusts the internal debug timestamp based on a predefined step. Callable By: Contract owner or admin with debug access. #### open_order(base_token: AssetId, base_size: I64, order_price: u64, price_update_data: Vec<Bytes>) [Payable] Description: Opens an order with specified base token, size, and price. Arguments: base_token, base_size, order_price, price_update_data. Implementation: Checks market status, registers base token, and updates price. Calls Other Functions: check_market_open, register_base_token, update_price. Payable: Accepts payments. Callable By: Any authorized trader or contract. #### modify_position(trader: Address, base_token: AssetId, exchanged_position_size: I64, exchanged_position_notional: I64) Description: Modifies a trader's position for a specific base token. Arguments: trader, base_token, exchanged_position_size, exchanged_position_notional. Implementation: Validates market status and settles funding before modifying the position. Calls Other Functions: check_market_open, settle_funding, require_enough_free_collateral. Callable By: Perpetual market contract. #### get_taker_position_safe(trader: Address, base_token: AssetId) -> I64 Description: Retrieves a trader's taker position size for a given base token, ensuring it's non-zero. Arguments: trader, base_token. Returns: Size of the taker position. Callable By: General access. #### get_taker_position(trader: Address, base_token: AssetId) -> I64 Description: Retrieves a trader's taker position size for a given base token. Arguments: trader, base_token. Returns: Size of the taker position. Callable By: General access. #### get_liquidated_position_size_and_notional(trader: Address, base_token: AssetId, account_value: I64, position_size_to_be_liquidated: I64) -> (I64, I64) Description: Calculates the size and notional of a liquidated position based on account value and position size to be liquidated. Arguments: trader, base_token, account_value, position_size_to_be_liquidated. Returns: Tuple containing size and notional of the liquidated position. Callable By: General access. #### get_max_abs_position_size(trader: Address, base_asset: AssetId) -> (u64, u64) Description: Retrieves the maximum absolute position size for a trader and a base asset. Arguments: trader, base_asset. Returns: Tuple containing max absolute short and long sizes. Callable By: General access. #### close_market(base_token: AssetId, closed_price: u64) Description: Closes the market for a specified base token at a given price. Arguments: base_token, closed_price. Implementation: Updates market status to closed. Calls Other Functions: only_owner (internal validation). Callable By: Contract owner. #### create_market(asset_id: AssetId, decimal: u32, price_feed: b256, im_ratio: u64, mm_ratio: u64, initial_price: u64) Description: Creates a market with specified parameters including asset ID, decimals, and ratios. Arguments: asset_id, decimal, price_feed, im_ratio, mm_ratio, initial_price. Implementation: Registers a new market and initializes its parameters. Calls Other Functions: only_owner (internal validation). Callable By: Contract owner. #### check_market_open(base_token: AssetId) Description: Checks if the market for a given base token is open. Arguments: base_token. Implementation: Verifies the market status. Callable By: General access. #### get_market(base_token: AssetId) -> Market Description: Retrieves market details for a specified base token. Arguments: base_token. Returns: Market structure with market details. Callable By: General access. #### get_funding(base_token: AssetId) -> (I64, u64) Description: Gets funding information for a specific base token. Arguments: base_token. Returns: Tuple containing funding growth and timestamp. Callable By: General access. #### settle_all_funding(trader: Address) Description: Settles all pending funding payments for a trader. Arguments: trader. Implementation: Processes funding settlements across all trader's base tokens. Calls Other Functions: settle_funding. Callable By: Vault contract or trader. #### get_all_pending_funding_payment(trader: Address) -> I64 Description: Retrieves the total pending funding payment for a trader. Arguments: trader. Returns: Total pending funding payment. Callable By: General access. #### get_pending_funding_payment(trader: Address, base_token: AssetId) -> (I64, I64) Description: Gets the pending funding payment for a trader and a specific base token. Arguments: trader, base_token. Returns: Tuple containing funding payment and funding growth. Callable By: General access. #### get_funding_rate(base_token: AssetId) -> I64 Description: Calculates the funding rate for a specific base token. Arguments: base_token. Returns: Funding rate. Callable By: General access. #### liquidate(trader: Address, base_token: AssetId, position_size: I64, price_update_data: Vec<Bytes>) [Payable] Description: Liquidates a specified size of a trader's position. Arguments: trader, base_token, position_size, price_update_data. Implementation: Processes liquidation and updates positions. Calls Other Functions: update_price, get_liquidated_position_size_and_notional. Payable: Accepts payments. Callable By: Any authorized entity. #### get_margin_requirement_for_liquidation(trader: Address) -> u64 Description: Retrieves the margin requirement for initiating liquidation. Arguments: trader. Returns: Margin requirement. Callable By: General access. #### is_liquidatable(trader: Address) -> bool Description: Determines if a trader's positions are eligible for liquidation. Arguments: trader. Returns: Boolean indicating liquidation eligibility. Callable By: General access. #### pause_market(base_token: AssetId, update_data: Vec<Bytes>) [Payable] Description: Pauses trading for a base token and updates the price feed. Arguments: base_token, update_data. Implementation: Changes market status to paused and updates price. Calls Other Functions: verify_owner_or_admin, update_price. Payable: Accepts payments. Callable By: Contract owner or admin. #### unpause_market(base_token: AssetId) Description: Resumes trading for a base token. Arguments: base_token. Implementation: Changes market status to open. Calls Other Functions: verify_owner_or_admin. Callable By: Contract owner or admin. #### add_admin(address: Address) Description: Adds an admin to the contract. Arguments: address. Implementation: Registers a new admin. Calls Other Functions: only_owner (internal validation). Callable By: Contract owner. #### remove_admin(address: Address) Description: Removes an admin from the contract. Arguments: address. Implementation: Deregisters an admin. Calls Other Functions: only_owner (internal validation). Callable By: Contract owner. #### update_protocol_fee_rate(protocol_fee_rate: u64) Description: Updates the protocol fee rate. Arguments: protocol_fee_rate. Implementation: Adjusts the protocol fee rate. Calls Other Functions: only_owner (internal validation). Callable By: Contract owner. #### update_insurance_fund_fee_share(insurance_fund_fee_share: u64) Description: Updates the insurance fund fee share ratio. Arguments: insurance_fund_fee_share. Implementation: Adjusts the fee share ratio for the insurance fund. Calls Other Functions: only_owner (internal validation). Callable By: Contract owner. #### update_liquidation_penalty_ratio(liquidation_penalty_ratio: u64) Description: Updates the liquidation penalty ratio. Arguments: liquidation_penalty_ratio. Implementation: Adjusts the ratio for liquidation penalties. Calls Other Functions: only_owner (internal validation). Callable By: Contract owner. #### update_max_funding_rate(max_funding_rate: u64) Description: Updates the maximum funding rate. Arguments: max_funding_rate. Implementation: Adjusts the maximum rate for funding. Calls Other Functions: only_owner (internal validation). Callable By: Contract owner. #### get_account_value(trader: Address) -> I64 Description: Retrieves the account value for a given trader. Arguments: trader. Returns: Account value. Callable By: General access. #### get_taker_open_notional(trader: Address, base_token: AssetId) -> I64 Description: Retrieves the open notional value of a taker's position. Arguments: trader, base_token. Returns: Open notional value. Callable By: General access. #### require_enough_free_collateral(trader: Address) Description: Ensures that a trader has enough free collateral as per the initial margin ratio. Arguments: trader. Implementation: Checks for sufficient free collateral. Calls Other Functions: get_free_collateral (from VaultContract). Callable By: General access. ## AccountBalanceContract Documentation ### Overview The `AccountBalanceContract` is designed to manage and query account balances, positions, and profit and loss (PNL) data in a financial trading system. It includes features like PNL calculation, balance settlement, position management, and token registration. ### ABI Functions #### modify_owed_realized_pnl(trader: Address, amount: I64) Description: Modifies the owed and realized PNL for a trader. Implementation: Updates the trader's PNL in the system. Callable By: Clearing House or Perpetual Market contracts. #### settle_owed_realized_pnl(trader: Address) -> I64 Description: Settles the owed and realized PNL for a trader, returning the settled amount. Implementation: Resets the trader's PNL to zero and returns the previous amount. Callable By: Vault contract. #### get_pnl(trader: Address) -> (I64, I64) Description: Retrieves the PNL information for a trader, including owed and unrealized PNL. Implementation: Sums up the PNL values across all trader's positions. Callable By: Any contract or trader querying PNL data. #### settle_balance_and_deregister(trader: Address, base_token: AssetId, taker_base: I64, taker_quote: I64, realized_pnl: I64) Description: Settles the balance for a trader and deregisters them from a specified market. Implementation: Adjusts the account balance and removes the trader from the base token registry. Callable By: Clearing House contract. #### get_account_balance(trader: Address, base_token: AssetId) -> AccountBalance Description: Retrieves the account balance for a trader in a specific market. Implementation: Returns balance details including position size and open notional values. Callable By: Any contract or trader querying account balance. #### register_base_token(trader: Address, base_token: AssetId) Description: Registers a base token for a trader. Implementation: Adds the base token to the trader's list of active tokens. Callable By: Clearing House contract. #### get_base_tokens(trader: Address) -> Vec<AssetId> Description: Retrieves a list of base tokens registered by a trader. Implementation: Returns all active base tokens associated with the trader. Callable By: Any contract or trader querying registered base tokens. #### settle_position_in_closed_market(trader: Address, base_token: AssetId) -> (I64, I64, I64, u64) Description: Settles a trader's position in a closed market for a specific base token. Implementation: Calculates and settles the position notional, open notional, and realized PNL. Callable By: Clearing House contract. #### get_liquidatable_position_size(trader: Address, base_token: AssetId, account_value: I64) -> I64 Description: Calculates the size of a liquidatable position for a trader based on their account value. Implementation: Determines the position size eligible for liquidation. Callable By: Any contract or trader assessing liquidation risks. #### get_taker_position_size(trader: Address, base_token: AssetId) -> I64 Description: Retrieves the taker position size for a trader in a specific base token. Implementation: Returns the current position size of the trader in the specified market. Callable By: Any contract or trader querying position size. #### get_total_position_value(trader: Address, base_token: AssetId) -> I64 Description: Retrieves the total position value for a trader in a specific base token. Implementation: Calculates the total value of the trader's position in the market. Callable By: Any contract or trader querying position value. #### get_total_abs_position_value(trader: Address) -> u64 Description: Retrieves the total absolute position value for a trader. Implementation: Sums up the absolute values of all positions across different markets. Callable By: Any contract or trader querying overall position value. #### settle_bad_debt(trader: Address) Description: Settles bad debt for a trader, ensuring the trader is not the insurance fund. Implementation: Adjusts PNL and balances to settle any outstanding bad debt. Callable By: Any contract or trader addressing bad debt issues. #### update_tw_premium_growth_global(trader: Address, base_token: AssetId, last_tw_premium_growth_global: I64) Description: Updates the global TWAP premium growth for a trader's position. Implementation: Records the latest TWAP premium growth for the trader's position. Callable By: Clearing House contract. #### get_taker_open_notional(trader: Address, base_token: AssetId) -> I64 Description: Retrieves the taker's open notional value for a specified base token. Implementation: Returns the current open notional value of the trader's position. Callable By: Any contract or trader querying open notional. #### get_margin_requirement_for_liquidation(trader: Address) -> u64 Description: Retrieves the margin requirement for liquidation for a specified trader. Implementation: Calculates the margin needed to avoid liquidation. Callable By: Any contract or trader assessing liquidation margins. #### get_margin_requirement(trader: Address) -> u64 Description: Retrieves the margin requirement for a specified trader. Implementation: Calculates the total margin requirement based on trader's positions. Callable By: Any contract or trader querying margin requirements. #### emit_account_balance_change_event(events: (Option<(Address, AssetId)>, Option<(Address, AssetId)>, Option<(Address, AssetId)>, Option<(Address, AssetId)>, Option<(Address, AssetId)>)) Description: Emits an event indicating a change in account balance. Implementation: Logs account balance changes for auditing and tracking. Callable By: Clearing House, Perpetual Market, or Vault contracts. #### emit_owed_realized_pnl_change_event(events: (Option<Address>, Option<Address>)) Description: Emits an event indicating a change in owed realized PNL. Implementation: Logs PNL changes for transparency and record-keeping. Callable By: Clearing House, Perpetual Market, or Vault contracts. ## PerpMarketContract Documentation ### Overview The `PerpMarketContract` is a vital component of a decentralized trading platform, handling various aspects of market operations including order management, price retrieval, and administrative functions. ### ABI Functions #### debug_increment_timestamp() Description: Increments the internal timestamp for debugging purposes. Implementation: Adjusts the internal debug timestamp based on a predefined step. Callable By: Contract owner or admin with debug access. #### open_order(trader: Address, base_token: AssetId, base_size: I64, order_price: u64) Description: Opens a new order for a trader with specified parameters. Implementation: Registers a new order in the system with given details. Callable By: Clearing House contract. Payable: No. #### remove_uncollaterised_orders(trader: Address) Description: Removes uncollateralized orders for a specified trader. Implementation: Identifies and deletes orders lacking sufficient collateral. Callable By: Any contract or trader addressing collateral issues. Payable: No. #### remove_order(order_id: b256) Description: Removes a specific order by its unique ID. Implementation: Deletes the order from the system. Callable By: The owner of the order. Payable: No. #### remove_all_orders() Description: Removes all orders belonging to the sender across all base tokens. Implementation: Identifies and deletes all orders associated with the sender. Callable By: The trader who owns the orders. Payable: No. #### match_orders(order_sell_id: b256, order_buy_id: b256, price_update_data: Vec<Bytes>) Description: Matches a sell order and a buy order to execute a trade. Implementation: Facilitates the trade between two matching orders. Callable By: Any authorized trader or contract. Payable: Yes. #### has_active_orders(trader: Address, base_token: AssetId) -> bool Description: Checks if a trader has active orders for a specific base token. Implementation: Returns a boolean indicating the presence of active orders. Callable By: Any contract or trader querying active orders. Payable: No. #### get_market_price(token: AssetId) -> u64 Description: Retrieves the current market price of a token. Implementation: Returns the latest market price for the specified token. Callable By: Any contract or trader querying market prices. Payable: No. #### get_twaps(base_token: AssetId) -> (Option<Twap>, Option<Twap>) Description: Retrieves the TWAPs (Time-Weighted Average Prices) for a specific base token. Implementation: Returns current and historical TWAPs for the token. Callable By: Any contract or trader querying TWAP data. Payable: No. #### get_mark_price(token: AssetId) -> u64 Description: Retrieves the current mark price of a token. Implementation: Returns the current mark price for the specified token. Callable By: Any contract or trader querying mark prices. Payable: No. #### get_total_trader_order_base(trader: Address, base_token: AssetId) -> I64 Description: Retrieves the total order value of a trader for a specific base token. Implementation: Returns the total value of orders for the trader in the base token. Callable By: Any contract or trader querying order values. Payable: No. #### update_mark_span(mark_span: u64) Description: Updates the mark span setting in the contract. Implementation: Adjusts the time span for mark price calculations. Callable By: Contract owner or admin. Payable: No. #### update_market_span(market_span: u64) Description: Updates the market span setting in the contract. Implementation: Adjusts the time span for market price calculations. Callable By: Contract owner or admin. Payable: No. #### update_fee_rate(fee_rate: u64) Description: Updates the fee rate setting in the contract. Implementation: Adjusts the fee rate for market operations. Callable By: Contract owner or admin. Payable: No. #### get_trader_orders(trader: Address, base_token: AssetId) -> Vec<Order> Description: Retrieves all orders placed by a trader for a specific base token. Implementation: Returns a list of orders for the trader in the specified token. Callable By: Any contract or trader querying order details. Payable: No. #### setup_twap(base_token: AssetId, current_twap: u64) Description: Sets up the TWAP for a specific base token. Implementation: Initializes or updates the TWAP for the given token. Callable By: Clearing House contract. Payable: No. ## InsuranceFundContract Documentation ### Overview The `InsuranceFundContract` is designed to manage the financial aspects of an insurance fund within a decentralized trading platform. It includes functionalities for setting thresholds, managing surplus distribution, and executing repayment processes. ### ABI Functions #### set_distribution_threshold(distribution_threshold: u64) Description: Sets the distribution threshold value for the contract. Implementation: Updates the threshold at which surplus distribution occurs. Callable By: Contract owner or designated admin. Payable: No. #### set_surplus_beneficiary(surplus_beneficiary: Address) Description: Sets the address to receive surplus funds. Implementation: Designates a new address as the surplus beneficiary. Callable By: Contract owner or designated admin. Payable: No. #### get_insurance_fund_capacity() -> I64 Description: Retrieves the current capacity of the insurance fund. Implementation: Returns the total capacity of the fund as a signed 64-bit integer. Callable By: Any contract or trader querying fund capacity. Payable: No. #### repay() Description: Initiates the insurance fund repayment process. Implementation: Executes the repayment from the contract's balance. Callable By: Any authorized entity to initiate repayment. Payable: No. #### distribute_fee(price_update_data: Vec<Bytes>) -> u64 Description: Distributes collected fees according to the contract's logic. Implementation: Distributes surplus fees if the fund exceeds the distribution threshold. Callable By: Any authorized entity to trigger fee distribution. Payable: No. ## VaultContract Documentation ### Overview The `VaultContract` serves as a crucial component in a decentralized trading platform, handling collateral deposits and withdrawals, trading management, and administrative functions. ### ABI Functions #### deposit_collateral() Description: Allows a user to deposit settlement token as collateral. Implementation: Adds collateral to the user's balance and logs the event. Callable By: Any user desiring to deposit collateral. Payable: Yes, requires payment in the settlement token. #### withdraw_collateral(amount: u64, price_update_data: Vec<Bytes>) Description: Enables a user to withdraw a specified amount of collateral. Implementation: Settles and decreases the user's balance, transferring the specified collateral amount. Arguments: `amount` (collateral amount to withdraw), `price_update_data` (price data for updates). Callable By: User wishing to withdraw their collateral. Payable: Yes, involves the transfer of collateral. #### withdraw_all(price_update_data: Vec<Bytes>) -> u64 Description: Withdraws the entire collateral balance for the calling user. Implementation: Computes and transfers the total available collateral for withdrawal. Arguments: `price_update_data` (price data for updates). Returns: The total amount of collateral withdrawn. Callable By: Any user seeking to withdraw their full collateral balance. Payable: Yes. #### get_collateral_balance(address: Address) -> u64 Description: Retrieves the collateral balance of a given address. Implementation: Returns the collateral balance associated with the specified address. Arguments: `address` (address to query). Returns: Collateral balance of the specified address. Callable By: Any entity querying collateral balance. Payable: No. #### get_free_collateral(trader: Address) -> I64 Description: Fetches the free collateral available to a specific trader. Implementation: Calculates and returns the trader's free collateral. Arguments: `trader` (trader's address). Returns: Amount of free collateral available. Callable By: Anyone inquiring about a trader's free collateral. Payable: No. #### get_account_value_and_total_collateral_value(trader: Address) -> (I64, I64) Description: Obtains the account value and total collateral value for a trader. Implementation: Computes and returns both the account value and total collateral value. Arguments: `trader` (trader's address). Returns: A tuple of account value and total collateral value. Callable By: Any party interested in a trader's financial status. Payable: No. #### pause_trading() Description: Pauses trading activities on the platform. Implementation: Activates the trading pause mechanism. Callable By: Contract owner or admin. Payable: No. #### resume_trading() Description: Resumes trading activities on the platform. Implementation: Deactivates the trading pause mechanism. Callable By: Contract owner or admin. Payable: No. #### add_admin(address: Address) Description: Adds an admin to the platform. Implementation: Grants administrative privileges to the specified address. Arguments: `address` (new admin's address). Callable By: Contract owner. Payable: No. #### remove_admin(address: Address) Description: Removes an admin from the platform. Implementation: Revokes administrative privileges from the specified address. Arguments: `address` (admin's address to remove). Callable By: Contract owner. Payable: No.