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:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Description: Checks if the market for a given base token is open.
Arguments: base_token.
Implementation: Verifies the market status.
Callable By: General access.
Description: Retrieves market details for a specified base token.
Arguments: base_token.
Returns: Market structure with market details.
Callable By: General access.
Description: Gets funding information for a specific base token.
Arguments: base_token.
Returns: Tuple containing funding growth and timestamp.
Callable By: General access.
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.
Description: Retrieves the total pending funding payment for a trader.
Arguments: trader.
Returns: Total pending funding payment.
Callable By: General access.
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.
Description: Calculates the funding rate for a specific base token.
Arguments: base_token.
Returns: Funding rate.
Callable By: General access.
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.
Description: Retrieves the margin requirement for initiating liquidation.
Arguments: trader.
Returns: Margin requirement.
Callable By: General access.
Description: Determines if a trader's positions are eligible for liquidation.
Arguments: trader.
Returns: Boolean indicating liquidation eligibility.
Callable By: General access.
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.
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.
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.
Description: Removes an admin from the contract.
Arguments: address.
Implementation: Deregisters an admin.
Calls Other Functions: only_owner (internal validation).
Callable By: Contract owner.
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.
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.
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.
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.
Description: Retrieves the account value for a given trader.
Arguments: trader.
Returns: Account value.
Callable By: General access.
Description: Retrieves the open notional value of a taker's position.
Arguments: trader, base_token.
Returns: Open notional value.
Callable By: General access.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
The VaultContract
serves as a crucial component in a decentralized trading platform, handling collateral deposits and withdrawals, trading management, and administrative functions.
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.
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.
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.
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.
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.
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.
Description: Pauses trading activities on the platform.
Implementation: Activates the trading pause mechanism.
Callable By: Contract owner or admin.
Payable: No.
Description: Resumes trading activities on the platform.
Implementation: Deactivates the trading pause mechanism.
Callable By: Contract owner or admin.
Payable: No.
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.
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.