# Table of Contents - [Introduction | SYMMIO Protocol Gitbook](#introduction-symmio-protocol-gitbook) - [Table of Contents | SYMMIO Protocol Gitbook](#table-of-contents-symmio-protocol-gitbook) - [Symmio Foundation | SYMMIO Protocol Gitbook](#symmio-foundation-symmio-protocol-gitbook) - [Documentation for Traders | SYMMIO Protocol Gitbook](#documentation-for-traders-symmio-protocol-gitbook) - [Symmio Whitepaper | SYMMIO Protocol Gitbook](#symmio-whitepaper-symmio-protocol-gitbook) - [Protocol Introduction | SYMMIO Protocol Gitbook](#protocol-introduction-symmio-protocol-gitbook) - [Concepts in SYMMIO | SYMMIO Protocol Gitbook](#concepts-in-symmio-symmio-protocol-gitbook) - [Withdrawals | SYMMIO Protocol Gitbook](#withdrawals-symmio-protocol-gitbook) - [Settlement (0.8.4) | SYMMIO Protocol Gitbook](#settlement-0-8-4-symmio-protocol-gitbook) - [Intent-Based Trading | SYMMIO Protocol Gitbook](#intent-based-trading-symmio-protocol-gitbook) - [Instant Trading | SYMMIO Protocol Gitbook](#instant-trading-symmio-protocol-gitbook) - [Force Closing Positions | SYMMIO Protocol Gitbook](#force-closing-positions-symmio-protocol-gitbook) - [Using Take Profit and Stop Loss | SYMMIO Protocol Gitbook](#using-take-profit-and-stop-loss-symmio-protocol-gitbook) - [Liquidations | SYMMIO Protocol Gitbook](#liquidations-symmio-protocol-gitbook) - [Funding Rates (0.8.4) | SYMMIO Protocol Gitbook](#funding-rates-0-8-4-symmio-protocol-gitbook) - [Market vs. Limit Orders | SYMMIO Protocol Gitbook](#market-vs-limit-orders-symmio-protocol-gitbook) - [Interacting with SYMMIO's Contracts | SYMMIO Protocol Gitbook](#interacting-with-symmio-s-contracts-symmio-protocol-gitbook) - [Learn how to build a Trading Bot using SYMMIO | SYMMIO Protocol Gitbook](#learn-how-to-build-a-trading-bot-using-symmio-symmio-protocol-gitbook) - [Closing a Position | SYMMIO Protocol Gitbook](#closing-a-position-symmio-protocol-gitbook) - [Opening a Position | SYMMIO Protocol Gitbook](#opening-a-position-symmio-protocol-gitbook) - [Monitoring Price | SYMMIO Protocol Gitbook](#monitoring-price-symmio-protocol-gitbook) - [Creating a Sub-Account | SYMMIO Protocol Gitbook](#creating-a-sub-account-symmio-protocol-gitbook) - [Monitoring Position Status | SYMMIO Protocol Gitbook](#monitoring-position-status-symmio-protocol-gitbook) - [Authenticating Trades | SYMMIO Protocol Gitbook](#authenticating-trades-symmio-protocol-gitbook) - [Documentation for Frontend Builders | SYMMIO Protocol Gitbook](#documentation-for-frontend-builders-symmio-protocol-gitbook) - [Instant Withdrawal | SYMMIO Protocol Gitbook](#instant-withdrawal-symmio-protocol-gitbook) - [Setting up a Frontend with SYMMIO | SYMMIO Protocol Gitbook](#setting-up-a-frontend-with-symmio-symmio-protocol-gitbook) - [Closing a Position | SYMMIO Protocol Gitbook](#closing-a-position-symmio-protocol-gitbook) - [Documentation for Investors | SYMMIO Protocol Gitbook](#documentation-for-investors-symmio-protocol-gitbook) - [Solver Docs (Github) | SYMMIO Protocol Gitbook](#solver-docs-github-symmio-protocol-gitbook) - [Instant Trading for Frontend Builders | SYMMIO Protocol Gitbook](#instant-trading-for-frontend-builders-symmio-protocol-gitbook) - [MultiAccount Deployment Guide | SYMMIO Protocol Gitbook](#multiaccount-deployment-guide-symmio-protocol-gitbook) - [Setting a Stop Loss | SYMMIO Protocol Gitbook](#setting-a-stop-loss-symmio-protocol-gitbook) - [Delegating Access to the Solver | SYMMIO Protocol Gitbook](#delegating-access-to-the-solver-symmio-protocol-gitbook) - [Introduction and Diamond Explainer | SYMMIO Protocol Gitbook](#introduction-and-diamond-explainer-symmio-protocol-gitbook) - [Documentation for Solvers | SYMMIO Protocol Gitbook](#documentation-for-solvers-symmio-protocol-gitbook) - [Building an Application with SYMMIO | SYMMIO Protocol Gitbook](#building-an-application-with-symmio-symmio-protocol-gitbook) - [How to Query our Contracts | SYMMIO Protocol Gitbook](#how-to-query-our-contracts-symmio-protocol-gitbook) - [Querying Info from the SYMMIO Diamond | SYMMIO Protocol Gitbook](#querying-info-from-the-symmio-diamond-symmio-protocol-gitbook) - [SYMM Diamond SDK | SYMMIO Protocol Gitbook](#symm-diamond-sdk-symmio-protocol-gitbook) - [Contracts Documentation 0.8.2 | SYMMIO Protocol Gitbook](#contracts-documentation-0-8-2-symmio-protocol-gitbook) - [MultiAccount | SYMMIO Protocol Gitbook](#multiaccount-symmio-protocol-gitbook) - [Architecture Deep Dive | SYMMIO Protocol Gitbook](#architecture-deep-dive-symmio-protocol-gitbook) - [Instant Trading | SYMMIO Protocol Gitbook](#instant-trading-symmio-protocol-gitbook) - [Account Abstracted Instant Actions Frontend Builders | SYMMIO Protocol Gitbook](#account-abstracted-instant-actions-frontend-builders-symmio-protocol-gitbook) - [Settlement and Profit Realization | SYMMIO Protocol Gitbook](#settlement-and-profit-realization-symmio-protocol-gitbook) - [Facets | SYMMIO Protocol Gitbook](#facets-symmio-protocol-gitbook) - [Building a Solver on SYMMIO | SYMMIO Protocol Gitbook](#building-a-solver-on-symmio-symmio-protocol-gitbook) - [Instant Trading | SYMMIO Protocol Gitbook](#instant-trading-symmio-protocol-gitbook) - [Hedging Strategies | SYMMIO Protocol Gitbook](#hedging-strategies-symmio-protocol-gitbook) - [Core Concepts | SYMMIO Protocol Gitbook](#core-concepts-symmio-protocol-gitbook) - [Instant Login (EOA) | SYMMIO Protocol Gitbook](#instant-login-eoa-symmio-protocol-gitbook) - [Creating an Account and Depositing Funds | SYMMIO Protocol Gitbook](#creating-an-account-and-depositing-funds-symmio-protocol-gitbook) - [Frequently Used Queries | SYMMIO Protocol Gitbook](#frequently-used-queries-symmio-protocol-gitbook) - [Glossary | SYMMIO Protocol Gitbook](#glossary-symmio-protocol-gitbook) - [Solver Flow Summary Example | SYMMIO Protocol Gitbook](#solver-flow-summary-example-symmio-protocol-gitbook) - [Overview | SYMMIO Protocol Gitbook](#overview-symmio-protocol-gitbook) - [Depositing and Allocating Collateral | SYMMIO Protocol Gitbook](#depositing-and-allocating-collateral-symmio-protocol-gitbook) - [1. Intent Creation | SYMMIO Protocol Gitbook](#1-intent-creation-symmio-protocol-gitbook) - [Solver Addresses & Endpoints | SYMMIO Protocol Gitbook](#solver-addresses-endpoints-symmio-protocol-gitbook) - [PartyB | SYMMIO Protocol Gitbook](#partyb-symmio-protocol-gitbook) - [Contract Addresses | SYMMIO Protocol Gitbook](#contract-addresses-symmio-protocol-gitbook) - [Role of a Solver | SYMMIO Protocol Gitbook](#role-of-a-solver-symmio-protocol-gitbook) - [Intent Lifecycle and Event Monitoring | SYMMIO Protocol Gitbook](#intent-lifecycle-and-event-monitoring-symmio-protocol-gitbook) - [Instant Trading | SYMMIO Protocol Gitbook](#instant-trading-symmio-protocol-gitbook) - [3. Hedging Off-Chain | SYMMIO Protocol Gitbook](#3-hedging-off-chain-symmio-protocol-gitbook) - [How to Add a Market as a Solver | SYMMIO Protocol Gitbook](#how-to-add-a-market-as-a-solver-symmio-protocol-gitbook) - [Understanding the Contract Architecture | SYMMIO Protocol Gitbook](#understanding-the-contract-architecture-symmio-protocol-gitbook) - [Main Flow | SYMMIO Protocol Gitbook](#main-flow-symmio-protocol-gitbook) - [Solver Settings | SYMMIO Protocol Gitbook](#solver-settings-symmio-protocol-gitbook) - [Facets | SYMMIO Protocol Gitbook](#facets-symmio-protocol-gitbook) - [Closing a Quote | SYMMIO Protocol Gitbook](#closing-a-quote-symmio-protocol-gitbook) - [Contracts Documentation 0.8.4 | SYMMIO Protocol Gitbook](#contracts-documentation-0-8-4-symmio-protocol-gitbook) - [Protocol higher level architecture | SYMMIO Protocol Gitbook](#protocol-higher-level-architecture-symmio-protocol-gitbook) - [Mode | SYMMIO Protocol Gitbook](#mode-symmio-protocol-gitbook) - [The SYMM Diamond | SYMMIO Protocol Gitbook](#the-symm-diamond-symmio-protocol-gitbook) - [Contracts Documentation 0.8.3 | SYMMIO Protocol Gitbook](#contracts-documentation-0-8-3-symmio-protocol-gitbook) - [Instant Trading (Solvers) | SYMMIO Protocol Gitbook](#instant-trading-solvers-symmio-protocol-gitbook) - [Zenith | SYMMIO Protocol Gitbook](#zenith-symmio-protocol-gitbook) - [Polygon (0.2.1) | SYMMIO Protocol Gitbook](#polygon-0-2-1-symmio-protocol-gitbook) - [Base | SYMMIO Protocol Gitbook](#base-symmio-protocol-gitbook) - [Sending a Quote | SYMMIO Protocol Gitbook](#sending-a-quote-symmio-protocol-gitbook) - [Contract Addresses | SYMMIO Protocol Gitbook](#contract-addresses-symmio-protocol-gitbook) - [Perps Hub | SYMMIO Protocol Gitbook](#perps-hub-symmio-protocol-gitbook) - [Trade on Symmio | SYMMIO Protocol Gitbook](#trade-on-symmio-symmio-protocol-gitbook) - [Trading Fees | SYMMIO Protocol Gitbook](#trading-fees-symmio-protocol-gitbook) - [Security (Audits / Bugbounty) | SYMMIO Protocol Gitbook](#security-audits-bugbounty-symmio-protocol-gitbook) - [Glossary | SYMMIO Protocol Gitbook](#glossary-symmio-protocol-gitbook) - [PartyA | SYMMIO Protocol Gitbook](#partya-symmio-protocol-gitbook) - [Recommended Architecture for Solvers | SYMMIO Protocol Gitbook](#recommended-architecture-for-solvers-symmio-protocol-gitbook) - [Staking and Vesting | SYMMIO Protocol Gitbook](#staking-and-vesting-symmio-protocol-gitbook) - [Force Actions Facet (0.8.4) | SYMMIO Protocol Gitbook](#force-actions-facet-0-8-4-symmio-protocol-gitbook) - [Mantle | SYMMIO Protocol Gitbook](#mantle-symmio-protocol-gitbook) - [Instant Trading Condition Checks | SYMMIO Protocol Gitbook](#instant-trading-condition-checks-symmio-protocol-gitbook) - [12-Hour Fraud Proof Window | SYMMIO Protocol Gitbook](#12-hour-fraud-proof-window-symmio-protocol-gitbook) - [Builders introduction | SYMMIO Protocol Gitbook](#builders-introduction-symmio-protocol-gitbook) - [MuonStorage | SYMMIO Protocol Gitbook](#muonstorage-symmio-protocol-gitbook) - [Bug bounty / Coverage | SYMMIO Protocol Gitbook](#bug-bounty-coverage-symmio-protocol-gitbook) - [Solver documentation | SYMMIO Protocol Gitbook](#solver-documentation-symmio-protocol-gitbook) - [Modified Events | SYMMIO Protocol Gitbook](#modified-events-symmio-protocol-gitbook) - [SDK - SYMM client | SYMMIO Protocol Gitbook](#sdk-symm-client-symmio-protocol-gitbook) - [Brand - Assets Logos | SYMMIO Protocol Gitbook](#brand-assets-logos-symmio-protocol-gitbook) - [Liquidation Facet (Implementation) | SYMMIO Protocol Gitbook](#liquidation-facet-implementation-symmio-protocol-gitbook) - [Berachain | SYMMIO Protocol Gitbook](#berachain-symmio-protocol-gitbook) - [Terms of Service & Licensing | SYMMIO Protocol Gitbook](#terms-of-service-licensing-symmio-protocol-gitbook) - [Core Financial Concepts | SYMMIO Protocol Gitbook](#core-financial-concepts-symmio-protocol-gitbook) - [Sherlock Audit -Aug 30, 2023 | SYMMIO Protocol Gitbook](#sherlock-audit-aug-30-2023-symmio-protocol-gitbook) - [Verifying Account Abstracted Instant Actions (ERC-4337) | SYMMIO Protocol Gitbook](#verifying-account-abstracted-instant-actions-erc-4337-symmio-protocol-gitbook) - [CONTRACT LICENSE | SYMMIO Protocol Gitbook](#contract-license-symmio-protocol-gitbook) - [Solver Error Codes | SYMMIO Protocol Gitbook](#solver-error-codes-symmio-protocol-gitbook) - [SymmioPartyA | SYMMIO Protocol Gitbook](#symmiopartya-symmio-protocol-gitbook) - [Main Flow (0.8.4) | SYMMIO Protocol Gitbook](#main-flow-0-8-4-symmio-protocol-gitbook) - [Facets | SYMMIO Protocol Gitbook](#facets-symmio-protocol-gitbook) - [BSC | SYMMIO Protocol Gitbook](#bsc-symmio-protocol-gitbook) - [CONTACT US | SYMMIO Protocol Gitbook](#contact-us-symmio-protocol-gitbook) - [Sonic | SYMMIO Protocol Gitbook](#sonic-symmio-protocol-gitbook) - [Arbitrum | SYMMIO Protocol Gitbook](#arbitrum-symmio-protocol-gitbook) - [TRADEMARK & COPYRIGHT NOTICE | SYMMIO Protocol Gitbook](#trademark-copyright-notice-symmio-protocol-gitbook) - [Polygon | SYMMIO Protocol Gitbook](#polygon-symmio-protocol-gitbook) - [Contract Use Grants | SYMMIO Protocol Gitbook](#contract-use-grants-symmio-protocol-gitbook) - [How to contact ? | SYMMIO Protocol Gitbook](#how-to-contact-symmio-protocol-gitbook) - [Creating the APIs | SYMMIO Protocol Gitbook](#creating-the-apis-symmio-protocol-gitbook) - [2. Seeing the Intent | SYMMIO Protocol Gitbook](#2-seeing-the-intent-symmio-protocol-gitbook) - [Coti | SYMMIO Protocol Gitbook](#coti-symmio-protocol-gitbook) - [Control Facet | SYMMIO Protocol Gitbook](#control-facet-symmio-protocol-gitbook) - [SYMM - V0.8 - 0.81 | SYMMIO Protocol Gitbook](#symm-v0-8-0-81-symmio-protocol-gitbook) - [The SYMM Diamond (0.8.4) | SYMMIO Protocol Gitbook](#the-symm-diamond-0-8-4-symmio-protocol-gitbook) - [Helper Contracts | SYMMIO Protocol Gitbook](#helper-contracts-symmio-protocol-gitbook) - [SYMM - 0.82 | SYMMIO Protocol Gitbook](#symm-0-82-symmio-protocol-gitbook) - [Solving for Symmio | SYMMIO Protocol Gitbook](#solving-for-symmio-symmio-protocol-gitbook) - [Sending a Quote (Instant Open) | SYMMIO Protocol Gitbook](#sending-a-quote-instant-open-symmio-protocol-gitbook) - [Rasa Instant Trading Implementation | SYMMIO Protocol Gitbook](#rasa-instant-trading-implementation-symmio-protocol-gitbook) - [Sherlock Audit - Oct 3, 2024 | SYMMIO Protocol Gitbook](#sherlock-audit-oct-3-2024-symmio-protocol-gitbook) - [Account Facet | SYMMIO Protocol Gitbook](#account-facet-symmio-protocol-gitbook) - [Smart State - Jul 2, 2023 | SYMMIO Protocol Gitbook](#smart-state-jul-2-2023-symmio-protocol-gitbook) - [Solver Implementation Guide (High Level Overview) | SYMMIO Protocol Gitbook](#solver-implementation-guide-high-level-overview-symmio-protocol-gitbook) - [PartyB Facet | SYMMIO Protocol Gitbook](#partyb-facet-symmio-protocol-gitbook) - [Technical Architecture | SYMMIO Protocol Gitbook](#technical-architecture-symmio-protocol-gitbook) - [Frontend Modifications | SYMMIO Protocol Gitbook](#frontend-modifications-symmio-protocol-gitbook) - [Frontend Use Grants | SYMMIO Protocol Gitbook](#frontend-use-grants-symmio-protocol-gitbook) - [Rasa Solver TP/SL Implementation | SYMMIO Protocol Gitbook](#rasa-solver-tp-sl-implementation-symmio-protocol-gitbook) - [Vaults | SYMMIO Protocol Gitbook](#vaults-symmio-protocol-gitbook) - [SymmioPartyB Contract | SYMMIO Protocol Gitbook](#symmiopartyb-contract-symmio-protocol-gitbook) - [Contract Modifications | SYMMIO Protocol Gitbook](#contract-modifications-symmio-protocol-gitbook) - [Sherlock Audit - Jun 17, 2024 | SYMMIO Protocol Gitbook](#sherlock-audit-jun-17-2024-symmio-protocol-gitbook) - [SYMM - 0.83 | SYMMIO Protocol Gitbook](#symm-0-83-symmio-protocol-gitbook) - [Sherlock Audit - Mar 7, 2025 | SYMMIO Protocol Gitbook](#sherlock-audit-mar-7-2025-symmio-protocol-gitbook) - [Frontend Builder Introduction | SYMMIO Protocol Gitbook](#frontend-builder-introduction-symmio-protocol-gitbook) - [SYMM - 0.84 | SYMMIO Protocol Gitbook](#symm-0-84-symmio-protocol-gitbook) - [GET Price Range | SYMMIO Protocol Gitbook](#get-price-range-symmio-protocol-gitbook) - [Funding Rate Facet (0.8.4) | SYMMIO Protocol Gitbook](#funding-rate-facet-0-8-4-symmio-protocol-gitbook) - [MuonStorage | SYMMIO Protocol Gitbook](#muonstorage-symmio-protocol-gitbook) - [Sherlock Audit - Jun 15, 2023 | SYMMIO Protocol Gitbook](#sherlock-audit-jun-15-2023-symmio-protocol-gitbook) - [PartyB | SYMMIO Protocol Gitbook](#partyb-symmio-protocol-gitbook) - [InstantLayer Contract | SYMMIO Protocol Gitbook](#instantlayer-contract-symmio-protocol-gitbook) - [Sherlock Audit - Jan 2, 2024 | SYMMIO Protocol Gitbook](#sherlock-audit-jan-2-2024-symmio-protocol-gitbook) - [Bridge Facet | SYMMIO Protocol Gitbook](#bridge-facet-symmio-protocol-gitbook) - [Fetching Gas Prices Script | SYMMIO Protocol Gitbook](#fetching-gas-prices-script-symmio-protocol-gitbook) - [PerpsHub TP/SL Implementation | SYMMIO Protocol Gitbook](#perpshub-tp-sl-implementation-symmio-protocol-gitbook) - [New Events | SYMMIO Protocol Gitbook](#new-events-symmio-protocol-gitbook) - [FRONTEND LICENSE | SYMMIO Protocol Gitbook](#frontend-license-symmio-protocol-gitbook) - [Collateral & Margin System | SYMMIO Protocol Gitbook](#collateral-margin-system-symmio-protocol-gitbook) - [User Interaction Scenarios | SYMMIO Protocol Gitbook](#user-interaction-scenarios-symmio-protocol-gitbook) - [Pair Trading - Settlement costs | SYMMIO Protocol Gitbook](#pair-trading-settlement-costs-symmio-protocol-gitbook) - [GET Get Funding Info | SYMMIO Protocol Gitbook](#get-get-funding-info-symmio-protocol-gitbook) - [Intent-Based Trading System | SYMMIO Protocol Gitbook](#intent-based-trading-system-symmio-protocol-gitbook) - [Oracle Integration | SYMMIO Protocol Gitbook](#oracle-integration-symmio-protocol-gitbook) - [Exchanges (Frontend Builders) | SYMMIO Protocol Gitbook](#exchanges-frontend-builders-symmio-protocol-gitbook) --- # Introduction | SYMMIO Protocol Gitbook ![Page cover](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252F3p6j5aB4ghYpn4NWL7sM%252Fheader.jpeg%3Falt%3Dmedia%26token%3Db531d6a5-5fcf-4b53-92e4-46cd00753ee7&width=1248&dpr=3&quality=100&sign=808233f1&sv=2) [hashtag](https://docs.symm.io/#the-symmio-protocol-a-trustless-clearing-house-for-derivatives) The Symmio Protocol - a trustless clearing house for derivatives. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- Symmio is a trustless hybrid (combining on and offchain) clearing house acting as communication, settlement & clearing layer for permissionless derivatives. At its core, Symmio is an intent-centric, meta-derivatives engine, with its first use case being a new type of hyper-efficient perps trading technology. * * * [hashtag](https://docs.symm.io/#symmio-explained-for-different-demographics) Symmio explained for different demographics ----------------------------------------------------------------------------------------------------------------------------- circle-check [hashtag](https://docs.symm.io/#for-crypto-natives) For Crypto Natives: ---------------------------------------------------------------------------- [hashtag](https://docs.symm.io/#symmio-is-to-derivatives-what-celestia-is-for-rollups) Symmio is to Derivatives, what Celestia is for Rollups. --------------------------------------------------------------------------------------------------------------------------------------------------- Celestia and Eigenlayer **enable Rollups as a Service (RaaS)** Symmio offers **“Derivatives as a Service” (DaaS)** DaaS can be used by exchanges or "Subnets" to create a derivatives trading protocol without any technical implementation work or liquidity onboarding; Symmio and its partners take care of everything. Several 3rd parties are already running their own exchanges **using our DaaS (https://intentx.io, https://based.markets, https://thena.fi, https://morphex.trade)** on several blockchains, including on BNB. We are currently generating $1 Billion in monthly volume with over $10 Billion in total volume (source: [https://analytics.symm.ioarrow-up-right](https://analytics.symm.io/) ) . Symmio takes a settlement fee from all subnets that settle on Symmio. The fees generated from settlement flow 100% back to SYMM stakers. In this open ecosystem, actors (integration partners (protocol/exchanges), liquidity providers (MMs), oracles, clearing operators and traders) can collaborate and compete for the best prices and solutions, driving feature innovation and cost efficiency. circle-info [hashtag](https://docs.symm.io/#for-the-nerds-the-term-symmio-stands-for-symmetrical-input-and-output) **For the nerds:** The term Symmio stands for "_**Symmetrical Input & Output"**_ -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- In [computingarrow-up-right](https://en.wikipedia.org/wiki/Computing) , input/output (I/O, i/o, or informally io or IO) is the communication between an information processing system, such as a [computerarrow-up-right](https://en.wikipedia.org/wiki/Computer) , and the outside world, such as another computer system, peripherals, or a human operator. In Symmio, the SYMM in SYMM-IO stands for the Symmetrical nature of the derivatives, bilaterally cleared with all parties existing only in symmetrical form, as all trading parties being a symmetrical counterpart to each other, the IO in SYMM-IO protocol describes the OTC-Derivatives communication & clearing layer between: [Exchanges (Frontend Builders)](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders) (like [https://intentx.ioarrow-up-right](https://intentx.io/) ), [Solving for Symmio](https://docs.symm.io/building-on-symmio/solving-for-symmio) (like [https://www.enso.finance/arrow-up-right](https://www.enso.finance/) ), Network (Liquidators or simply MEV researcher), (like [https://muon.netarrow-up-right](https://www.muon.net/) or [https://www.orbs.com/arrow-up-right](https://www.orbs.com/) ) & [SYMMIO CORE v0.82](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contract-docs/symmio-core-v0.82) the "Symmetrical" or Bilateral Settlement Contract (like the Symmiio core deployed on a State machine like Ethereum). Symmio itself is not only the contracts that live ontop of a State machine, Symmio is the Input and Output protocol that defines the rules how these diverse set of players should interact with each other, implemented as trustless as possible, with the goal to replace the existing traditional Derivatives status quo, like [ISDA Master Agreementsarrow-up-right](https://www.investopedia.com/terms/i/isda-master-agreement.asp) , which rely on enforcability by Law and replace it through a Mathematical and Economically based protocol that enforces through code. Vires in Numeris. * * * [hashtag](https://docs.symm.io/#learn-more) Learn more: ------------------------------------------------------------ [hashtag](https://docs.symm.io/#next-steps) Next steps: ------------------------------------------------------------ Try out a frontend and [start trading.arrow-up-right](https://www.symm.io/frontends) Become a [Symmio Liquidity Provider also called Hedger,](https://docs.symm.io/building-on-symmio/solving-for-symmio) check out the Hedger Outlook to see what is possible as Hedger. Launch your own perpetual trading platform using [Symmioarrow-up-right](https://docs.symm.io/building-on-symm-io/subnets-frontends/introduction) [NextTable of Contentschevron-right](https://docs.symm.io/overview/table-of-contents) Last updated 25 days ago --- # Table of Contents | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/overview/table-of-contents#want-to-become-a-frontend-provider) Want to become a Frontend provider? -------------------------------------------------------------------------------------------------------------------------------------- [Exchanges (Frontend Builders)](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders) [Perps - Settlement Costs](https://docs.symm.io/building-on-symmio/trading-fees/perps-settlement-costs) [hashtag](https://docs.symm.io/overview/table-of-contents#want-to-become-an-lp) Want to become an LP? ---------------------------------------------------------------------------------------------------------- [Solving for Symmio](https://docs.symm.io/building-on-symmio/solving-for-symmio) [hashtag](https://docs.symm.io/overview/table-of-contents#want-to-audit-bug-bounty-us) Want to audit / bug bounty us? -------------------------------------------------------------------------------------------------------------------------- [Technical Documentation](https://docs.symm.io/protocol-architecture/technical-documentation) [Audits](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits) [Bug bounty / Coverage](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/bug-bounty-coverage) [hashtag](https://docs.symm.io/overview/table-of-contents#want-to-understand-the-system-and-write-an-article) Want to understand the system and write an article? ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- [PreviousIntroductionchevron-left](https://docs.symm.io/) [NextSymmio Foundationchevron-right](https://docs.symm.io/token-information/symmio-foundation) Last updated 1 year ago * [Want to become a Frontend provider?](https://docs.symm.io/overview/table-of-contents#want-to-become-a-frontend-provider) * [Want to become an LP?](https://docs.symm.io/overview/table-of-contents#want-to-become-an-lp) * [Want to audit / bug bounty us?](https://docs.symm.io/overview/table-of-contents#want-to-audit-bug-bounty-us) * [Want to understand the system and write an article?](https://docs.symm.io/overview/table-of-contents#want-to-understand-the-system-and-write-an-article) sun-brightdesktopmoon sun-brightdesktopmoon --- # Symmio Foundation | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/token-information/symmio-foundation#all-official-information-related-to) All official information related to ------------------------------------------------------------------------------------------------------------------------------------------------ * **SYMM token** * **Points Program** * **Utility** * **Governance mechanisms** * **Distribution details** * **Development plans & Future Roadmaps** and any associated updates is available exclusively through the following Symmio Foundation resources: 1. [**symmio.foundation**arrow-up-right](https://symmio.foundation/) Visit the Symmio Foundation's official website for high-level overviews, announcements, and foundational insights about the $SYMM token and the ecosystem. 2. [**docs.symmio.foundation**arrow-up-right](https://docs.symmio.foundation/) Explore the comprehensive documentation hub for in-depth details, technical specifications, and token-related policies. These platforms are the sole authoritative sources for $SYMM token information. Please refer to these sites to ensure you have the most accurate, up-to-date, and reliable details about the $SYMM token and its role within the Symmio ecosystem. For any further inquiries, you can reach out to the Symmio team through the official communication channels listed on these sites. [PreviousTable of Contentschevron-left](https://docs.symm.io/overview/table-of-contents) [NextProtocol Introductionchevron-right](https://docs.symm.io/protocol-architecture/protocol-introduction) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Documentation for Traders | SYMMIO Protocol Gitbook [Concepts in SYMMIOchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio) [Learn how to build a Trading Bot using SYMMIOchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio) [Interacting with SYMMIO's Contractschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts) [PreviousSymmio Whitepaperchevron-left](https://docs.symm.io/protocol-architecture/symmio-whitepaper) [NextConcepts in SYMMIOchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio) sun-brightdesktopmoon sun-brightdesktopmoon --- # Symmio Whitepaper | SYMMIO Protocol Gitbook circle-info #### [hashtag](https://docs.symm.io/protocol-architecture/symmio-whitepaper#preamble) Preamble The Symmio system is continually evolving, and with it, our understanding and application of its potential. As we implement a fully trustless clearing system, we recognize the challenges that drive further improvements and expand our knowledge. We are eager to share a glimpse into something we've been fervently working on. It is important to note that both our whitepaper and our protocol are works in progress. As Symmio evolves, our whitepaper will be continually refined and updated. While it already provides an overview of our long-term vision, practical implementation, and future concepts, it represents just the tip of the iceberg. Additional publications, including SYMM v2.0, Netting, and ACOs, are scheduled to follow in 2024 and 2025 as our research progresses. Your interest fuels our commitment to excellence. As you read this version, please know that we are equally excited to present further research to you very soon. [hashtag](https://docs.symm.io/protocol-architecture/symmio-whitepaper#full-whitepaper-is-available-on-github) Full Whitepaper is available on github: ----------------------------------------------------------------------------------------------------------------------------------------------------------- [https://github.com/SYMM-IO/docs/blob/main/Whitepaper/SYMMIO\_paper\_0\_8.pdfarrow-up-right](https://github.com/SYMM-IO/docs/blob/main/Whitepaper/SYMMIO_paper_0_8.pdf) [PreviousProtocol Introductionchevron-left](https://docs.symm.io/protocol-architecture/protocol-introduction) [NextDocumentation for Traderschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders) Last updated 7 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Protocol Introduction | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/protocol-introduction#the-gateway-to-otc-derivatives) The Gateway to OTC derivatives ---------------------------------------------------------------------------------------------------------------------------------------------- **S‍ymmio allows anyone to permissionlessly** issue and trade any asset **with infinite leverage, in every direction.** The only DeFi primitive this industry needs. For example through our engine solvers can create: chevron-right**List of potential Assets**[hashtag](https://docs.symm.io/protocol-architecture/protocol-introduction#list-of-potential-assets) * **Cryptocurrency Futures / Perpetuals / Options, Stocks & Equities** * **Low-Cap Perpetuals, Bonds, Yield-Swaps, Low-Cap Options** * **Forward Rate Swaps, Commodities, Volatility Indices, Real Estate Indexes** * **FX Pairs, Inflation-Protected Assets, Basket Indices** * **ETFs, Options, Carbon Credits, Weather Markets** * **Energy Contracts, Macroeconomic Indicators, Credit Default Swaps** * **NFT Floor Prices, IPO Exposure, Metaverse Land Parcels, Prediction Markets** * **Election Outcomes, Sporting Events** O**r any other asset not listed here, with any possible price function.** Learn: [How to Add a Market as a Solver](https://docs.symm.io/protocol-architecture/documentation-for-solvers/how-to-add-a-market-as-a-solver) [hashtag](https://docs.symm.io/protocol-architecture/protocol-introduction#interested-in) **Interested in:** ----------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/protocol-introduction#trading-on-an-existing-frontend) **Trading on an existing frontend?** ### [hashtag](https://docs.symm.io/protocol-architecture/protocol-introduction#learning-about-how-trading-works-in-symmio) Learning about how trading works in SYMMIO? * How SYMMIO's intent-based system works * Market vs Limit Orders in SYMMIO * How Funding Rates are charged in SYMMIO * Liquidation details in SYMMIO * Querying on-chain data and interacting with contracts * Higher Level Architecture Start here: [Documentation for Traders: SYMMIO Concepts](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio) ### [hashtag](https://docs.symm.io/protocol-architecture/protocol-introduction#building-a-trading-bot) Building a trading bot? * Trade execution flows * Fetching trade parameters from solvers * Encoding and formatting on-chain transactions Start here: [Learn how to build a Trading Bot using SYMMIO](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio) ### [hashtag](https://docs.symm.io/protocol-architecture/protocol-introduction#becoming-a-frontend-builder) Becoming a Frontend Builder? * Frontend Builder setup * Deploying a MultiAccount contract * Frontend SDK * Supporting Instant Trading & Instant Withdrawal Start Here: [Frontend Builder Docs](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/frontend-builder-introduction) ### [hashtag](https://docs.symm.io/protocol-architecture/protocol-introduction#becoming-a-solver-on-symmio) Becoming a Solver on SYMMIO? * Solver API requirements * Offering New Markets as a Solver * Conditional & instant order support * Testnet & deployment environment Start Here: [Documentation for Solvers](https://docs.symm.io/protocol-architecture/documentation-for-solvers) ### [hashtag](https://docs.symm.io/protocol-architecture/protocol-introduction#contracts-addresses-and-endpoints) **Contracts Addresses and Endpoints?** * Frontend Affiliate addresses * Diamond contract addresses * Solver API endpoints and documentation Check the Reference: [Contract Addresses](https://docs.symm.io/protocol-architecture/contract-addresses) & [API endpoints](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints) . ### [hashtag](https://docs.symm.io/protocol-architecture/protocol-introduction#deeper-dive-into-symmios-architecture) Deeper Dive into SYMMIO's Architecture? * Detailed Contract Documentation * Muon API Endpoints * SYMMIO Diamond SDK Check [Contract Architecture Details](https://docs.symm.io/protocol-architecture/architecture-deep-dive) Offering new markets on SYMMIO? start by setting up a solver [Solver Docs](https://docs.symm.io/protocol-architecture/documentation-for-solvers/solver-docs) * understand the whole architecture? [Technical Documentation](https://docs.symm.io/protocol-architecture/technical-documentation) * Become a Frontend Builder and offer existing markets? [Building an Application with SYMMIO](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio) & [Frontend Builder Introduction](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/frontend-builder-introduction) * Trade existing markets on a frontend? [Exchanges (Frontend Builders)](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders) & [https://symm.io/frontendsarrow-up-right](https://symm.io/frontends) [PreviousSymmio Foundationchevron-left](https://docs.symm.io/token-information/symmio-foundation) [NextSymmio Whitepaperchevron-right](https://docs.symm.io/protocol-architecture/symmio-whitepaper) Last updated 25 days ago * [The Gateway to OTC derivatives](https://docs.symm.io/protocol-architecture/protocol-introduction#the-gateway-to-otc-derivatives) * [Interested in:](https://docs.symm.io/protocol-architecture/protocol-introduction#interested-in) * [Trading on an existing frontend?](https://docs.symm.io/protocol-architecture/protocol-introduction#trading-on-an-existing-frontend) * [Learning about how trading works in SYMMIO?](https://docs.symm.io/protocol-architecture/protocol-introduction#learning-about-how-trading-works-in-symmio) * [Building a trading bot?](https://docs.symm.io/protocol-architecture/protocol-introduction#building-a-trading-bot) * [Becoming a Frontend Builder?](https://docs.symm.io/protocol-architecture/protocol-introduction#becoming-a-frontend-builder) * [Becoming a Solver on SYMMIO?](https://docs.symm.io/protocol-architecture/protocol-introduction#becoming-a-solver-on-symmio) * [Contracts Addresses and Endpoints?](https://docs.symm.io/protocol-architecture/protocol-introduction#contracts-addresses-and-endpoints) * [Deeper Dive into SYMMIO's Architecture?](https://docs.symm.io/protocol-architecture/protocol-introduction#deeper-dive-into-symmios-architecture) sun-brightdesktopmoon sun-brightdesktopmoon --- # Concepts in SYMMIO | SYMMIO Protocol Gitbook [Intent-Based Tradingchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/intent-based-trading) [Market vs. Limit Orderschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/market-vs.-limit-orders) [Using Take Profit and Stop Losschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/using-take-profit-and-stop-loss) [Force Closing Positionschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/force-closing-positions) [Liquidationschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/liquidations) [Instant Tradingchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/instant-trading) [Withdrawalschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/withdrawals) [Settlement (0.8.4)chevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/settlement-0.8.4) [Funding Rates (0.8.4)chevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/funding-rates-0.8.4) [PreviousDocumentation for Traderschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders) [NextIntent-Based Tradingchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/intent-based-trading) sun-brightdesktopmoon sun-brightdesktopmoon --- # Withdrawals | SYMMIO Protocol Gitbook When you’re trading on SYMMIO, your funds sit inside the protocol rather than directly in your wallet. You can deposit in instantly and trade as much as you like, the only time there’s a delay is when you want to withdraw back out to your wallet (or to another EOA). SYMMIO uses a **12-hour withdrawal cooldown**. Once you request a withdrawal (after deallocating funds from your trading sub-accounts), those funds are locked for 12 hours before they can leave the system. You can think of this like the withdrawal delay on an optimistic rollup. The reason for this is safety. If something goes wrong — a bug, a malicious solver, or an attack that tries to move funds out quickly — the cooldown gives the protocol’s monitoring and fraud-checking systems time to react. During that window, suspicious activity can be detected, users can be suspended and damage can be contained. For normal traders, this just means: * You can **trade instantly**. * You can **deposit instantly**. * But when you withdraw, there is a **12-hour delay** before the funds land back in your wallet. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/withdrawals#instant-withdrawals-via-bridges) Instant withdrawals via bridges If you need funds right now, you don’t have to wait the full twelve hours yourself. [Bridges](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/bridge-facet-0.8.4) offer fast/instant withdrawals. The idea is: 1. You transfer funds to the bridge’s address inside SYMMIO. 2. The bridge transfers the same amount (minus a small fee) immediately. 3. The bridge then waits out the 12-hour cooldown on your behalf and receives the funds later. From your perspective, it feels like an instant withdrawal with a small service fee, while the cooldown and risk are handled by the bridge. [PreviousInstant Tradingchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/instant-trading) [NextSettlement (0.8.4)chevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/settlement-0.8.4) Last updated 2 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Settlement (0.8.4) | SYMMIO Protocol Gitbook When you trade on SYMMIO, your positions earn or lose money over time. That profit or loss is called unrealized PnL. It exists on paper, but it isn’t yet locked in as realized PnL. Separately, you also have an allocated balance: real collateral that can be used to pay for losses, open new positions, or be withdrawn. The protocol requires this allocated balance to remain sufficient at all times, which means you can’t close a losing trade unless you have enough realized collateral to cover the loss. Sometimes a trader is profitable overall but still gets blocked from closing a losing position, because all of those profits are still unrealized inside open positions. Settlement is the mechanism that converts some of those unrealized gains into usable balance. Let's illustrate settling unrealized profit works with an example: **Scenario** **Bob** (Party A) has three open positions: 1. **Position 1** with **Rasa Hedger** (Party B1): * **Unrealized Profit**: **$300** * **Quote ID**: `1` 2. **Position 2** with **PerpsHub Hedger** (Party B2): * **Unrealized Profit**: **$100** * **Quote ID**: `2` 3. **Position 3** with **PerpsHub Hedger** (Party B2): * **Unrealized Loss**: **$250** * **Quote ID**: `3` Bob's is technically $150 in profit, and wants to close **Position 3**, which has an unrealized loss of $250. However, since Bob has insufficient **allocated balance**, he cannot cover this loss upon closing. In situations like this, the solver can step in and unlock the necessary funds. PerpsHub submits a signed message from Muon attesting to the current market prices and the unrealized profits and losses across Bob’s positions. The contract verifies the signature and checks that everyone remains solvent. Upon settling, $150 profit for Position1 and $100 profit for Position2 are realized. After settlement, Bob's allocated balance is $250, with Position2's profit fully settled, and Position1's profit partially settled ($150) Position3 remains unchanged, and PerpsHub can now successfully fill the close request for Position3, as Bob has sufficient allocated balance ($250) to cover the loss ($250). Now Bob has $250 of spendable collateral, and PerpsHub can safely close the losing position. Nothing in the system breaks, no one takes on uncollateralized risk, and Bob isn’t trapped waiting for his losing trade to recover. This settlement process has several important protections built in. The updated prices must always lie between the original entry price and the signed current price, neither side of the trade is allowed to end up insolvent as a result of settlement and multiple positions can be settled at once, allowing a solver to quickly free up collateral across many trades if needed. More details on settlement can be found [here](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/settlement-facet-0.8.4) . [PreviousWithdrawalschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/withdrawals) [NextFunding Rates (0.8.4)chevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/funding-rates-0.8.4) Last updated 25 days ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Intent-Based Trading | SYMMIO Protocol Gitbook Most crypto derivatives today are traded on order-book exchanges. Traders place bids and asks on a shared book, and a matching engine decides when two orders meet. Instead of using a centralized order book, traders on SYMMIO express intents. An intent is simply a request that says: _“I want to go long or short this market, here is my price, my size, and the collateral I’m using.”_ When a trader submits this intent, it becomes visible to a network of independent counterparties called [**solvers**](https://docs.symm.io/protocol-architecture/glossary) . Each solver can decide whether they want to take the other side of that trade. So rather than fighting for priority in a centralized orderbook, traders using SYMMIO simply declare what they want and the market comes to them. This model removes the need for a centralized matching engine and makes the system permissionless, flexible, and peer-to-peer. It allows anyone to create and trade derivatives in a trustless manner, without relying on a central exchange. ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252Fqav9o9qs3DYgrYx34z8D%252FSymmioDocsV0.8.4%2520%289%29.png%3Falt%3Dmedia%26token%3Dcc864215-8690-4ef6-8cc4-f96b38cbff87&width=768&dpr=3&quality=100&sign=1c23b9be&sv=2) To make this possible, SYMMIO introduces three main roles: * Party A: the trader who creates an intent. * [Party B](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/partyb) : also called the solver or hedger, who chooses to accept that trade. * Liquidators: impartial actors who monitor positions and step in if collateral falls below safe levels. circle-info See the [Glossary](https://docs.symm.io/protocol-architecture/glossary) for more information. When a solver accepts a trader’s intent, the position opens on-chain, with collateral from both parties locked into the protocol. When the user wishes to close his position, he simply declares an intent to close his position, the solver handles the close request, and both parties' balances are updated. [PreviousConcepts in SYMMIOchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio) [NextMarket vs. Limit Orderschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/market-vs.-limit-orders) Last updated 29 days ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Instant Trading | SYMMIO Protocol Gitbook Usually, when trading on-chain, every action needs a wallet signature and a network confirmation: to open a trade, close a trade, cancel etc. That’s secure, but it can feel slow and clunky, especially if you’re used to the speed of execution on centralized exchanges. Instant Trading on SYMMIO is a way to keep the same trustless backend while making the trading experience feel almost as fast as a CEX. Instead of signing every single trade, you set up a secure “session” with a solver once, and they can then execute specific actions on your behalf, within strict limits you control. If you've traded on one of our affiliate [frontendsarrow-up-right](https://www.symm.io/frontends) , they will guide you to create a sub-account when you first sign up and deposit collateral into that, rather than trade directly from your wallet. From this sub-account, a a solver address can be approved to call a small set of functions for you, like opening positions, requesting closes, cancelling quotes, or allocating collateral. You do this by confirming a single on-chain transaction from your wallet that grants those permissions to the solver for your chosen sub-account. The delegation is function-level, so the solver can’t do anything outside what you’ve explicitly allowed. This access can also be revoked on-chain. See more information [here](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/multiaccount-0.8.4) . Once delegation is in place, the frontend guides you through a one-time login. You'll sign a message that proves you control the sub-account and agree to start an instant-trading session. The solver verifies this signature and issues an access token to the frontend. That token is then attached to your API requests, so when you click “Open” or “Close” in the UI, the solver can immediately act on your behalf using its delegated access. Under the hood, the solver is still performing the usual risk checks and on-chain calls, but from your trades are confirmed almost instantly, with on-chain settlement following shortly after. Delegation happens through the [MultiAccount](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/multiaccount-0.8.4) contract, so only the sub-account owner can grant or revoke access, and only for the exact functions you’ve chosen. There is a two-step revocation process: you first propose to revoke access, then, after a short cooldown, you complete the revocation. This gives solvers enough notice not to be rug-pulled mid-flow, while still letting you take back control whenever you want. On the solver side, access tokens have an expiration time, and every instant action still goes through balance checks, PnL checks, and normal SYMMIO risk logic before anything is sent on-chain. [PreviousLiquidationschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/liquidations) [NextWithdrawalschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/withdrawals) Last updated 1 month ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Force Closing Positions | SYMMIO Protocol Gitbook In the cases where the counterparty you’re trading with might go unresponsive or refuse to act when it’s time to close or cancel, traders have the ability to force cancel quotes or positions. These force actions help keep the system fair and safe for everyone. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/force-closing-positions#when-force-actions-help) When force actions help * If you asked to cancel a quote and the solver never responded, you can trigger `forceCancelQuote`**,** which refunds your locked funds so you aren’t stuck with a stale quote. * If you requested to close a position but the solver didn’t act, you can call `forceCancelCloseRequest` to restore the position to active, giving you the option to try again or choose a different solver. * If the market has moved and your requested close conditions were met, but the solver didn’t finalize the close, you can use `forceClosePosition`. This ends the trade and locks in a fair close price, even if the solver is ignoring you. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/force-closing-positions#force-closing-a-position) Force Closing a Position Force actions are permissionless: once the conditions are met, anyone can trigger them on-chain. For a position to be force closed, the user needs to provide a [signed price signature](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/force-actions-facet-0.8.4) (`HighLowPriceSig`) from the Muon network. That signature includes the highest, lowest and average price over a time window, plus each party’s unrealized PnL at the end of that window. The protocol checks that enough time has passed since the user asked to close (a grace period, so the solver had a fair chance to respond) and that your close request hasn’t expired. It also checks that the market actually moved through your requested close price by a safety margin: for a long, the price must have gone high enough; for a short, it must have gone low enough. If everything checks out, the position is closed. The force close price is guaranteed to be at least the `requestedClosePrice` plus a penalty bonus. However, if the market average during that time window was even better than the penalty price, PartyA gets the market average instead. circle-info You can check the details of the Force Actions functions [here](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/force-actions-facet-0.8.4) . [PreviousUsing Take Profit and Stop Losschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/using-take-profit-and-stop-loss) [NextLiquidationschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/liquidations) Last updated 25 days ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Using Take Profit and Stop Loss | SYMMIO Protocol Gitbook Most frontend builders on SYMMIO give you a way to set take profit (TP) and stop loss (SL) levels, so you don’t have to sit and watch the chart all day. When your target or safety level is reached, the system will try to close your position for you. Under the hood, this can work in two main ways: * The frontend asks you to [delegate permission](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/delegating-access-to-the-solver) to a small service that is allowed to request closes on your behalf when certain price conditions are met, or the frontend application talks directly to a solver’s [Conditional orders API](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders) , and the solver manages TP/SL for you. Both approaches end up doing the same thing from your perspective: when price hits your TP or SL, a close request is sent for your position. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/using-take-profit-and-stop-loss#how-it-works-for-you-as-a-trader) How it works for you as a trader The exact UI will differ between frontends, but in most cases it will follow this pattern: #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/using-take-profit-and-stop-loss#open-a-position) **Open a position** Trade as usual. Once your position is open, go to the **“**Positions**”** or **“**Open Positions**”** tab of the app. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/using-take-profit-and-stop-loss#find-the-tp-sl-controls) **Find the TP/SL controls** Next to your position, you’ll see a TP/SL button or a settings icon. Click it to open the take-profit / stop-loss panel. ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FnN2vt2y1xH8i3VDaxHQa%252Fimage.png%3Falt%3Dmedia%26token%3D1b561234-4696-4660-99f0-ecdcacd82877&width=768&dpr=3&quality=100&sign=8feeaf06&sv=2) Setting a TP/SL on IntentX #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/using-take-profit-and-stop-loss#approve-tp-sl-control) **Approve TP/SL control** The first time you set up TP/SL, you’ll usually be asked to **approve** either conditional order functionality or instant trading, which both enable conditional order management. This approval lets the frontend or the solver request to close your position for you when the conditions you set are met. circle-info You stay in control of your funds: the service cannot withdraw or move your money, it can only send the same close requests you could send yourself. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/using-take-profit-and-stop-loss#choose-your-take-profit-and-stop-loss) **Choose your Take Profit and Stop Loss** Once TP/SL is enabled, you can set: * A Take Profit level – where you’re happy to lock in gains * A Stop Loss level – where you want to cut the trade to cap downside Most frontends will let you use percentage-based settings or enter exact prices if you already know your target and invalidation levels. ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FfUDWqSrFYvjPcmfZaT0C%252Fimage.png%3Falt%3Dmedia%26token%3D841e7348-ca69-4bde-bec2-aeba7fa09983&width=768&dpr=3&quality=100&sign=e3a1428&sv=2) Setting a TP/SL on IntentX Behind the scenes, the app will translate your choices into a conditional order payload, including the **trigger price** (where TP/SL should activate), and the minimum acceptable execution price, which builds in some slippage protection. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/using-take-profit-and-stop-loss#confirm-and-save) **Confirm and save** After you’ve chosen your levels, confirm in the UI. From this point on, as long as your position remains open and your TP/SL conditions are valid, the system will watch the market and attempt to close your trade when your thresholds are reached. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/using-take-profit-and-stop-loss#adjust-or-remove-later) **Adjust or remove later** You can always come back to the same TP/SL panel to move your take profit higher or lower, tighten or loosen your stop loss, or cancel the TP/SL off completely. circle-info Refer to the specific frontend application's documentation for any discrepancies. [PreviousMarket vs. Limit Orderschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/market-vs.-limit-orders) [NextForce Closing Positionschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/force-closing-positions) Last updated 25 days ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Liquidations | SYMMIO Protocol Gitbook Liquidation is what happens when an account no longer has enough collateral to safely support its positions. To understand how it works in SYMMIO, it helps to first look at how your collateral is tracked. When you send a quote, the margin required for that position moves into a **pending** state. You can’t use that amount to open other trades, but it still counts as part of your allocated balance when the system checks if you’re solvent. Once a solver accepts your quote and the position opens, that margin becomes **locked**: it actively backs your open trade. Anything not pending or locked is your **free balance**. All of your positions on SYMMIO are treated as **cross margin**. That means your entire allocated balance, across all positions and pending quotes, works together to support your risk. As your unrealized PnL (UPnL) changes, the system leans on these collateral sources in order: first your locked margin, then your free balance, and finally your pending locked amounts. If your total UPnL is still above the lowest allowed threshold, you’re safe. But if losses grow so large that even your pending locked funds are not enough, the account is considered unsafe and liquidation is triggered. Because the system is cross-margin, **Party A is liquidated as a whole**. All of Party A’s open positions and outstanding quotes are moved into a liquidated state at once — in practical terms, everything is closed or cancelled together. When this happens, special actors called **liquidators** step in. They use signed data from the Muon network to prove your total losses and the prices of the markets you’re trading. The protocol then closes your positions, redistributes collateral between you and your counterparties, and pays a small fee to the liquidator as a reward for keeping the system safe. Your CVA and margins are used according to the rules of the system. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/liquidations#example) Example To illustrate this process, let's use an example: Imagine Alice (Party A) has $1,000 allocated for trading. She's got multiple positions open, all cross-margined together. Let's say she's got: * $500 locked in active positions * $200 in pending locked (quotes waiting to be filled) * $300 free and available * $100 in Locked CVA ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252Fd8TZdcxuIVEOQToHssuQ%252FSymmioDocsV0.8.4%2520%2810%29.png%3Falt%3Dmedia%26token%3D28e83a6a-d54d-495b-824b-e1151d872204&width=768&dpr=3&quality=100&sign=edf651de&sv=2) Stage 1: Alice's has manageable losses. ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252Fa5eq86jKVtnVw7cfCUBO%252FSymmioDocsV0.8.4%2520%2811%29.png%3Falt%3Dmedia%26token%3Ddfab900a-36e8-4023-acd6-085bc4dafe3a&width=768&dpr=3&quality=100&sign=776c0790&sv=2) Stage 2: Alice suffers deeper losses ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252Fj7URndQmYbnVls2ph8fT%252FSymmioDocsV0.8.4%2520%2812%29.png%3Falt%3Dmedia%26token%3D7daa007e-b9da-4451-8a36-55aac784a81c&width=768&dpr=3&quality=100&sign=13dbe7e&sv=2) Stage 3: Alice has critical losses and is about to be liquidated ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FsHjga1qbHdIsroIrW1Cn%252FSymmioDocsV0.8.4%2520%2813%29.png%3Falt%3Dmedia%26token%3D27d51949-876e-4440-b354-9227fc1891ab&width=768&dpr=3&quality=100&sign=61c0b5cb&sv=2) Stage 4: Alice is liquidated Party B (the solver) can also be liquidated, but in a more targeted way. If a solver’s allocated balance is not enough relative to a specific Party A, they can be liquidated just for that relationship. [PreviousForce Closing Positionschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/force-closing-positions) [NextInstant Tradingchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/instant-trading) Last updated 2 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Funding Rates (0.8.4) | SYMMIO Protocol Gitbook ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/funding-rates-0.8.4#funding-rates-in-symmio) Funding Rates in SYMMIO Perpetual futures never settle, so their price can drift away from the real market price. **Funding rates** are a small payment exchanged between longs and shorts to keep prices aligned. If longs are dominating and the perp price is above spot → **longs pay shorts**. If shorts are dominating and the perp price is below spot → **shorts pay longs**. This makes holding the more “advantaged” side a little more expensive, nudging prices back toward the real market value. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/funding-rates-0.8.4#how-it-works-on-symmio) How it works on SYMMIO Every symbol on SYMMIO has it's own funding rate, which is applied at the end of periods, called **epochs**. When an epoch ends, positions pay (or receive) funding. On the contracts, this cycle's length is defined as the `fundingRateEpochDuration`. Solvers are responsible for charging funding during the symbol's `fundingRateWindowTime`, which is a short window either side of the epoch 'flip'. Example Symbol: Copy { "symbolId": "1", "name": "BTCUSDT", "isValid": true, "minAcceptableQuoteValue": "120000000000000000000", "minAcceptablePortionLF": "3000000000000000", "tradingFee": "3800000000000000", "maxLeverage": "100000000000000000000", "fundingRateEpochDuration": "14400", // <- 4 hours "fundingRateWindowTime": "420" // <- 7 minutes } When funding is applied, the protocol updates the `openedPrice` of your trade, simulating the effect of charging on the position, without actually transferring any tokens. The event is also logged on-chain, so you can always see when funding was charged and how much it affected your position. You can check the funding charges on your positions here: [![Logo](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2Fexplorer-symmio.vercel.app%2Ffavicon.ico%3Ffavicon.0b3bf435.ico&width=20&dpr=3&quality=100&sign=7831950&sv=2)Symmio - Explorerexplorer-symmio.vercel.appchevron-right](https://explorer-symmio.vercel.app/positions?page=0&size=10) ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FHnRntc7GkR92hsJNDDLp%252FSymmioDocsV0.8.4%2520%288%29.png%3Falt%3Dmedia%26token%3De4bbfcfd-cac5-4827-b664-a4a2cc304552&width=768&dpr=3&quality=100&sign=4c7ef681&sv=2) Explorer Preview circle-info Solvers are responsible for streaming the rates which they are applying in the next epoch, but they don't necessarily stream the epoch durations. Ultimately they can only charge during the window defined by the smart contracts, so always refer to the smart contracts to clarify epoch durations. [PreviousSettlement (0.8.4)chevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/settlement-0.8.4) [NextLearn how to build a Trading Bot using SYMMIOchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio) Last updated 25 days ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Market vs. Limit Orders | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/market-vs.-limit-orders#sending-a-quote) Sending a Quote --------------------------------------------------------------------------------------------------------------------------------------------------------------- When a trader wants to make a trade using SYMMIO, he calls `sendQuoteWithAffiliate()`. The trader must include a price, regardless of whether they want to create a Market Order or a Limit Order. Copy function sendQuoteWithAffiliate( address[] memory partyBsWhiteList, uint256 symbolId, PositionType positionType, OrderType orderType, uint256 price, uint256 quantity, uint256 cva, uint256 lf, uint256 partyAmm, uint256 partyBmm, uint256 maxFundingRate, uint256 deadline, address affiliate, SingleUpnlAndPriceSig memory upnlSig ) external returns (uint256); ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/market-vs.-limit-orders#limit-orders) Limit Orders Limit orders can be partially filled. The `price` passed is the exact price the trader wants to enter a position at, and the trading fee is calculated as a fraction of `requestedOpenPrice * quantity`. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/market-vs.-limit-orders#market-orders) Market orders Market orders must be filled in one go. Because the trader wants to enter the position immediately, the quote price is sent with some slippage, guaranteeing his entry. The [frontend](https://docs.symm.io/protocol-architecture/glossary) will handle the slippage calculation after the user sets his tolerance, which involves taking the oracle price from Muon and shifting it slightly depending on the position type (long or short). The shift accounts for the solver’s spread as well as any fluctuations in market price For market orders the trading fee is calculated as a fraction of the `oracle price * quantity`. When the counterparty accepts the quote, he must open the quote at an equal or better price than was first requested by the trader. For longs, this is a price below or equal to the requestedOpenPrice, and for shorts this is above or equal to the requested open price. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/market-vs.-limit-orders#closing-a-quote) Closing a Quote --------------------------------------------------------------------------------------------------------------------------------------------------------------- Similar to opening a quote, a **market** order must be fully closed, whereas a **limit** order can be partially closed. The same logic for market orders applies for closes: The user will set his slippage, and the frontend will calculate the appropriate closePrice. Here the logic is inverted, for long positions the `closePrice` is decreased; for shorts it’s increased. The trader can initiate a [force close](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/force-closing-positions) if the counterparty is unresponsive, and a sufficient cooldown period has passed. Force closes can **only** be performed on Limit orders. [PreviousIntent-Based Tradingchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/intent-based-trading) [NextUsing Take Profit and Stop Losschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/using-take-profit-and-stop-loss) Last updated 25 days ago * [Sending a Quote](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/market-vs.-limit-orders#sending-a-quote) * [Limit Orders](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/market-vs.-limit-orders#limit-orders) * [Market orders](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/market-vs.-limit-orders#market-orders) * [Closing a Quote](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/market-vs.-limit-orders#closing-a-quote) sun-brightdesktopmoon sun-brightdesktopmoon --- # Interacting with SYMMIO's Contracts | SYMMIO Protocol Gitbook [Closing a Positionchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/closing-a-position) [Instant Withdrawalchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/instant-withdrawal) [How to Query our Contractschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts) [PreviousFull Example Scriptchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/full-example-script) [NextClosing a Positionchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/closing-a-position) Last updated 25 days ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Learn how to build a Trading Bot using SYMMIO | SYMMIO Protocol Gitbook This guide provides a comprehensive walkthrough for building a trading bot that interacts via the SYMM protocol using Python. This guide will focus on using an affiliate's [MultiAccount](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/multiaccount-0.8.4) with [Instant Trading](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading) without relying on a frontend application. The full trading bot and example codes can all be found in this [repositoryarrow-up-right](https://github.com/academy17/symm_example_codes) . ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio#prerequisites) Prerequisites Before starting, ensure you have: * Python 3.8+ * A wallet with private key (for signing transactions) * A suitable RPC endpoint * Environment variables set up in a .env file [PreviousFunding Rates (0.8.4)chevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/funding-rates-0.8.4) [NextCreating a Sub-Accountchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/creating-a-sub-account) Last updated 5 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Closing a Position | SYMMIO Protocol Gitbook When the exit condition is met (`EXIT_PRICE`), we need to close the position. More information on this can be found [here](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/closing-a-quote-instant-close) . #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/closing-a-position#preparing-the-close-request) Preparing the Close Request Similar to opening a position, we need to fetch the price from Muon and apply slippage. For closing a long position, we apply negative slippage (0.99x the price): Copy # Fetch Muon price and apply -1% slippage (for long positions) muon_price = fetch_muon_price() close_price = str(muon_price * Decimal("0.99")) # 1% slippage for selling #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/closing-a-position#sending-the-close-request) Sending the Close Request Copy payload = { "quote_id": quote_id, "quantity_to_close": CONFIG["QUANTITY"], "close_price": close_price } response = requests.post(f"{HEDGER_URL}/instant_close", json=payload, headers=headers) #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/closing-a-position#verifying-the-close) Verifying the Close After sending the close request, we check the response status to ensure the position was closed successfully: Copy if response.status_code == 200: print("[CLOSE] Position closed successfully") return True else: print(f"[CLOSE] Error: {response.status_code}, {response.text}") return False [PreviousMonitoring Position Statuschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/monitoring-position-status) [NextFull Example Scriptchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/full-example-script) Last updated 1 month ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Opening a Position | SYMMIO Protocol Gitbook When the entry condition is met, we need to open a position using the solver's instant trading API. More details on this can be found [here](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/sending-a-quote-instant-open) . #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/opening-a-position#fetching-price-from-muon-oracle) Fetching Price from Muon Oracle For on-chain verification of price and solvency, we need to fetch the price and a signature from the Muon oracle: Copy def fetch_muon_price(): try: response = requests.get(MUON_URL) data = response.json() fetched_price_wei = data["result"]["data"]["result"]["price"] return Decimal(fetched_price_wei) / Decimal('1e18') except Exception as e: print(f"[ERROR] Failed to fetch Muon price: {e}") return None #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/opening-a-position#applying-slippage) Applying Slippage Since we're going LONG, we increase the price by 1% to ensure our order gets filled: Copy # For long positions, add 1% slippage adjusted_price = fetched_price * Decimal('1.01') #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/opening-a-position#preparing-trade-parameters) Preparing Trade Parameters We need to calculate collateral parameters based on the notional value and parameters returned from the `get_locked_params` solver endpoint. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/opening-a-position#sending-the-trade-request) Sending the Trade Request The API will return a temporary quote ID that we'll use to track our order. [PreviousMonitoring Pricechevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/monitoring-price) [NextSetting a Stop Losschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/setting-a-stop-loss) Last updated 1 month ago sun-brightdesktopmoon Copy def fetch_locked_params(): """Fetch locked parameters for the trade.""" try: response = requests.get(LOCKED_PARAMS_URL) response.raise_for_status() data = response.json() if data.get("message") == "Success": return data else: raise ValueError("Failed to fetch locked parameters") except Exception as e: print(f"[ERROR] Failed to fetch locked parameters: {e}") return None def calculate_normalized_locked_value(notional, locked_param, leverage, apply_leverage=True): """Compute normalized locked value for a given parameter.""" notional = Decimal(str(notional)) locked_param = Decimal(str(locked_param)) leverage = Decimal(str(leverage)) if apply_leverage: return str(notional * locked_param / (Decimal('100') * leverage)) else: return str(notional * locked_param / Decimal('100')) Copy trade_params = { "symbolId": CONFIG["SYMBOL_ID"], "positionType": CONFIG["POSITION_TYPE"], # 0 for long, 1 for short "orderType": 1, # 1 for market order (must be market since we're using instant actrions) "price": str(adjusted_price), "quantity": CONFIG["QUANTITY"], "cva": normalized_cva, "lf": normalized_lf, "partyAmm": normalized_party_amm, "partyBmm": '0', "maxFundingRate": CONFIG["MAX_FUNDING_RATE"], "deadline": deadline } response = requests.post(f"{HEDGER_URL}/instant_open", json=trade_params, headers=headers) sun-brightdesktopmoon --- # Monitoring Price | SYMMIO Protocol Gitbook The sample trading bot makes decisions based on price movements. Because the asset being traded is hedged with Binance it's appropriate to monitor the price using their endpoints. In our sample, we are executing a basic strategy: longing when price is below or equal to our defined `ENTRY_PRICE` and closing our position when the price is equal or above our `EXIT_PRICE`. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/monitoring-price#setting-up-price-monitoring) Setting Up Price Monitoring We define entry and exit prices in the configuration: Copy CONFIG = { "SYMBOL": "XRPUSDT", "ENTRY_PRICE": "3.05", # Enter when price falls below this "EXIT_PRICE": "3.1", # Exit when price rises above this "QUANTITY": "6", # ... other configuration options } #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/monitoring-price#monitoring-loop) Monitoring Loop The bot continuously monitors the price and compares it to our thresholds: Copy # Main trading loop while True: # Get current price from Binance current_price = get_binance_price(CONFIG["SYMBOL"]) # Check for entry conditions if not in_position and current_price <= entry_price: # Open a position # Check for exit conditions elif in_position and current_price >= exit_price: # Close the position time.sleep(CONFIG["POLL_INTERVAL"]) The `get_binance_price` function fetches the current price from Binance's API: [PreviousAuthenticating Tradeschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/authenticating-trades) [NextOpening a Positionchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/opening-a-position) Last updated 5 months ago sun-brightdesktopmoon Copy def get_binance_price(symbol): """Get the current price of a symbol from Binance.""" try: params = {"symbol": symbol} response = requests.get(BINANCE_API_URL, params=params) response.raise_for_status() data = response.json() price = Decimal(data["price"]) print(f"[PRICE] Current {symbol} price: {price}") return price except Exception as e: print(f"[ERROR] Failed to get Binance price: {e}") return None sun-brightdesktopmoon --- # Creating a Sub-Account | SYMMIO Protocol Gitbook ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/creating-a-sub-account#step-1-creating-a-sub-account) Step 1: Creating a Sub-Account A sub-account allows you to manage multiple trading accounts under one main wallet. This is done through an affiliate's [MultiAccount](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/multiaccount) contract. Contract addresses can be found here. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/creating-a-sub-account#how-to-create-a-sub-account) How to Create a Sub-Account To create a sub-account, we use the MultiAccount contract's `addAccount()` method, passing a name for the sub-account: Copy from dotenv import load_dotenv import os import json from web3 import Web3 load_dotenv() CONFIG = { "rpc_url": os.getenv("RPC_URL"), "private_key": os.getenv("PRIVATE_KEY"), "multiaccount_address": os.getenv("MULTIACCOUNT_ADDRESS"), } class MultiAccountClient: def __init__(self, config): self.config = config abi_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "abi", "MultiAccount.json")) with open(abi_path, "r") as abi_file: self.abi = json.load(abi_file) self.w3 = Web3(Web3.HTTPProvider(config["rpc_url"])) self.account = self.w3.eth.account.from_key(config["private_key"]) self.multiaccount = self.w3.eth.contract( address=Web3.to_checksum_address(config["multiaccount_address"]), abi=self.abi ) def add_account(self, name: str): """Add a new account and retrieve its address from the emitted event""" try: txn = self.multiaccount.functions.addAccount(name).build_transaction({ "from": self.account.address, "nonce": self.w3.eth.get_transaction_count(self.account.address, "pending"), "gas": 8000000, "gasPrice": self.w3.eth.gas_price, }) signed_txn = self.w3.eth.account.sign_transaction(txn, private_key=self.config["private_key"]) tx_hash = self.w3.eth.send_raw_transaction(signed_txn.raw_transaction) print(f"Transaction sent: {tx_hash.hex()}") receipt = self.w3.eth.wait_for_transaction_receipt(tx_hash) print("Transaction confirmed.") event_signature_hash = self.w3.keccak(text="AddAccount(address,address,string)").hex() for log in receipt.logs: if log.topics[0].hex() == event_signature_hash: decoded_event = self.multiaccount.events.AddAccount().process_log(log) account_address = decoded_event["args"]["account"] print(f"New account created: {account_address}") return account_address print("AddAccount event not found in transaction logs.") return None except Exception as e: print(f"Error adding account: {e}") raise def main(): """Main function to demonstrate adding an account""" client = MultiAccountClient(CONFIG) # Example: Name for the new account account_name = "sdk_client" # Replace with the desired account name new_account_address = client.add_account(account_name) if new_account_address: print(f"Successfully created account with address: {new_account_address}") else: print("Failed to retrieve the new account address.") if __name__ == "__main__": main() When the transaction is successful, a new account address that will be used for all your trading activities will be emitted by the contract. This address doesn't have its own private key - it's controlled by your main wallet. [PreviousLearn how to build a Trading Bot using SYMMIOchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio) [NextDepositing and Allocating Collateralchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/depositing-and-allocating-collateral) Last updated 5 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Monitoring Position Status | SYMMIO Protocol Gitbook After sending the trade request via the instant open endpoint, we must monitor its status to get the permanent quote ID (this is the QID which is stored on-chain). The endpoint for this is documented [here](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#instant-open-position) . #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/monitoring-position-status#polling-for-quote-status) Polling for Quote Status The temporary quote ID will be replaced with a permanent ID once the trade is confirmed: Copy def poll_quote_status(token, temp_quote_id): """Poll for the status of a quote until it gets a permanent ID.""" #In order to track the status of the quote, we will poll the /instant_open/{address} endpoint print(f"[STATUS] Starting to poll for quote status of temp ID: {temp_quote_id}") headers = { "Authorization": f"Bearer {token}" } max_attempts = 120 # 60 seconds (120 * 0.5s) attempts = 0 if isinstance(temp_quote_id, str) and temp_quote_id.startswith('-'): try: temp_quote_id = int(temp_quote_id) except ValueError: print(f"[STATUS] Warning: Could not convert temp_quote_id {temp_quote_id} to int") print(f"[STATUS] Looking for temp_quote_id: {temp_quote_id} (type: {type(temp_quote_id)})") while attempts < max_attempts: try: response = requests.get(STATUS_URL, headers=headers) if response.status_code != 200: print(f"[STATUS] Error: Response status {response.status_code}") print(f"[STATUS] Response text: {response.text}") attempts += 1 time.sleep(CONFIG["STATUS_POLL_INTERVAL"]) continue data = response.json() print(f"[STATUS] Poll attempt {attempts+1}/{max_attempts}") if not data: print("[STATUS] Empty response, waiting for next update...") attempts += 1 time.sleep(CONFIG["STATUS_POLL_INTERVAL"]) continue quotes = [] if isinstance(data, list): quotes = data elif isinstance(data, dict) and "quotes" in data: quotes = data["quotes"] if not quotes: print("[STATUS] No quotes found in response") attempts += 1 time.sleep(CONFIG["STATUS_POLL_INTERVAL"]) continue print(f"[STATUS] Found {len(quotes)} quotes to check") # Look for any quote with a positive quote_id (confirmed) for quote in quotes: quote_id = quote.get("quote_id") if isinstance(quote_id, str) and quote_id.isdigit(): quote_id = int(quote_id) if isinstance(quote_id, int) and quote_id > 0: print(f"[STATUS] ✓ CONFIRMED: Quote has permanent ID: {quote_id}") return quote_id attempts += 1 time.sleep(CONFIG["STATUS_POLL_INTERVAL"]) except Exception as e: print(f"[ERROR] Error polling quote status: {e}") traceback.print_exc() attempts += 1 time.sleep(CONFIG["STATUS_POLL_INTERVAL"]) print("[STATUS] ⚠ Timed out waiting for permanent quote ID") return None This approach looks for any quote with a positive ID, which indicates that the trade has been confirmed. [PreviousSetting a Stop Losschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/setting-a-stop-loss) [NextClosing a Positionchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/closing-a-position) Last updated 5 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Authenticating Trades | SYMMIO Protocol Gitbook ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/authenticating-trades#authentication-and-login) Authentication and Login To interact with a solver's [instant trading endpoints](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading) , you need to authenticate using Sign-In With Ethereum (SIWE). #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/authenticating-trades#siwe-authentication-process) SIWE Authentication Process 1. Request a nonce from the server 2. Create a SIWE message with the nonce 3. Sign the message with your wallet 4. Send the signature to the server to get an access token **Example Code:** Copy import os import requests import json from eth_account import Account from eth_account.messages import encode_defunct from dotenv import load_dotenv from datetime import datetime, timedelta, timezone load_dotenv() PRIVATE_KEY = os.getenv("PRIVATE_KEY") ACTIVE_ACCOUNT = os.getenv("SUB_ACCOUNT_ADDRESS") HEDGER_URL = os.getenv("HEDGER_URL") CHAIN_ID = int(os.getenv("CHAIN_ID", 42161)) DOMAIN = "localhost" ORIGIN = "http://localhost:3000" LOGIN_URI = f"{HEDGER_URL}/login" ISSUED_AT = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z" EXPIRATION_DATE = (datetime.now(timezone.utc) + timedelta(hours=2, minutes=30)).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z" wallet = Account.from_key(PRIVATE_KEY) def get_nonce(address: str) -> str: """Fetch the nonce for the active account from the server.""" url = f"{HEDGER_URL}/nonce/{address}" response = requests.get(url) response.raise_for_status() return response.json()["nonce"] def build_siwe_message(domain, address, statement, uri, version, chain_id, nonce, issued_at, expiration_time): """Build a SIWE message string following the EIP-4361 format.""" return f"""{domain} wants you to sign in with your Ethereum account: {address} {statement} URI: {uri} Version: {version} Chain ID: {chain_id} Nonce: {nonce} Issued At: {issued_at} Expiration Time: {expiration_time}""" def main(): try: print(f"\n[1/4] Wallet Address: {wallet.address}") print(f"[1.5/4] Active Account (Checksum): {ACTIVE_ACCOUNT}") nonce = get_nonce(ACTIVE_ACCOUNT) print(f"[2/4] Got nonce: {nonce}") message_string = build_siwe_message( domain=DOMAIN, address=wallet.address, statement=f"msg: {ACTIVE_ACCOUNT}", uri=LOGIN_URI, version="1", chain_id=CHAIN_ID, nonce=nonce, issued_at=ISSUED_AT, expiration_time=EXPIRATION_DATE ) print("\n[3/4] SIWE message to sign:\n", message_string) message = encode_defunct(text=message_string) signed_message = wallet.sign_message(message) signature = "0x" + signed_message.signature.hex() print("\nSignature:", signature) body = { "account_address": ACTIVE_ACCOUNT, "expiration_time": EXPIRATION_DATE, "issued_at": ISSUED_AT, "signature": signature, "nonce": nonce } print("body: ", body) headers = { "Content-Type": "application/json", "Origin": ORIGIN, "Referer": ORIGIN, } print("\n[4/4] Sending login request...") response = requests.post( LOGIN_URI, json=body, headers=headers ) if response.status_code != 200: print(f"Server response: {response.status_code}") print(f"Response text: {response.text}") response.raise_for_status() print("Login response:", response.json()) except Exception as e: print(f"Error in SIWE login flow: {e}") import traceback traceback.print_exc() if __name__ == "__main__": main() The access token will be used for all subsequent API requests. Multiple access tokens can be generated so this step can be done before every instant order if the token is not saved. [PreviousDelegating Access to the Solverchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/delegating-access-to-the-solver) [NextMonitoring Pricechevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/monitoring-price) Last updated 5 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Documentation for Frontend Builders | SYMMIO Protocol Gitbook [Setting up a Frontend with SYMMIOchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/setting-up-a-frontend-with-symmio) [MultiAccount Deployment Guidechevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/multiaccount-deployment-guide) [Building an Application with SYMMIOchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio) [Frontend Builder SDK Setup Guidechevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/frontend-builder-sdk-setup-guide) [Instant Trading for Frontend Builderschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-trading-for-frontend-builders) [Instant Withdrawal for Frontend Builderschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-withdrawal-for-frontend-builders) [PreviousHow to Query our Contractschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts) [NextSetting up a Frontend with SYMMIOchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/setting-up-a-frontend-with-symmio) sun-brightdesktopmoon sun-brightdesktopmoon --- # Instant Withdrawal | SYMMIO Protocol Gitbook An Instant Withdrawal lets you withdraw funds without waiting for the normal cooldown period, which is 12 hours. Instead, you select a fee option that matches how fast you want your withdrawal processed and withdraw funds through a bridge. This guide shows how to do this without using a frontend application. Instant withdrawals work in two steps : 1. **On-chain**: You transfer your allocated balance to a bridge. 2. **Off-chain**: You select a fee option, and the backend schedules the withdrawal to execution. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/instant-withdrawal#before-you-start) Before You Start You’ll need: * **Python 3.8** or newer * A wallet private key (used for signing and paying gas) * An RPC URL for the chain you are withdrawing from * The Python script from the reference repo * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/instant-withdrawal#setup) Setup Create and activate a virtual environment, then install dependencies: Copy python -m venv venv source venv/bin/activate pip install -r requirements.txt * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/instant-withdrawal#configure-.env) Configure .env The script reads configuration from a .env file. You’ll need to use the private key corresponding with the wallet that you wish to withdraw from, and an RPC provider: circle-info Withdrawing 1 USDC means passing `1000000` since on Base USDC has 6 decimals. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/instant-withdrawal#running-the-script) Running the Script From the project root: Once started, the script walks through all steps automatically. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/instant-withdrawal#what-the-script-does-step-by-step) What the Script Does (Step by Step) Below is the exact flow, mapped directly to the Python code. * * * #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/instant-withdrawal#id-1.-sign-in-with-your-wallet-siwe) 1\. Sign in with your wallet (SIWE) The script first proves wallet ownership using Sign-In With Ethereum and gets an access token. This gives it an **access token** so it can talk to the Instant Withdrawal backend. This token is required for all Instant Withdrawal API calls. * * * #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/instant-withdrawal#id-2.-lock-fee-options-for-your-withdrawal-amount) 2\. Lock fee options for your withdrawal amount Next, the script asks the backend for available fee options for a specific amount. This temporarily locks the options so rates can't change. * * * #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/instant-withdrawal#id-3.-deallocate-funds-from-trading-on-chain) 3\. Deallocate funds from trading (on-chain) If your funds are currently allocated to trading, they must be freed first. The script fetches a Muon uPNL signature, formats it for the contract and sends the transaction. This step must complete on-chain before continuing. * * * #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/instant-withdrawal#id-4.-transfer-funds-to-the-withdrawal-bridge-on-chain) 4\. Transfer funds to the withdrawal bridge (on-chain) Once funds are free, they are transferred into the Instant Withdrawal bridge. After confirmation, the script extracts a `transactionId` from the emitted event. This ID is required for the next step. * * * #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/instant-withdrawal#id-5.-fetch-pending-fee-policies) 5\. Fetch pending fee policies Now that the bridge transfer exists on-chain, the script fetches again the valid fee options tied to that transfer. * * * #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/instant-withdrawal#id-6.-select-a-fee-policy-and-schedule-the-withdrawal) 6\. Select a fee policy and schedule the withdrawal The script automatically picks the fastest option and submits it. Once this is done, the withdrawal is scheduled and will execute automatically. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/instant-withdrawal#reference-implementation) Reference Implementation -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [This repositoryarrow-up-right](https://github.com/academy17/instant_withdrawal_reference) contains a python script showcasing the full flow for Instant Withdrawal. [PreviousClosing a Positionchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/closing-a-position) [NextHow to Query our Contractschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts) Last updated 29 days ago * [Before You Start](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/instant-withdrawal#before-you-start) * [Setup](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/instant-withdrawal#setup) * [Configure .env](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/instant-withdrawal#configure-.env) * [Running the Script](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/instant-withdrawal#running-the-script) * [What the Script Does (Step by Step)](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/instant-withdrawal#what-the-script-does-step-by-step) * [Reference Implementation](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/instant-withdrawal#reference-implementation) sun-brightdesktopmoon Copy PRIVATE_KEY=0x... RPC_URL=https://... CHAIN_ID=8453 BASE_URL=https://instant-withdrawal-backend... Copy python instant_withdrawal.py Copy nonce = requests.post( f"{BASE_URL}/v1/auth/nonce", json={"address": wallet_address} ).json()["nonce"] Copy message = requests.get( f"{BASE_URL}/v1/auth/sign-in-message", params={"address": wallet_address, "domain": DOMAIN, "uri": ORIGIN} ).json()["message"] Copy signed = account.sign_message(encode_defunct(text=message)) Copy token = requests.post( f"{BASE_URL}/v1/auth/login", json={"message": payload, "signature": signature} ).json()["accessToken"] Copy options = requests.post( f"{BASE_URL}/v1/fee-options", params={"account": subaccount, "amount": AMOUNT}, headers={"Authorization": f"Bearer {token}"} ).json()["options"] Copy call_data = diamond.functions.deallocate( amount, upnl_sig )._encode_transaction_data() Copy tx = multi_account.functions._call( subaccount, [call_data] ) Copy call_data = diamond.functions.transferToBridge( amount, BRIDGE_ADDRESS )._encode_transaction_data() Copy tx = multi_account.functions._call( subaccount, [call_data] ) Copy policies = requests.get( f"{BASE_URL}/v1/pending-fee-policy/{subaccount}", headers={"Authorization": f"Bearer {token}"} ).json()["policies"] Copy fastest = min(policies, key=lambda p: p["cooldown"]) Copy result = requests.post( f"{BASE_URL}/v1/select-fee-policy", json={ "symmioBridgeId": bridge_id, "cooldown": fastest["cooldown"], "feeAmount": fastest["fee"], }, headers={"Authorization": f"Bearer {token}"} ).json() sun-brightdesktopmoon --- # Setting up a Frontend with SYMMIO | SYMMIO Protocol Gitbook To integrate a frontend with SYMMIO, follow the steps below. This serves as a general outline assuming familiarity with the SYMMIO ecosystem, smart contract interaction, and frontend development. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/setting-up-a-frontend-with-symmio#id-1.-clone-or-build-the-frontend-application) **1\. Clone or Build the Frontend Application** ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ The first step is to either clone the official SYMMIO Frontend SDK repository or create your own custom frontend application using the provided SDK and documentation. The SDK simplifies the process of interacting with SYMMIO's APIs and smart contracts. Refer to the [Frontend SDK Setup Guide](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/frontend-builder-sdk-setup-guide) for detailed instructions on cloning and configuring the SDK or creating your own implementation. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/setting-up-a-frontend-with-symmio#id-2.-deploy-a-multiaccount-contract) **2\. Deploy a MultiAccount Contract** ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ To support useful user functionality and track fees, you’ll need to deploy a MultiAccount contract following the standards set by SYMMIO. The MultiAccount contract plays a vital role in managing user interactions with SYMMIO’s smart contracts: * **User Volume Tracking**: MultiAccount helps track trading volume at a user level, providing insights into user activity and engagement. * **Sub-Accounts for Trading**: Users can create sub-accounts under their primary account for better organization and management of their trades. * **Automated Fee Claiming**: Users interact with the `sendQuoteWithAffiliate()` function by passing the MultiAccount address of the frontend. This enables frontend builders to automatically claim fees for trades routed through them, streamlining the process for both users and the platform. Refer to the [MultiAccount Deployment Guide](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/multiaccount-deployment-guide) for detailed instructions on deploying and configuring the contract. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/setting-up-a-frontend-with-symmio#id-3.-provide-frontend-application-urls-for-whitelisting) **3\. Provide Frontend Application URLs for Whitelisting** ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Once your frontend application is ready for deployment, you’ll need to share the URL(s) with the team for whitelisting. Provide the production frontend address to ensure it is added to the CORS whitelist. If you have test or staging environments, you can provide their URLs as well, and the team will include them in the whitelist for development and testing. Whitelisting your frontend is a critical step for enabling features like Instant Execution, where user requests are processed rapidly via delegated access. [PreviousDocumentation for Frontend Builderschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders) [NextMultiAccount Deployment Guidechevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/multiaccount-deployment-guide) Last updated 29 days ago * [1\. Clone or Build the Frontend Application](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/setting-up-a-frontend-with-symmio#id-1.-clone-or-build-the-frontend-application) * [2\. Deploy a MultiAccount Contract](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/setting-up-a-frontend-with-symmio#id-2.-deploy-a-multiaccount-contract) * [3\. Provide Frontend Application URLs for Whitelisting](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/setting-up-a-frontend-with-symmio#id-3.-provide-frontend-application-urls-for-whitelisting) sun-brightdesktopmoon sun-brightdesktopmoon --- # Closing a Position | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/closing-a-position#how-to-request-to-close-a-position-on-symm-if-the-frontend-application-is-unavailable) How to Request to Close a Position on SYMM if the Frontend Application is Unavailable ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- If you need to close your position or cancel a quote to unlock collateral but the frontend is unavailable, you can follow these steps to execute the operation manually using on-chain methods. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/closing-a-position#solution-1-use-the-ipfs-fe) Solution 1: Use the IPFS FE Use the IPFS frontend to close the position (Website TBA) ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/closing-a-position#solution-2-manually-close-with-a-block-explorer) Solution 2: Manually Close with a Block Explorer #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/closing-a-position#step-1-locate-the-transaction-when-you-opened-the-position) Step 1: Locate the Transaction When You Opened the Position You need to find the `SendQuote` event log that was emitted when you initially opened your position. This log contains essential information such as the `partyA` address and the `quoteId`. You can obtain this information from a block explorer (like Etherscan) by searching for your account and looking for `_call()` transactions . Here’s an example of what the `SendQuote` emitted event might look like: ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FSCCJ80GCpPPUnh2TXdSv%252Fimage.png%3Falt%3Dmedia%26token%3D9c82fb38-5642-4319-99dc-96885bfa95c8&width=768&dpr=3&quality=100&sign=ae3fc78c&sv=2) sendQuote event #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/closing-a-position#step-2-find-the-calldatas-for-closing-the-position) Step 2: Find the `calldatas[]` for Closing the Position You need the `calldata[]` to send to the diamond contract (in this case, the SYMMIO Clearing Engine) to request to close your position. Here's how you can do that: 1. **Find the Diamond Address**: From the `SendQuote` log (from Step 1), identify the address of the SYMMIO Clearing Engine It will look something like this: 2. **Access Louper.dev**: * Go to [louper.devarrow-up-right](https://louper.dev/) . * Paste the diamond address and select the correct chain (e.g., Ethereum, BSC, etc.). * Connect the wallet you originally used to open the position. 3. **Request to Close the Position**: * Navigate to the **Write** tab in louper.dev. * Look for the function `requestToClosePosition` (or `requestToCancelQuote` if the quote was never responded to). Populate the fields using the data you extracted from the `SendQuote` log: ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FjU7v3mN1dmYcdwgztcaD%252Fimage.png%3Falt%3Dmedia%26token%3D8eb1b597-7603-4345-ace7-ad43c3bea300&width=768&dpr=3&quality=100&sign=7b2af3ad&sv=2) requestToClosePosition example ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FRBXTiFUTFLYUUtqoLLub%252Fimage.png%3Falt%3Dmedia%26token%3Db4108118-46c3-4540-bff7-05d253108ef7&width=768&dpr=3&quality=100&sign=3d79b51e&sv=2) requestToCancelQuote() example Make sure you adjust the closing price to ensure it reflects current market price with some added slippage to ensure that the closing operation goes through. For longs the `closePrice` should be slightly less than the `marketPrice` and for shorts the `closePrice` should be slightly more than the `marketPrice` Once you’ve populated the fields, click **Write** and wait for a wallet popup. Click the **View Raw** button to see the raw transaction data. This is where you’ll see the `calldata[]` generated. Copy this as a HEX string. ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252F6NQjTMdqAdff6Kj7IhwA%252Fimage.png%3Falt%3Dmedia%26token%3Da421d621-ecd3-4470-b048-8d234c0feca1&width=768&dpr=3&quality=100&sign=76184e87&sv=2) #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/closing-a-position#step-3-execute-the-_call-on-the-multiaccount-contract) Step 3: Execute the `_call()` on the MultiAccount Contract Now that you have the `calldata[]`, you can manually execute the closing request: 1. **Find the MultiAccount Contract**: This is the contract you used to open the position, the same one you checked the logs for to find the SendQuote event. 2. **Perform the** `**_call()**`: * Connect your trading wallet to the appropriate block explorer depending on the chain the trade was opened on (e.g., Etherscan or another compatible tool). * Perform a `_call()` by pasting the `calldata[]` and `partyA` address into the appropriate fields. circle-info The `partyA` is not the wallet you use but the sub-account address. You can find the `partyA` address in the details of the sendQuote event. ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252F17yTowK5TY0RJ2JSezD1%252Fimage.png%3Falt%3Dmedia%26token%3D69dbfbc5-0bb3-4c95-ace0-725beeca9855&width=768&dpr=3&quality=100&sign=d5e80d35&sv=2) Writing with a Block Explorer Submit the transaction on-chain to close the position by clicking **Write**. If everything was set up correctly, the position should be closed successfully. circle-info If you encounter an "is not a valid array" error, you must send the calldata as a hex string, enclosed in brackets and quotes e.g. `["0xa63b936300000000000000000000000000000000000000000000000000000000000002ba"]` [PreviousInteracting with SYMMIO's Contractschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts) [NextInstant Withdrawalchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/instant-withdrawal) Last updated 6 months ago * [How to Request to Close a Position on SYMM if the Frontend Application is Unavailable](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/closing-a-position#how-to-request-to-close-a-position-on-symm-if-the-frontend-application-is-unavailable) * [Solution 1: Use the IPFS FE](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/closing-a-position#solution-1-use-the-ipfs-fe) * [Solution 2: Manually Close with a Block Explorer](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/closing-a-position#solution-2-manually-close-with-a-block-explorer) sun-brightdesktopmoon Copy Address: 0x976c87cd3eb2de462db249cca711e4c89154537b (SYMMIO: Clearing Engine) sun-brightdesktopmoon --- # Documentation for Investors | SYMMIO Protocol Gitbook For information for investors, refer to the [Symmio Foundation Documetnationarrow-up-right](https://docs.symmio.foundation/) . [PreviousSolver Error Codeschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/solver-error-codes) [NextArchitecture Deep Divechevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive) Last updated 25 days ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Solver Docs (Github) | SYMMIO Protocol Gitbook [https://github.com/SYMM-IO/docs/tree/main/hedger\_docsarrow-up-right](https://github.com/SYMM-IO/docs/tree/main/hedger_docs) [PreviousDocumentation for Solverschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers) [NextCore Conceptschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/core-concepts) Last updated 1 month ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Instant Trading for Frontend Builders | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-trading-for-frontend-builders#instant-trading-for-frontend-builders-enhancing-user-experience-and-capability) Instant Trading for Frontend Builders: Enhancing User Experience and Capability --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Instant Trading on SYMMIO introduces a new era of speed and responsiveness for decentralized derivatives trading. Before, users had to wait seconds—or even minutes—for trade confirmations and price lock-ins. With Instant Trading, frontend builders can now deliver a trading experience that closely matches the speed found on centralized exchanges, all while preserving the transparency and trustlessness of decentralized infrastructure. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-trading-for-frontend-builders#why-instant-trading-matters-for-frontend-builders) Why Instant Trading Matters for Frontend Builders **1\. Dramatic UX Improvements**: By integrating Instant Trading, frontend builders can provide near-instant trade confirmations (under one second) and rapid on-chain settlement (5–30 seconds depending on the network). This reduces user frustration, improves retention, and encourages more active engagement. **2\. Unlocking Advanced Trading Strategies**: Faster execution times enable strategies like scalping and precise position management that were previously challenging in decentralized environments. This enhances the attractiveness of your platform to both retail users and professional traders. **3\. Session Management**: Users delegate certain trading functions to solvers via the MultiAccount contract, allowing trades to be opened and closed without repeatedly signing individual transactions. Frontend builders can guide users through this one-time delegation process and streamline their subsequent trading activities. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-trading-for-frontend-builders#key-requirements-for-frontend-builders) Key Requirements for Frontend Builders **1\. Delegation of Functions**: Frontend Builders must implement an initial user flow where the trader authorizes solver addresses to act on their behalf for specific functions. Once granted, these permissions enable quick, automated trade execution without additional signatures. **2\. Secure Authentication Flow**: Your frontend needs to handle authentication and session creation. Users sign a message, solvers verify it, and the frontend receives an access token. This token is crucial for subsequent requests, ensuring trades occur instantly while maintaining a secure environment. You can read more about this [here](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation) . **3\. Integration with Solver Endpoints**: While frontend builders handle the user interface and overall experience, Instant Trading relies on solver endpoints to process trades instantly. Applications connect securely with these solver APIs to submit trade requests and receive immediate confirmations. **4\. Transparent User Communication**: Communicate the implications of delegating access. Emphasize that users retain control, can revoke delegated functions, and that access tokens expire. You can read more about the solver implementations and endpoints here: [Instant Trading (Solvers)chevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-solvers) [Rasa Instant Trading Implementationchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation) circle-info It's advised for solvers to follow Rasa's implementation to ensure a consistent format for API endpoints across solvers. For a practical example of how these endpoints are called in a full script, check the guide here: [Building an Application with SYMMIO](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/instant-login-eoa) ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-trading-for-frontend-builders#future-outlook) Future Outlook With Instant Trading, frontend builders are able to offer: * **Account-Based APIs**: Simplifying integration for automated strategies and enabling more complex trading frameworks. * **Advanced TP/SL Implementations**: Leveraging instant actions to adjust or close positions with extreme precision. * **Full Account Abstraction**: Eventually, users could trade without manually managing wallets, signatures, or even addresses—operating purely via familiar Web2 methods while retaining the security of decentralized finance. [PreviousFrontend Builder SDK Setup Guidechevron-left](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/frontend-builder-sdk-setup-guide) [NextAccount Abstracted Instant Actions Frontend Builderschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-trading-for-frontend-builders/account-abstracted-instant-actions-frontend-builders) Last updated 7 months ago * [Instant Trading for Frontend Builders: Enhancing User Experience and Capability](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-trading-for-frontend-builders#instant-trading-for-frontend-builders-enhancing-user-experience-and-capability) * [Why Instant Trading Matters for Frontend Builders](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-trading-for-frontend-builders#why-instant-trading-matters-for-frontend-builders) * [Key Requirements for Frontend Builders](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-trading-for-frontend-builders#key-requirements-for-frontend-builders) * [Future Outlook](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-trading-for-frontend-builders#future-outlook) sun-brightdesktopmoon sun-brightdesktopmoon --- # MultiAccount Deployment Guide | SYMMIO Protocol Gitbook circle-info This guide has been updated to reflect the Etherscan V1 -> V2 upgrade. This document outlines the required steps and responsibilities for deploying the MultiAccount contract. 1. **Responsibility and Security** The full responsibility for the deployment and ongoing management of the MultiAccount contract lies with the deploying entity. To ensure the integrity and security of the contract, please take the following actions: * Conduct thorough audits of the contract code. * Implement robust security checks. * Ensure regular maintenance and monitoring of the deployed contract. 2. **Deployment of Latest Version** It is essential to deploy the latest version of the MultiAccount contract. The most current version can be found at the following link: [MultiAccount Contractarrow-up-right](https://github.com/SYMM-IO/protocol-core/blob/main/contracts/multiAccount/MultiAccount.sol) Please note that the MultiAccount contract available in this repository is a sample code. You are free to modify or customize the code to meet your specific requirements. However, be aware that any modifications or changes to the contract may extend the time required for the registration process, as the Symmio team will need to thoroughly review and approve the changes. 1. Transfer of Admin Roles and ProxyAdmin Ownership Upon successful deployment, the following steps must be completed to ensure secure management of the contract: * Transfer the admin roles to the appropriate entity. * Transfer ownership of the ProxyAdmin to a 3-day timelock contract for added security. These measures are necessary to safeguard the contract against unauthorized access or modifications. 1. **Proposal to Symmio Team** After deploying the contract and completing the necessary security measures, a formal proposal must be submitted to the Symmio team. The proposal should request that the deployed MultiAccount contract address be registered in the Symmio Core Contracts. If any modifications have been made to the original sample contract, please note that the registration process may take longer due to the required review of the changes by the Symmio team. **Prerequisites** * Install Node.js and npm. * Install Hardhat in your project directory: `npm install --save-dev hardhat` * Install Typescript and `ts-node`: `npm install --save-dev typescript ts-node` [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/multiaccount-deployment-guide#step-1-clone-the-repo) Step 1: Clone the Repo ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/multiaccount-deployment-guide#step-2-prerequisites) Step 2: Prerequisites ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- **Ensure you're working with Node 20 LTS** (Hardhat doesn’t support Node 21) [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/multiaccount-deployment-guide#step-3-create-a-.env) Step 3: Create a `.env` ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- At the repo root, create a `.env`. Within the repo you'll find a `.env.example`. Copy the example over into the .env and populate the fields appropriately. The required variables for deployment are here: circle-info Use `**ETHERSCAN_API_KEY**` (single key). V1 per-network keys are now deprecated. Read more about the changes [herearrow-up-right](https://docs.etherscan.io/) . [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/multiaccount-deployment-guide#step-4-update-hardhat.config.ts-etherscan-v2) Step 4: Update `hardhat.config.ts` (Etherscan V2) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Replace your `etherscan` section in `hardhat.config.ts` with **one key** and **clean URLs** (no `?apikey=` anywhere): Example: [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/multiaccount-deployment-guide#step-5-installing-dependencies) Step 5: Installing Dependencies ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- **Install hardhat via the terminal (if not done already):** [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/multiaccount-deployment-guide#step-6-compile-the-contracts) Step 6: Compile the Contracts --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/multiaccount-deployment-guide#step-7-deploying-a-multiaccount-contract-polygon) Step 7: Deploying a MultiAccount Contract (Polygon) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- In this example, we're deploying a MultiAccount contract on **Polygon**, using the address of the diamond deployed there (`--symmio-address`). A comprehensive list of all the deployed Diamond addresses can be found here. This will print to the terminal: You can find the deployed addresses in `/tasks/data/deployed.json`. This file is used for verification in the following step. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/multiaccount-deployment-guide#step-8-verifying-the-multiaccount-contract) Step 8: Verifying the MultiAccount contract ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Simply run the verification script with the appropriate network flag to verify the contracts. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/multiaccount-deployment-guide#troubleshooting) Troubleshooting ------------------------------------------------------------------------------------------------------------------------------------------------------------ * **“Using deprecated V1 endpoint / API key invalid”** → ensure you have **ETHERSCAN\_API\_KEY** (single key, **not** a string) and your `apiURL`s **don’t** contain `?apikey=..` * **Node warning** → `node -v` must be **v20.x**. * **Compiler mismatch** → run `npx hardhat clean && npx hardhat compile`. (Stick with the repo’s existing Solidity settings.) [PreviousSetting up a Frontend with SYMMIOchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/setting-up-a-frontend-with-symmio) [NextBuilding an Application with SYMMIOchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio) Last updated 28 days ago * [Step 1: Clone the Repo](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/multiaccount-deployment-guide#step-1-clone-the-repo) * [Step 2: Prerequisites](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/multiaccount-deployment-guide#step-2-prerequisites) * [Step 3: Create a .env](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/multiaccount-deployment-guide#step-3-create-a-.env) * [Step 4: Update hardhat.config.ts (Etherscan V2)](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/multiaccount-deployment-guide#step-4-update-hardhat.config.ts-etherscan-v2) * [Step 5: Installing Dependencies](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/multiaccount-deployment-guide#step-5-installing-dependencies) * [Step 6: Compile the Contracts](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/multiaccount-deployment-guide#step-6-compile-the-contracts) * [Step 7: Deploying a MultiAccount Contract (Polygon)](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/multiaccount-deployment-guide#step-7-deploying-a-multiaccount-contract-polygon) * [Step 8: Verifying the MultiAccount contract](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/multiaccount-deployment-guide#step-8-verifying-the-multiaccount-contract) * [Troubleshooting](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/multiaccount-deployment-guide#troubleshooting) sun-brightdesktopmoon Copy git clone https://github.com/SYMM-IO/protocol-core cd protocol-core Copy node -v # should show v20.x # if not: nvm install 20 nvm use 20 node -v Copy MANTLE_API_KEY="" MANTLE2_API_KEY="" BNB_API_KEY="" BLAST_API_KEY="" BASE_API_KEY="" POLYGON_API_KEY="" ARBITRUM_API_KEY="" IOTA_API_KEY="" MODE_API_KEY="" BERA_API_KEY="" PRIVATE_KEY="" PRIVATE_KEYS_STR="" ADMIN_PUBLIC_KEY="" HARDHAT_DOCKER_URL="http://eth-node:8545" TEST_USER_BALANCE=5000 TEST_USER_MAX_QUOTE=100 HEDGER_WEB_SERVICE="http://127.0.0.1:8090" TEST_USER_TIMEOUT=120000 LOG_LEVEL=debug DEPLOY_MULTICALL=false VALIDATION_PROBABILITY=0.2 DEPLOY_MULTICALL=true TEST_MODE={static,pre-upgrade,fuzz} Copy ETHERSCAN_API_KEY=YOUR_ETHERSCAN_V2_KEY PRIVATE_KEY=0xYOUR_DEPLOYER_PRIVATE_KEY ADMIN_PUBLIC_KEY=0xYOUR_ADMIN_PUBLIC_KEY Copy etherscan: { apiKey: process.env.ETHERSCAN_API_KEY || "", //Just using the V2 API customChains: [\ // Keep only chains you actually verify on.\ // IMPORTANT: no "?apikey=..." in apiURL anymore.\ {\ network: "zkEvm",\ chainId: 1101,\ urls: {\ apiURL: "https://api-zkevm.polygonscan.com/api",\ browserURL: "https://zkevm.polygonscan.com",\ },\ },\ {\ network: "opbnb",\ chainId: 204,\ urls: {\ apiURL: "https://api-opbnb.bscscan.com/api",\ browserURL: "https://opbnb.bscscan.com",\ },\ },\ {\ network: "iota",\ chainId: 8822,\ urls: {\ apiURL: "https://explorer.evm.iota.org/api",\ browserURL: "https://explorer.evm.iota.org",\ },\ },\ {\ network: "mode",\ chainId: 34443,\ urls: {\ apiURL: "https://api.routescan.io/v2/network/mainnet/evm/34443/etherscan",\ browserURL: "https://modescan.io",\ },\ },\ {\ network: "blast",\ chainId: 81457,\ urls: {\ apiURL: "https://api.blastscan.io/api",\ browserURL: "https://blastscan.io",\ },\ },\ {\ network: "mantle",\ chainId: 5000,\ urls: {\ apiURL: "https://api.mantlescan.xyz/api",\ browserURL: "https://mantlescan.xyz",\ },\ },\ {\ network: "sonic",\ chainId: 146,\ urls: {\ apiURL: "https://api.sonicscan.org/api",\ browserURL: "https://sonicscan.org",\ },\ },\ {\ network: "bera",\ chainId: 80094,\ urls: {\ apiURL: "https://api.routescan.io/v2/network/mainnet/evm/80094/etherscan",\ browserURL: "https://beratrail.io",\ },\ },\ ], }, Copy npm install --save-dev hardhat Copy npx hardhat compile Copy npx hardhat deploy:multiAccount --symmio-address 0x976c87Cd3eB2DE462Db249cCA711E4C89154537b --admin 0x3B5aC601c7bB74999AB3135fa43cbDBc6aB74570 --network polygon Copy Running deploy:multiAccount Deploying contracts with the account: 0x3B5aC601c7bB74999AB3135fa43cbDBc6aB74570 0x3B5aC601c7bB74999AB3135fa43cbDBc6aB74570 0x976c87Cd3eB2DE462Db249cCA711E4C89154537b MultiAccount deployed to { proxy: '0x69192790420cd7e97f231BB73B9c9C5d914A2fc8', admin: '0xC0788bB9293e53703a4e3921409849FAE006306C', implementation: '0x0F0711432E871bc0C581DA0cF71fC82565f3e77b' } Could not read existing JSON file: Error: ENOENT: no such file or directory, open 'D:\docsmulti\protocol-core\tasks\data\deployed.json' Deployed addresses written to JSON file Copy [\ {\ "name": "MultiAccountProxy",\ "address": "0x78174a787914Ae4eB8c1EaC87fEa19c547fD474D",\ "constructorArguments": [\ "0x3B5aC601c7bB74999AB3135fa43cbDBc6aB74570",\ "0x976c87Cd3eB2DE462Db249cCA711E4C89154537b",\ "0x60803461016157601f610e2d38819003918201601f191683019291906001600160401b038411838510176101665781606092849260409687528339810103126101615761004b8161017c565b9060206100648461005d83850161017c565b930161017c565b9160009182805282815285832060018060a01b0380961690818552825260ff87852054161561012a575b507febee9ae4283d502e7ed608f7bff6281dc40560c705aa66f8f31324862ed03f5a9081845283815285878520931692838552815260ff8785205416156100f2575b505050501660018060a01b0319600154161760015551610c7c90816101918239f35b8184528381528684209083855252858320600160ff19825416179055600080516020610e0d833981519152339380a4388080806100d0565b8380528382528684208185528252868420805460ff19166001179055339084600080516020610e0d8339815191528180a43861008e565b600080fd5b634e487b7160e01b600052604160045260246000fd5b51906001600160a01b03821682036101615756fe60406080815260048036101561001457600080fd5b600091823560e01c806301569e3a1461062857806301ffc9a7146105d2578063248a9ca3146105a85780632f2ff15d146104ff57806336568abe1461046d57806359f6d3921461043257806362dfbb2e146101665780637278b28f1461013d57806391d14854146100f7578063a217fddf146100d85763d547741f1461009957600080fd5b346100d457806003193601126100d4576100d191356100cc60016100bb610843565b938387528660205286200154610916565b610ab7565b80f35b8280fd5b8382346100f357816003193601126100f35751908152602090f35b5080fd5b5090346100d457816003193601126100d4578160209360ff92610118610843565b903582528186528282206001600160a01b039091168252855220549151911615158152f35b8382346100f357816003193601126100f35760015490516001600160a01b039091168152602090f35b50823461042f57602092836003193601126100f35780359067ffffffffffffffff82116100d457366023830112156100d45781810135906101a6826108b2565b926101b386519485610890565b828452868401926024913683838301011161042b57818792848b93018737860101527febee9ae4283d502e7ed608f7bff6281dc40560c705aa66f8f31324862ed03f5a808652858852868620338752885260ff878720541615610279575050600154925161026c949384938493509083906001600160a01b03165af1923d15610270573d610240816108b2565b9061024d83519283610890565b81528092863d92013e5b808051958695151586528501528301906108f1565b0390f35b60609150610257565b87935086908661028833610b52565b918351906102958261085e565b6042825287820192606036853782511561041957603084538251906001918210156104075790607860218501536041915b81831161039e5750505061037057604861036c9593859361035493610345975197889376020b1b1b2b9b9a1b7b73a3937b61d1030b1b1b7bab73a1604d1b8d86015261031c8d82519283916037890191016108ce565b8401917001034b99036b4b9b9b4b733903937b6329607d1b6037840152518093868401906108ce565b01036028810186520184610890565b5194859462461bcd60e51b86528501528301906108f1565b0390fd5b60648688878188519362461bcd60e51b8552840152820152600080516020610c508339815191526044820152fd5b909192600f811660108110156103f5576f181899199a1a9b1b9c1cb0b131b232b360811b901a6103ce8587610b2b565b53891c9280156103e3576000190191906102c6565b634e487b7160e01b825260118a528882fd5b634e487b7160e01b835260328b528983fd5b634e487b7160e01b8152603289528790fd5b634e487b7160e01b8152603288528690fd5b8680fd5b80fd5b8382346100f357816003193601126100f357602090517febee9ae4283d502e7ed608f7bff6281dc40560c705aa66f8f31324862ed03f5a8152f35b509190346100f357826003193601126100f357610488610843565b90336001600160a01b038316036104a457906100d19135610ab7565b608490602085519162461bcd60e51b8352820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b6064820152fd5b5090346100d457816003193601126100d457359061051b610843565b908284528360205261053260018286200154610916565b82845260208481528185206001600160a01b039093168086529290528084205460ff161561055e578380f35b828452836020528084208285526020528320600160ff1982541617905533917f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d8480a43880808380f35b5090346100d45760203660031901126100d457816020936001923581528085522001549051908152f35b5090346100d45760203660031901126100d457359063ffffffff60e01b82168092036100d45760209250637965db0b60e01b8214918215610617575b50519015158152f35b6301ffc9a760e01b1491503861060e565b50346100d4576020908160031936011261083f576001600160a01b038335818116949085900361083b57858052858452828620338752845260ff8387205416156106b15750907ff78ccdf5924090b2ab6627ac5da4ec5affed73d47c6bc6c8a4620a0d5ed57bc891846001549483519286168352820152a16001600160a01b0319161760015580f35b919050846106be33610b52565b90808351906106cc8261085e565b6042825286820192606036853782511561082857603084538251906001918210156108155790607860218501536041915b8183116107aa5750505061077b5760486107529385936107619361036c975196879376020b1b1b2b9b9a1b7b73a3937b61d1030b1b1b7bab73a1604d1b8c86015261031c8c82519283916037890191016108ce565b01036028810185520183610890565b5193849362461bcd60e51b855284015260248301906108f1565b606485878087519262461bcd60e51b84528301526024820152600080516020610c508339815191526044820152fd5b909192600f81166010811015610802576f181899199a1a9b1b9c1cb0b131b232b360811b901a6107da8587610b2b565b53881c9280156107ef576000190191906106fd565b634e487b7160e01b825260118952602482fd5b634e487b7160e01b835260328a52602483fd5b634e487b7160e01b815260328852602490fd5b634e487b7160e01b815260328752602490fd5b8580fd5b8380fd5b602435906001600160a01b038216820361085957565b600080fd5b6080810190811067ffffffffffffffff82111761087a57604052565b634e487b7160e01b600052604160045260246000fd5b90601f8019910116810190811067ffffffffffffffff82111761087a57604052565b67ffffffffffffffff811161087a57601f01601f191660200190565b60005b8381106108e15750506000910152565b81810151838201526020016108d1565b9060209161090a815180928185528580860191016108ce565b601f01601f1916010190565b600090808252602090828252604092838120338252835260ff84822054161561093f5750505050565b61094833610b52565b918451906109558261085e565b60428252848201926060368537825115610aa35760308453825190600191821015610aa35790607860218501536041915b818311610a3557505050610a0557604861036c9386936109e9936109da985198899376020b1b1b2b9b9a1b7b73a3937b61d1030b1b1b7bab73a1604d1b8a86015261031c815180928c6037890191016108ce565b01036028810187520185610890565b5192839262461bcd60e51b8452600484015260248301906108f1565b60648486519062461bcd60e51b82528060048301526024820152600080516020610c508339815191526044820152fd5b909192600f81166010811015610a8f576f181899199a1a9b1b9c1cb0b131b232b360811b901a610a658587610b2b565b5360041c928015610a7b57600019019190610986565b634e487b7160e01b82526011600452602482fd5b634e487b7160e01b83526032600452602483fd5b634e487b7160e01b81526032600452602490fd5b9060009180835282602052604083209160018060a01b03169182845260205260ff604084205416610ae757505050565b80835282602052604083208284526020526040832060ff1981541690557ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b339380a4565b908151811015610b3c570160200190565b634e487b7160e01b600052603260045260246000fd5b604051906060820182811067ffffffffffffffff82111761087a57604052602a8252602082016040368237825115610b3c57603090538151600190811015610b3c57607860218401536029905b808211610be1575050610baf5790565b606460405162461bcd60e51b81526020600482015260206024820152600080516020610c508339815191526044820152fd5b9091600f81166010811015610c3a576f181899199a1a9b1b9c1cb0b131b232b360811b901a610c108486610b2b565b5360041c918015610c25576000190190610b9f565b60246000634e487b7160e01b81526011600452fd5b60246000634e487b7160e01b81526032600452fdfe537472696e67733a20686578206c656e67746820696e73756666696369656e74a164736f6c6343000812000a2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d"\ ]\ },\ {\ "name": "MultiAccountAdmin",\ "address": "0xB3A34B46a9103fB157b5b1Af4655ec703b1578D2",\ "constructorArguments": []\ },\ {\ "name": "MultiAccountImplementation",\ "address": "0x950BaeF761A17Cd0f77d6dB8008ebeBd011FCA4b",\ "constructorArguments": []\ }\ ] Copy npx hardhat verify:deployment --network polygon sun-brightdesktopmoon --- # Setting a Stop Loss | SYMMIO Protocol Gitbook Once a position is successfully opened via the solver’s **instant trading API**, it's worth setting a stop loss to protect that position. This ensures risk is bounded even if the bot goes offline or market conditions change unexpectedly. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/setting-a-stop-loss#high-level-flow) High-Level Flow 1. Authenticate with the Hedger API ([SIWE login](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/instant-login-eoa) ) 2. Open an instant market position 3. Let the **temporary quote ID** resolve into a permanent `quoteId` 4. Calculate the stop-loss price 5. Submit a stop-loss request to the solver API > ⚠️ A stop loss **must reference a permanent** `**quoteId**`. You cannot attach SL/TP to a temporary quote. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/setting-a-stop-loss#authentication-siwe-login) Authentication (SIWE Login) Before any protected actions (open, stop loss, cancel, etc.), the bot must authenticate using **Sign-In With Ethereum (SIWE)**. 1. Fetch a nonce from the hedger 2. Build a SIWE message scoped to the **active trading account** 3. Sign the message with the owner wallet 4. Exchange the signature for a JWT access token Copy token = login() The returned `access_token` is used as a Bearer token for all subsequent requests. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/setting-a-stop-loss#opening-the-position-instant-open) Opening the Position (Instant Open) The bot opens a position using the solver’s `instant_open` endpoint. Key points: * Orders **must be market orders** (`orderType = 1`) * The price is derived from the **Muon Oracle** * Slippage is applied to guarantee execution * Collateral parameters are calculated using `get_locked_params` #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/setting-a-stop-loss#returned-values) Returned Values * `temp_quote_id`: Temporary identifier for the order * `open_price`: The raw Muon price used to derive SL/TP levels * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/setting-a-stop-loss#resolving-the-temporary-quote-id) Resolving the Temporary Quote ID Instant trades initially return a **temporary quote ID**. Before setting a stop loss, the bot must wait until this temp ID is finalized into a **permanent** `**quoteId**`. This is done by polling the user’s active quotes: #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/setting-a-stop-loss#why-this-is-required) Why This Is Required * Stop loss and take profit requests are validated against finalized on-chain quotes * Using a temp ID will result in rejection * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/setting-a-stop-loss#calculating-the-stop-loss-price) Calculating the Stop Loss Price Once the quote is confirmed, derives a stop-loss price relative to the entry price. In this example: * The bot is **LONG** * Stop loss is set at **80% of entry price** #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/setting-a-stop-loss#notes) Notes * Precision should match the symbol’s supported decimals * For SHORT positions, this logic would be inverted * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/setting-a-stop-loss#stop-loss-request-payload) Stop Loss Request Payload The stop loss is submitted using the `stop_loss` endpoint. circle-info This refers to [PerpsHub TPSL Implementation](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/perpshub-tp-sl-implementation) , check [Rasa's TPSL Implementation](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/rasa-solver-tp-sl-implementation) for detailed instructions on how to construct their payload. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/setting-a-stop-loss#payload-structure) Payload Structure #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/setting-a-stop-loss#field-explanation) Field Explanation Field Description `userAddress` Wallet that signed the login message `accountAddress` Trading account (EOA or sub-account) `positionSide` `0 = Long`, `1 = Short` `symbolId` Internal symbol identifier `requestedPrice` Original entry price `quoteId` Permanent quote ID `tpPrice` Leave empty if not setting TP `slPrice` Calculated stop loss price `timestamp` Client-side timestamp (ms) * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/setting-a-stop-loss#sending-the-stop-loss-request) Sending the Stop Loss Request On success, the solver will acknowledge the stop loss and register it for on-chain execution when the trigger price is reached. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/setting-a-stop-loss#complete-execution-flow) Complete Execution Flow A full example implementation can be found in our SYMM SDK. [PreviousOpening a Positionchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/opening-a-position) [NextMonitoring Position Statuschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/monitoring-position-status) Last updated 1 month ago * [High-Level Flow](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/setting-a-stop-loss#high-level-flow) * [Authentication (SIWE Login)](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/setting-a-stop-loss#authentication-siwe-login) * [Opening the Position (Instant Open)](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/setting-a-stop-loss#opening-the-position-instant-open) * [Resolving the Temporary Quote ID](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/setting-a-stop-loss#resolving-the-temporary-quote-id) * [Calculating the Stop Loss Price](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/setting-a-stop-loss#calculating-the-stop-loss-price) * [Stop Loss Request Payload](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/setting-a-stop-loss#stop-loss-request-payload) * [Sending the Stop Loss Request](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/setting-a-stop-loss#sending-the-stop-loss-request) * [Complete Execution Flow](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/setting-a-stop-loss#complete-execution-flow) sun-brightdesktopmoon Copy temp_quote_id, open_price = open_instant_trade(token) Copy quote_id = poll_quote_status(token, temp_quote_id) Copy sl_price = (open_price * Decimal('0.8')).quantize( Decimal("0.000001"), rounding=ROUND_DOWN ) Copy { "userAddress": "", "accountAddress": "", "positionSide": 0, "symbolId": 4, "requestedPrice": "ENTRY_PRICE", "quoteId": 12345, "tpPrice": "", "slPrice": "STOP_LOSS_PRICE", "timestamp": 1710000000000 } Copy response = requests.post( f"{HEDGER_URL}/stop_loss", json=payload, headers={ "Content-Type": "application/json", "Authorization": f"Bearer {token}" } ) Copy Login (SIWE) ↓ Instant Open Position ↓ Receive temp_quote_id ↓ Poll until quoteId is finalized ↓ Compute stop loss price ↓ POST /stop_loss sun-brightdesktopmoon --- # Delegating Access to the Solver | SYMMIO Protocol Gitbook ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/delegating-access-to-the-solver#step-3-delegating-access-to-the-solver) Step 3: Delegating Access to the Solver For instant trading, you need to delegate certain function access rights to the SYMM solver (also called PartyB). You can read more about this requirement [here](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/instant-login-eoa) . #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/delegating-access-to-the-solver#required-function-selectors) Required Function Selectors The following function selectors are required for instant trading: * `0x7f2755b2` - sendQuote * `0x40f1310c` - sendQuoteWithAffiliate * `0x501e891f` - requestToClosePosition #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/delegating-access-to-the-solver#example-code-delegating-access-via-multiaccount-for-a-sub-account) Example Code (Delegating Access via MultiAccount for a sub-account) Copy from dotenv import load_dotenv import os import json from web3 import Web3 load_dotenv() CONFIG = { "rpc_url": os.getenv("RPC_URL"), "private_key": os.getenv("PRIVATE_KEY"), "multiaccount_address": os.getenv("MULTIACCOUNT_ADDRESS"), "sub_account_address": os.getenv("SUB_ACCOUNT_ADDRESS"), "party_b_address": os.getenv("PARTY_B_ADDRESS"), } class MultiAccountClient: def __init__(self, config): self.config = config abi_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "abi", "MultiAccount.json")) with open(abi_path, "r") as abi_file: self.abi = json.load(abi_file) self.w3 = Web3(Web3.HTTPProvider(config["rpc_url"])) self.account = self.w3.eth.account.from_key(config["private_key"]) self.multiaccount = self.w3.eth.contract( address=Web3.to_checksum_address(config["multiaccount_address"]), abi=self.abi ) def delegate_accesses(self, account_address: str, target_address: str, selectors: list, state: bool): """Batch delegate access for multiple function selectors""" try: selectors_bytes = [Web3.to_bytes(hexstr=s) for s in selectors] txn = self.multiaccount.functions.delegateAccesses( Web3.to_checksum_address(account_address), Web3.to_checksum_address(target_address), selectors_bytes, state ).build_transaction({ "from": self.account.address, "nonce": self.w3.eth.get_transaction_count(self.account.address, "pending"), "gas": 400000, "gasPrice": self.w3.eth.gas_price, }) signed_txn = self.w3.eth.account.sign_transaction(txn, private_key=self.config["private_key"]) tx_hash = self.w3.eth.send_raw_transaction(signed_txn.raw_transaction) print(f"Delegate accesses transaction sent: {tx_hash.hex()}") self.w3.eth.wait_for_transaction_receipt(tx_hash) print("Delegate accesses transaction confirmed.") except Exception as e: print(f"Error delegating accesses: {e}") raise def main(): client = MultiAccountClient(CONFIG) sub_account_address = CONFIG["sub_account_address"] party_b_address = CONFIG["party_b_address"] selectors = [\ "0x7f2755b2", # sendQuote\ "0x40f1310c", # sendQuoteWithAffiliate\ "0x501e891f", # requestToClosePosition\ ] state = True print("Batch delegating access for Instant Open and Instant Close...") client.delegate_accesses(sub_account_address, party_b_address, selectors, state) if __name__ == "__main__": main() [PreviousDepositing and Allocating Collateralchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/depositing-and-allocating-collateral) [NextAuthenticating Tradeschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/authenticating-trades) Last updated 5 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Introduction and Diamond Explainer | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/introduction-and-diamond-explainer#introduction) Introduction ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Symmio is a trustless, hybrid clearing house that functions as the communication, settlement, and clearing layer for permissionless derivatives. It’s built as an intent-centric, meta-derivatives engine, designed to power hyper‑efficient perpetuals trading. Within our architecture: * **PartyA** is the trader—the party that initiates a trading intent. * **PartyB** is the hedger/solver—the counterparty that accepts and hedges the trade. "Hedger" and "Solver" can be used interchangeably. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/introduction-and-diamond-explainer#the-symm-diamond) The SYMM Diamond ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- SYMMIO's core contracts are built using the EIP‑2535 Diamond Standard—a modular and upgradeable approach that splits functionality into multiple facets. This design enables independent upgrades and simplifies contract management without affecting the overall system. You can read more in detail about the diamond architecture in our [Contract Documents (0.8.4)](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/the-symm-diamond-0.8.4) . All SYMM-related function calls should be directed to the Diamond contract—not to any individual facet. The facets serve solely as the underlying logic components, while the Diamond acts as the central dispatcher. When you invoke a function on the Diamond, it delegates the call to the appropriate facet, which then updates the shared storage accordingly. [PreviousBuilding an Application with SYMMIOchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio) [NextQuerying Info from the SYMMIO Diamondchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/querying-info-from-the-symmio-diamond) Last updated 29 days ago * [Introduction](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/introduction-and-diamond-explainer#introduction) * [The SYMM Diamond](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/introduction-and-diamond-explainer#the-symm-diamond) sun-brightdesktopmoon sun-brightdesktopmoon --- # Documentation for Solvers | SYMMIO Protocol Gitbook [Solver Docs (Github)chevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/solver-docs-github) [Core Conceptschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/core-concepts) [Building a Solver on SYMMIOchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio) [Conditional Orderschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders) [Instant Tradingchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading) [How to Add a Market as a Solverchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/how-to-add-a-market-as-a-solver) [Fetching Gas Prices Scriptchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script) [Verifying Account Abstracted Instant Actions (ERC-4337)chevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/verifying-account-abstracted-instant-actions-erc-4337) [Solver Error Codeschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/solver-error-codes) [PreviousUser Interaction Scenarioschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-withdrawal-for-frontend-builders/user-interaction-scenarios) [NextSolver Docs (Github)chevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/solver-docs-github) sun-brightdesktopmoon sun-brightdesktopmoon --- # Building an Application with SYMMIO | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio#building-with-the-symmio-architecture) Building with the SYMMIO Architecture -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- The SYMM platform is built on a robust, modular architecture that leverages advanced concepts like the Diamond Standard for upgradeable contracts, MultiAccount management, and a suite of specialized facets to manage trading operations. This section serves as your comprehensive guide to understanding and working with the core components of SYMMIO. Whether you are creating a frontend or developing an additional utility for your project, this guide provides the foundational knowledge and practical instructions to get you started. circle-info To learn how to build a trading bot using SYMMIO, refer to [this guide](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio) ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio#overview) Overview This section is designed to help developers understand how the SYMM ecosystem is structured and how its various components interact. You will learn about the architectural principles behind SYMM—including modularity, upgradeability, and separation of concerns—and how these design choices enable secure and efficient trading on the platform. The upcoming subsections will cover the following topics: * **Diamond Explainer:** Explore the core of the SYMMIO architecture built on the Diamond Standard (EIP‑2535). This subsection will explain how the diamond pattern is used to create a flexible and upgradeable smart contract system, breaking down facets, selectors, and storage management. * **MultiAccount Explainer:** Understand the MultiAccount design, which allows users to manage sub‑accounts and delegate trading actions. Learn how this system provides both cross‑account and isolated account functionality, and the mechanisms behind access delegation and revocation. * **Creating an Account:** Walk through the process of creating a new sub‑account using the SYMMIO MultiAccount contract. This section will describe account initialization, role assignment, and the deployment of account contracts. * **Depositing and Allocating:** Learn how to fund your SYMMIO sub-account by depositing collateral and then allocating those funds for trading. Detailed examples will illustrate how the allocation process works and how it affects your trading capacity. * **Sending a Quote:** Discover how to initiate a trade by sending a quote. This part covers the core functionality for setting up trade requests—including specifying the trading symbol, price, quantity, and risk parameters—and how these requests are processed by the system. * **Closing a Quote:** Understand the standard process for closing a position. This section details how a user can request a position close, the various states involved, and the roles of both Party A and Party B during the closing process. * **Sending a Quote (Instant Open):** This variant of the quote-sending process is designed for scenarios where immediate execution is desired. Learn how the Instant Open mechanism works, its benefits, and its trade-offs compared to the standard quote process. * **Closing a Quote (Instant Open):** Explore the instant close mechanism that allows positions to be closed immediately. This approach minimizes delays and is designed for users who need to react swiftly to changing market conditions Each subsection will provide a detailed explanation, function signatures, example usage, and event descriptions to help you build with SYMM confidently. By the end of this section, you will have a clear understanding of how to leverage the SYMM architecture to create, manage, and execute trades in a secure, modular, and upgradeable environment. [PreviousMultiAccount Deployment Guidechevron-left](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/multiaccount-deployment-guide) [NextIntroduction and Diamond Explainerchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/introduction-and-diamond-explainer) Last updated 29 days ago * [Building with the SYMMIO Architecture](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio#building-with-the-symmio-architecture) * [Overview](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio#overview) sun-brightdesktopmoon sun-brightdesktopmoon --- # How to Query our Contracts | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#the-symm-diamond) The SYMM Diamond ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ SYMMIO's core contracts are implemented with **EIP-2535**, a solution for building modular and upgradeable contracts. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#eip-2535-diamond-standard-overview) **EIP-2535: Diamond Standard Overview** EIP-2535 introduces the Diamond Standard in smart contract development. This standard centralizes around the concept of a "Diamond" contract, which is constructed from multiple "facets," each responsible for different functionalities. This modular design enhances maintainability by allowing facets to be upgraded or modified independently without affecting the entire contract. Key to this architecture are function selectors, which serve as unique identifiers for each function within the facets. These selectors efficiently direct function calls to the correct facet, facilitating organized and conflict-free code execution. For further reading and technical details, refer to the [official EIP-2535 documentationarrow-up-right](https://eips.ethereum.org/EIPS/eip-2535) . When a facet, is invoked via a `delegatecall` from the Diamond, it operates directly on the Diamond’s storage. The facet uses the slot address computed by the library to access or modify the data in the specific storage slot. This operation is transparent to the Diamond itself. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#finding-facet-contracts) Finding Facet Contracts In the SYMM Diamond, the `facets()` function of the `DiamondLoupeFacet` plays a crucial role in inspecting the contract's structure and behaviour. When this function is called on the Diamond, it returns an array of `Facet` structs, each containing the address of a facet along with the specific function selectors associated with that facet. To examine the facets and call functions on them, we'll use a tool called [Louperarrow-up-right](https://louper.dev/) . This platform displays all facets and functions related to a Diamond contract and allows us to query data directly from them. Since functions cannot be called on through the Diamond contract directly through a blockchain explorer, Louper provides an efficient and user-friendly way to interact with the Diamond. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#using-louper-to-read-data) Using Louper to Read Data In this example, we'll use Louper to find all the contract symbols available to trade on Thena. First, paste the address into the tool and select the appropriate chain (BNB): ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252F6qjf3dewHcWrngIC6bMm%252Fimage.png%3Falt%3Dmedia%26token%3Df419e867-f40c-4649-a5af-5bb0d7d77c50&width=768&dpr=3&quality=100&sign=a50c1ecb&sv=2) Then, click the **Read** tab, and select the View Facet. This shows all the view functions available to query on the Diamond. ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FQ6ApOwWdVtWiyEC3Lore%252Fimage.png%3Falt%3Dmedia%26token%3D130d9033-3988-40e7-aa15-a603fb43789a&width=768&dpr=3&quality=100&sign=ce0d5a87&sv=2) Now you can query the symbols available to trade on the Diamond using `getSymbols()` with `start` and `size` as parameters: ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FTfpzhnTIsp0cS7rbkZhq%252Fimage.png%3Falt%3Dmedia%26token%3D5f694e86-f0c4-4444-97c4-018f4c0ebd50&width=768&dpr=3&quality=100&sign=4568de59&sv=2) For more information on the View Facet's functions, please refer to the [ViewFacet arrow-up-right](https://app.gitbook.com/o/-McFr-NnfqafWnoj_Y5M/s/YQhBmTCs9MwhhuPQrV5v/~/changes/474/building-on-symm-io/technical-documentation/contracts-documentation-0.8.2/facets/view-facet) documentation (0.8.2). [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#using-subgraphs-to-query-data) Using Subgraphs to Query Data -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- The Graph is a decentralized protocol for indexing and querying blockchain data. You can also query data on the diamond using a subgraph URL provided by SYMM. In this example, we'll query the symbol data using the Apollo Client. **Prerequisites** * Basic understanding of GraphQL * A tool for making HTTP requests, such as Postman, cURL, or a GraphQL client like Apollo Client **Endpoint URL** First identify a suitable endpoint: This endpoint is the analytics endpoint for the SYMMIO Diamond on BNB. **Example Query** To fetch data, send a POST request to the endpoint with the GraphQL query: **Using cURL** ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#using-apollo-client-in-react) **Using Apollo Client in React** #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#install-apollo-client) Install Apollo Client: #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#set-up-apollo-client-and-make-the-query) Set up Apollo Client and make the query: [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#subgraph-urls-by-chain) Subgraph URLs by Chain ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#arbitrum) Arbitrum #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#analytics-subgraph) [Analytics Subgrapharrow-up-right](https://api.goldsky.com/api/public/project_cm1hfr4527p0f01u85mz499u8/subgraphs/arbitrum_analytics/latest/gn) [**Events Subgraph**arrow-up-right](https://api.goldsky.com/api/public/project_cm1hfr4527p0f01u85mz499u8/subgraphs/arbitrum_events/latest/gn) ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#mantle) Mantle #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#analytics-subgraph-1) [Analytics Subgrapharrow-up-right](https://api.goldsky.com/api/public/project_cm1hfr4527p0f01u85mz499u8/subgraphs/mantle_analytics/latest/gn) [**Events Subgraph**arrow-up-right](https://api.goldsky.com/api/public/project_cm1hfr4527p0f01u85mz499u8/subgraphs/mantle_events/latest/gn) ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#bnb) BNB #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#analytics-subgraph-2) [Analytics Subgrapharrow-up-right](https://api.goldsky.com/api/public/project_cm1hfr4527p0f01u85mz499u8/subgraphs/bnb_analytics/latest/gn) [**Events Subgraph**arrow-up-right](https://api.goldsky.com/api/public/project_cm1hfr4527p0f01u85mz499u8/subgraphs/bnb_events/latest/gn) ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#base) Base #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#analytics-subgraph-3) [Analytics Subgrapharrow-up-right](https://api.goldsky.com/api/public/project_cm1hfr4527p0f01u85mz499u8/subgraphs/base_analytics/latest/gn) [**Events Subgraph**arrow-up-right](https://api.goldsky.com/api/public/project_cm1hfr4527p0f01u85mz499u8/subgraphs/base_events/latest/gn) ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#berachain) Berachain #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#analytics-subgraph-4) [Analytics Subgrapharrow-up-right](https://api.goldsky.com/api/public/project_cm1hfr4527p0f01u85mz499u8/subgraphs/bera_analytics/latest/gn) [**Events Subgraph**arrow-up-right](https://api.goldsky.com/api/public/project_cm1hfr4527p0f01u85mz499u8/subgraphs/bera_events/latest/gn) ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#mode) Mode #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#analytics-subgraph-5) [Analytics Subgrapharrow-up-right](https://api.goldsky.com/api/public/project_cm1hfr4527p0f01u85mz499u8/subgraphs/mode_analytics/latest/gn) [**Events Subgraph**arrow-up-right](https://api.goldsky.com/api/public/project_cm1hfr4527p0f01u85mz499u8/subgraphs/mode_events/latest/gn) ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#iota) Iota #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#analytics-subgraph-6) [Analytics Subgrapharrow-up-right](https://api.goldsky.com/api/public/project_cm1hfr4527p0f01u85mz499u8/subgraphs/iota_analytics/latest/gn) [**Events Subgraph**arrow-up-right](https://api.goldsky.com/api/public/project_cm1hfr4527p0f01u85mz499u8/subgraphs/iota_events/latest/gn) ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#polygon) Polygon #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#analytics-subgraph-7) [Analytics Subgrapharrow-up-right](https://api.goldsky.com/api/public/project_cm1hfr4527p0f01u85mz499u8/subgraphs/polygon_analytics/latest/gn) [**Events Subgraph**arrow-up-right](https://api.goldsky.com/api/public/project_cm1hfr4527p0f01u85mz499u8/subgraphs/polygon_events/latest/gn) ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#blast) Blast #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#analytics-subgraph-8) [Analytics Subgrapharrow-up-right](https://api.goldsky.com/api/public/project_cm1hfr4527p0f01u85mz499u8/subgraphs/blast_analytics/latest/gn) [**Events Subgraph**arrow-up-right](https://api.goldsky.com/api/public/project_cm1hfr4527p0f01u85mz499u8/subgraphs/blast_events/latest/gn) [PreviousInstant Withdrawalchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/instant-withdrawal) [NextDocumentation for Frontend Builderschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders) Last updated 25 days ago * [The SYMM Diamond](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#the-symm-diamond) * [Finding Facet Contracts](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#finding-facet-contracts) * [Using Louper to Read Data](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#using-louper-to-read-data) * [Using Subgraphs to Query Data](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#using-subgraphs-to-query-data) * [Using Apollo Client in React](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#using-apollo-client-in-react) * [Subgraph URLs by Chain](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#subgraph-urls-by-chain) * [Arbitrum](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#arbitrum) * [Mantle](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#mantle) * [BNB](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#bnb) * [Base](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#base) * [Berachain](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#berachain) * [Mode](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#mode) * [Iota](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#iota) * [Polygon](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#polygon) * [Blast](https://docs.symm.io/protocol-architecture/documentation-for-traders/interacting-with-symmios-contracts/how-to-query-our-contracts#blast) sun-brightdesktopmoon Copy https://api.studio.thegraph.com/query/62454/analytics_bnb_8_2/version/latest Copy query MyQuery { symbols(first: 3) { blockNumber id name timestamp tradingFee updateTimestamp } } Copy shCopy codecurl -X POST \ -H "Content-Type: application/json" \ -d '{"query":"query MyQuery { symbols(first: 3) { blockNumber id name timestamp tradingFee updateTimestamp } }"}' \ https://api.studio.thegraph.com/query/62454/analytics_bnb_8_2/version/latest Copy npm install @apollo/client graphql Copy import React from 'react'; import { ApolloClient, InMemoryCache, ApolloProvider, useQuery, gql } from '@apollo/client'; const client = new ApolloClient({ uri: 'https://api.studio.thegraph.com/query/62454/analytics_bnb_8_2/version/latest', cache: new InMemoryCache() }); const GET_SYMBOLS = gql` query MyQuery { symbols(first: 3) { blockNumber id name timestamp tradingFee updateTimestamp } } `; const DataComponent = () => { const { loading, error, data } = useQuery(GET_SYMBOLS); if (loading) return

Loading...

; if (error) return

Error :(

; return (

Symbols

{data.symbols.map(symbol => (

{symbol.name}

Block Number: {symbol.blockNumber}

Timestamp: {new Date(symbol.timestamp * 1000).toLocaleString()}

Trading Fee: {symbol.tradingFee}

Update Timestamp: {new Date(symbol.updateTimestamp * 1000).toLocaleString()}

))}
); }; const App = () => ( ); export default App; sun-brightdesktopmoon --- # Querying Info from the SYMMIO Diamond | SYMMIO Protocol Gitbook Because the Diamond delegates function calls to its facets, directly interacting with the Diamond via a blockchain explorer can be challenging. Instead, use specialized tools and subgraphs for querying: ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/querying-info-from-the-symmio-diamond#using-louper) Using Louper [**Louper**arrow-up-right](https://louper.dev/) is a user‑friendly interface that displays all facets and their functions for a Diamond contract. It allows you to: * **Inspect Facets:** The `facets()` function (from the DiamondLoupeFacet) returns an array of facet structs with their addresses and function selectors. * **Query View Functions:** By selecting the “Read” tab and choosing the View Facet, you can query data directly. For example, you can call `getSymbol(symbolId)` to find all the information related to a symbol. ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FRN8IUD5EjmMMNWm4TXUl%252Fimage.png%3Falt%3Dmedia%26token%3Da6593262-16b7-43f7-9ad7-555ee8c9e949&width=768&dpr=3&quality=100&sign=c846eeba&sv=2) Using Louper How to use Louper: 1. **Paste the Diamond Address:** Open [Louperarrow-up-right](https://louper.dev/) and enter the Diamond contract address. You can find a list of all the Diamond addresses here. 2. **Select the Chain:** Choose the correct network (e.g., BNB). 3. **Query Data:** Go to the “Read” tab, select the View Facet, and call functions such as `getSymbol(symbolId)` to fetch trading symbols. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/querying-info-from-the-symmio-diamond#using-goldsky-subgraphs) Using Goldsky Subgraphs We now use Goldsky for our subgraphs. SYMMIO provides subgraph endpoints to query the Diamond’s data. **Example Subgraph Endpoint (BNB):** **Example Query (GraphQL):** ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/querying-info-from-the-symmio-diamond#useful-query-functions) Useful Query Functions The following functions allow you to retrieve information from the SYMMIO diamond. These functions are designed to help applications display real‑time account data and market status. All functions are to be called on the Diamond contract, which will delegate the queries to the appropriate facets. * `**allocatedBalanceOfPartyA(address partyA)**`**:** Returns the allocated balance for a given sub‑account. This balance represents the collateral that is “free”—i.e., not locked in open positions. Full documentation [here](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/view-facet-0.8.4#allocatedbalanceofpartya-and-allocatedbalanceofpartyb) . * `**balanceInfoOfPartyA(address subaccount)**`**:** Provides detailed balance information for Party A. This includes allocated balances, locked balances, pending locked funds, and other relevant metrics. Full documentation [here](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/view-facet-0.8.4#balanceinfoofpartya) . * `**deallocateCooldown(address subaccount)**`**:** Retrieves the cooldown period required before funds can be withdrawn following a deallocation. This period is typically set to 12 hours. * `**getpartyAOpenPositions(address subaccount)**`**:** Returns an array of all open positions held by Party A. Full documentation [here](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/view-facet-0.8.4#getpartyaopenpositions-and-getpartybopenpositions) . * `**getQuote(uint quoteId)**`**:** Fetches detailed information about a specific quote. Use this function to review all parameters of a quote submitted by a user. Full documentation [here](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/view-facet-0.8.4#getquote) . * `**getSymbol(uint symbolId)**`**:** Returns details about a trading symbol, including its name, trading fee, and other configuration parameters. Full documentation [here](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/view-facet-0.8.4#getsymbol-9-and-getsymbols) . * `**partyAPositionsCount(address subaccount)**`**:** Provides the total number of open positions held by Party A. This is useful for quickly assessing account exposure. Full documentation [here](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/view-facet-0.8.4#partyapositionscount) . * `**withdrawCooldownOf(address subaccount)**`**:** Retrieves the withdrawal cooldown timestamp for a sub‑account, indicating when funds will next be available for withdrawal. Full documentation [here](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/view-facet-0.8.4#withdrawcooldownof) . [PreviousIntroduction and Diamond Explainerchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/introduction-and-diamond-explainer) [NextMultiAccountchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/multiaccount) Last updated 29 days ago * [Using Louper](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/querying-info-from-the-symmio-diamond#using-louper) * [Using Goldsky Subgraphs](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/querying-info-from-the-symmio-diamond#using-goldsky-subgraphs) * [Useful Query Functions](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/querying-info-from-the-symmio-diamond#useful-query-functions) sun-brightdesktopmoon Copy https://api.goldsky.com/api/public/project_cm1hfr4527p0f01u85mz499u8/subgraphs/arbitrum_analytics/latest/gn Copy query { symbols(first: 3) { id name blockNumber timestamp tradingFee updateTimestamp } } sun-brightdesktopmoon --- # SYMM Diamond SDK | SYMMIO Protocol Gitbook The SYMM Diamond SDK provides ready-to-use code examples and utilities for interacting with Symmio smart contracts. It aims to simplify the development process by offering modular, well-documented examples that can be adapted to your specific needs. For comprehensive information on contract functions, please refer to the [Contracts Documentation](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4) . To understand the trading flow, consult this [Guide](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio) . This toolkit is ideal for: * DeFi developers working with Symmio protocol * Trading platforms looking to integrate with Symmio * Developers building custom interfaces for decentralized perpetual trading * Anyone wanting to understand how to interact with the SYMM Diamond contract ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/symm-diamond-sdk#features-overview) Features Overview The toolkit provides implementations for key protocol interactions: * **Account Management** * Create and manage sub-accounts via the MultiAccount contract * Deposit and allocate collateral * **Trading Operations** * Send quotes * Open and close positions * Cancel quotes * **View Functions** * Query account balances * Retrieve open positions * Access quote details ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/symm-diamond-sdk#getting-started) Getting Started To begin working with the SYMM Diamond SDK: 1. **Clone the** [**Repository**arrow-up-right](https://github.com/academy17/symm_example_codes) : 2. **Set Up Environment**: Follow the installation instructions in the README to configure your development environment. 3. **Configure Settings**: Copy the [.env.examplearrow-up-right](vscode-file://vscode-app/c:/Users/xdout/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/code/electron-browser/workbench/workbench.html) file to .env and fill in your specific configuration values. 4. **Run Example Scripts**: Query information related to positions and execute functions on the diamond. [PreviousMuonStorage (0.8.4)chevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/symm-app-muon/muonstorage-0.8.4) [NextMuon APIchevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/muon-api) Last updated 25 days ago * [Features Overview](https://docs.symm.io/protocol-architecture/architecture-deep-dive/symm-diamond-sdk#features-overview) * [Getting Started](https://docs.symm.io/protocol-architecture/architecture-deep-dive/symm-diamond-sdk#getting-started) sun-brightdesktopmoon sun-brightdesktopmoon --- # Contracts Documentation 0.8.2 | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2#overview) Overview --------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2#introduction) Introduction Symmetrical Contracts are a new financial trading primitive for trading derivatives permissionlessly and in a trustless manner on the blockchain, inspired by TradFi "Bilateral Agreements". Symmio uses **intent-centric** architecture combined with bilateral OTC to create truly permissionless digitized derivatives for the blockchain economy. Intent-centric means, there is a `PartyA` that requests a trade and a `PartyB` that responds, a PartyA & B match results in both sides putting up collateral (hence bilateral) to execute the trade. The core contracts focus on the sending, receiving, locking and accepting of quotes, as well as the management of the provided collateral by both parties, additionally it also regulates how 3rd Party Liquidators can use Oracles to flag parties as liquidatable in case they fail to provide sufficient capital. The core contracts do not provide a matching engine-- the matching of PartyA and PartyBs can be done via decentralized frontend applications or decentralized driver architecture, as external services. Matching can easily be facilitated by providing an array of whitelisted PartyBs in the quote. This document is a technical guide for SYMM core contracts v.0.8.2, explaining the system's architecture, functionalities, and how to interact with it. It covers the intent-centric design, collateral management, and roles of oracles and liquidators, offering a comprehensive understanding of Symmio's permissionless derivatives on the blockchain. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2#setup-instructions) Setup Instructions To setup the testing environment: * Clone the [Github Repoarrow-up-right](https://github.com/SYMM-IO/protocol-core) . * Copy the `.env.example` file, name it `.env`, and then provide the required variables in that .env file. * Then you can run static tests by using `npx hardhat test` * Also, there is a hardhat task for deploying the contracts. You can run it with `npx hardhat deploy:diamond` [arrow-up-right](https://symmdocs.gitbook.io/symm-smart-contracts-documentation-0.8.2/main-flow) [PreviousArchitecture Deep Divechevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive) [NextMain Flowchevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/main-flow) Last updated 7 months ago * [Overview](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2#overview) * [Introduction](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2#introduction) * [Setup Instructions](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2#setup-instructions) sun-brightdesktopmoon sun-brightdesktopmoon --- # MultiAccount | SYMMIO Protocol Gitbook The MultiAccount contract is a critical component of the SYMM architecture that enables users to create dedicated sub‑accounts. MultiAccounts are contracts typically deployed by **frontend builders** that are whitelisted by hedgers. They enable users to create sub-accounts to trade with. These sub‑accounts are smart contracts **deployed via the MultiAccount contract**. By default, all positions within an account are considered for liquidation, each account is in CROSS. By using sub‑accounts, users can isolate risk by using separate sub‑accounts. ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FXD4kAB5kiGkRCAAriro6%252FFrontend%2520Builder%2520Flow.png%3Falt%3Dmedia%26token%3D1e09643d-0f93-449a-82ac-e44c2de5812c&width=768&dpr=3&quality=100&sign=699be869&sv=2) [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/multiaccount#deploying-a-multiaccount) Deploying a MultiAccount ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Frontend Builders must deploy a MultiAccount and get whitelisted by SYMM. If you're a frontend looking to deploy a MultiAccount, please refer to this [guide](https://symmdocs.gitbook.io/multiaccount-deployment-guide/) . [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/multiaccount#multiaccount-flow) MultiAccount Flow ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/multiaccount#how-it-works) **How It Works:** 1. **Account Creation:** Your wallet calls the MultiAccount contract and specifies which sub‑account to use for executing functions. When you create a sub‑account using `addAccount()`, a new contract is deployed using the current account implementation and linked to your wallet as the owner. 2. **Forwarding Calls:** When you call the `_call()` function on MultiAccount, the call is forwarded to your sub‑account, which in turn sends the call to the SYMM Diamond. Since the Diamond’s logic operates based on the `msg.sender`, actions must originate from the sub‑account to correctly update storage and state. 3. **Parameter Encoding:** All function calls are encoded using the SYMM Diamond’s ABI. This means you must encode the parameters for the desired function using the ABI, and pass that data to the `_call()` method. For example: circle-info The MultiAccount contract address is also known as the affiliate address. The affiliate allows for automatic tracking and claiming of platform fees generated by a frontend. [PreviousQuerying Info from the SYMMIO Diamondchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/querying-info-from-the-symmio-diamond) [NextCreating an Account and Depositing Fundschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/creating-an-account-and-depositing-funds) Last updated 28 days ago * [Deploying a MultiAccount](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/multiaccount#deploying-a-multiaccount) * [MultiAccount Flow](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/multiaccount#multiaccount-flow) * [How It Works:](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/multiaccount#how-it-works) sun-brightdesktopmoon Copy const encodedSendQuoteWithAffiliateData = web3.eth.abi.encodeFunctionCall(sendQuoteWithAffiliateFunctionAbi, sendQuoteParameters); const _callData = [ subAccountAddress, [ encodedSendQuoteData ] ]; const sendQuoteWithAffiliateReceipt = await multiAccountContract.methods._call(..._callData).send({ from: account.address, gas: adjustedGasLimit.toString(), gasPrice: sendQuotePrice.toString() }); sun-brightdesktopmoon --- # Architecture Deep Dive | SYMMIO Protocol Gitbook [Contracts Documentation 0.8.2chevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2) [Contracts Documentation 0.8.3chevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3) [Contracts Documentation 0.8.4chevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4) [SYMM Diamond SDKchevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/symm-diamond-sdk) [Muon APIchevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/muon-api) [PreviousDocumentation for Investorschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-investors) [NextContracts Documentation 0.8.2chevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2) sun-brightdesktopmoon sun-brightdesktopmoon --- # Instant Trading | SYMMIO Protocol Gitbook [Instant Trading (Solvers)](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-solvers) [Rasa Instant Trading Implementation](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation) [Instant Trading Condition Checks](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-condition-checks) [PreviousPerpsHub TP/SL Implementationchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/perpshub-tp-sl-implementation) [NextInstant Trading (Solvers)chevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-solvers) Last updated 9 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Account Abstracted Instant Actions Frontend Builders | SYMMIO Protocol Gitbook This section explains how and why we the ERC-4337 “account abstraction” style login is used for Instant Actions. It will cover: • What ERC-4337 and EIP-1271 bring to the table • The end-to-end flow for Instant Login (fetching a nonce, building a SIWE message, hashing/signing, local EIP-1271 validation, HTTP call) • A complete TypeScript code snippet showing how to call `/login` and obtain an access token [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-trading-for-frontend-builders/account-abstracted-instant-actions-frontend-builders#why-erc-4337-account-abstraction) Why ERC-4337 / Account Abstraction? -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Traditional EOAs (Externally Owned Accounts) sign every transaction with their private key. Smart-contract wallets (Gnosis Safe, Argent, etc.) cannot expose a raw private key. ERC-4337 let’s a smart-contract wallet “`personal_sign`” arbitrary data off-chain, then verify that signature on-chain via the standard EIP-1271 `isValidSignature(bytes32, bytes)` call. **Benefits for Instant Actions:** • Users grant a single “session” signature once. • Solvers can verify authorization on-chain or locally. • No need for the user to re-sign every open/close quote. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-trading-for-frontend-builders/account-abstracted-instant-actions-frontend-builders#high-level-login-flow) High-Level Login Flow ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1. Fetch a nonce from `/nonce/{subAccount}` 2. Construct a SIWE message (domain, wallet address, statement, nonce, issuedAt, expiration) 3. Apply EIP-191 prefix + keccak256 → “ERC-4337 hash” 4. Ask the Safe to personal\_sign the raw SIWE string (SigningMethod.ETH\_SIGN) 5. (Optional) Locally verify the signature via `protocolKit.isValidSignature(erc4337Hash, sig)` 6. POST to `/login` with • `account_address` • `issued_at` • `expiration_time` • `nonce` • `signature` (packed Safe signatures) • `sign_type: “ERC4337”` circle-info The `sign_type` field is essential to obtain an access token with Rasa but not necessarily required for other solvers. Server validates on-chain via EIP-1271 and returns an access token Use that token as Authorization: Bearer for all subsequent instant open/close calls. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-trading-for-frontend-builders/account-abstracted-instant-actions-frontend-builders#detailed-code-example-typescript) Detailed Code Example (TypeScript) * * * When the server receives your POST body, the solver backend will: • Reconstruct the same SIWE message (using your domain, URI, nonce, subaccount, etc.) • Re-compute the ERC-4337 hash (EIP-191 prefix + keccak256) • Call `userSmartWallet.isValidSignature(hash, signature)` on-chain – If it returns `0x1626ba7e`, the signature is valid • If valid, mint you a JWT access\_token with an expiry and your sub-account embedded Using Your Access Token * * * Once you have `access_token`, attach it to every instant-action request: Authorization: Bearer The solver will trust that token (no further on-chain checks) until it expires. You can see how to attach this token to requests in the [Building an Application with SYMMIO](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/sending-a-quote-instant-open) section. [PreviousInstant Trading for Frontend Builderschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-trading-for-frontend-builders) [NextInstant Withdrawal for Frontend Builderschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-withdrawal-for-frontend-builders) Last updated 8 months ago * [Why ERC-4337 / Account Abstraction?](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-trading-for-frontend-builders/account-abstracted-instant-actions-frontend-builders#why-erc-4337-account-abstraction) * [High-Level Login Flow](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-trading-for-frontend-builders/account-abstracted-instant-actions-frontend-builders#high-level-login-flow) * [Detailed Code Example (TypeScript)](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-trading-for-frontend-builders/account-abstracted-instant-actions-frontend-builders#detailed-code-example-typescript) sun-brightdesktopmoon Copy import Safe, { hashSafeMessage } from '@safe-global/protocol-kit' import { SigningMethod } from '@safe-global/types-kit' import { ethers } from 'ethers' import axios from 'axios' async function main() { // ── Configuration ───────────────────────────────────────── const RPC_URL = 'https://rpc.ankr.com/base/…' const SAFE_OWNER = '0x…' // your EOA private key const SAFE_ADDRESS = '0x…' // your Safe contract const SUBACCOUNT = '0x…' // sub-account for login const SOLVER_BASE = 'https://base-hedger82.rasa.capital' const DOMAIN = 'localhost' const ORIGIN = 'http://localhost:3000' const CHAIN_ID = 8453 // 1) initialize Safe SDK (this is the account compatible with ERC4337) const protocolKit = await Safe.init({ provider: RPC_URL, signer: SAFE_OWNER, safeAddress: SAFE_ADDRESS }) // 2) fetch nonce const nonce = await axios .get(`${SOLVER_BASE}/nonce/${SUBACCOUNT}`) .then(r => r.data.nonce) // 3) build SIWE message string (exactly same style as your code) const issuedAt = new Date().toISOString() const expirationTime = new Date(Date.now() + 86_400_000).toISOString() const siweMessage = `${DOMAIN} wants you to sign in with your Ethereum account: ${SAFE_ADDRESS} msg: ${SUBACCOUNT} URI: ${SOLVER_BASE}/login Version: 1 Chain ID: ${CHAIN_ID} Nonce: ${nonce} Issued At: ${issuedAt} Expiration Time: ${expirationTime}` // 4) compute ERC‐4337/EIP-191 hash function encodeERC4337(msg: string): string { const hexMsg = Buffer.from(msg, 'utf8').toString('hex') const prefix = `\x19Ethereum Signed Message:\n${msg.length}` const prefixHex= Buffer.from(prefix, 'utf8').toString('hex') return ethers.keccak256('0x' + prefixHex + hexMsg) } const erc4337Hash = encodeERC4337(siweMessage) console.log('[ERC4337] message hash:', erc4337Hash) // 5) personal_sign via the Safe (EIP-191) const safeMsg = protocolKit.createMessage(siweMessage) const signed = await protocolKit.signMessage( safeMsg, SigningMethod.ETH_SIGN, // personal_sign / EIP-191 SAFE_ADDRESS ) const signature = signed.encodedSignatures() // 6) local EIP-1271 validation (optional) const ok = await protocolKit.isValidSignature(erc4337Hash, signature) if (!ok) throw new Error('Local EIP-1271 check failed') // 7) send the login request const loginBody = { account_address: SUBACCOUNT, issued_at: issuedAt, expiration_time: expirationTime, nonce, signature, sign_type: 'ERC4337' // tell server “use EIP-1271 flow” } const resp = await axios.post( `${SOLVER_BASE}/login`, loginBody, { headers: { 'Content-Type': 'application/json', Origin: ORIGIN, Referer: ORIGIN } } ) console.log('Login response:', resp.data) // → { access_token: 'eyJ…' } } main().catch(console.error) sun-brightdesktopmoon --- # Settlement and Profit Realization | SYMMIO Protocol Gitbook On SYMMIO there’s a distinction between unrealized PnL (what a position is worth on paper) and allocated balance (real funds you can use to pay losses or withdraw). Settlement is the mechanism that lets you turn some of that unrealized profit into real, spendable balance so the system can keep functioning smoothly. A classic situation looks like this: a trader has several winning positions with you, plus one losing position they want to close. On paper they’re in profit overall, but their allocated balance is too low to pay for the loss on the closing trade. If you try to close it directly, the protocol blocks the operation because Party A doesn’t have enough realized collateral. From your point of view, you know they’re good for it—their winners cover the loss—but the contract only sees that their allocated balance is short. That’s where you, as Party B, would invoke a [settlement](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/settlement-0.8.4) . From a risk point of view, settlement is one of your main tools to avoid “good” traders getting stuck. If you never settle, you’ll eventually run into cases where a profitable account can’t close a losing leg because their realized balance is too low. [PreviousHedging Strategieschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/core-concepts/hedging-strategies) [NextInstant Tradingchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/core-concepts/instant-trading) Last updated 25 days ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Facets | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets#enhancing-the-code-structure) Enhancing The Code Structure -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- For each facet, we added an interface and provided documentation for every method, explaining its parameters and offering a brief overview of its usage. [PreviousContracts Documentation 0.8.3chevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3) [NextControl Facetchevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/control-facet) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Building a Solver on SYMMIO | SYMMIO Protocol Gitbook [Solver Implementation Guide (High Level Overview)chevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-implementation-guide-high-level-overview) [1\. Intent Creationchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/1.-intent-creation) [2\. Seeing the Intentchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/2.-seeing-the-intent) [3\. Hedging Off-Chainchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/3.-hedging-off-chain) [4\. Opening/Closing a Position On-Chainchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/4.-opening-closing-a-position-on-chain) [Creating the APIschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis) [Solver Flow Summary Examplechevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-flow-summary-example) [Recommended Architecture for Solverschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/recommended-architecture-for-solvers) [Glossarychevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/glossary) [PreviousInstant Tradingchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/core-concepts/instant-trading) [NextSolver Implementation Guide (High Level Overview)chevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-implementation-guide-high-level-overview) Last updated 1 month ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Instant Trading | SYMMIO Protocol Gitbook [Instant Login (EOA)chevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/instant-login-eoa) [Sending a Quote (Instant Open)chevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/sending-a-quote-instant-open) [Closing a Quote (Instant Close)chevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/closing-a-quote-instant-close) [PreviousClosing a Quotechevron-left](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/closing-a-quote) [NextInstant Login (EOA)chevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/instant-login-eoa) Last updated 11 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Hedging Strategies | SYMMIO Protocol Gitbook At a high level, there are two choices with regards to hedging: **hedge** or **no-hedge**. A fully hedged solver will try to be as close to delta-neutral as possible. When you open a long for a trader on SYMMIO, you might immediately open a matching long on a CEX or another venue. If the trader wins, your off-chain hedge wins by roughly the same amount, so your net result is close to flat. Your profit then comes from spreads, fees, funding, or other edges you’ve built into your quoting model. On the other end of the spectrum, a solver can decide not to hedge at all, or to hedge only partially. In that case you’re acting more like a traditional market maker or prop desk: you take directional views, you might skew your quotes based on what positions you already have, and you accept that your PnL will fluctuate with the market. SYMMIO doesn’t enforce a particular style. The protocol only cares that you stay solvent under its rules. [PreviousIntent Lifecycle and Event Monitoringchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/core-concepts/intent-lifecycle-and-event-monitoring) [NextSettlement and Profit Realizationchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/core-concepts/settlement-and-profit-realization) Last updated 25 days ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Core Concepts | SYMMIO Protocol Gitbook [Role of a Solverchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/core-concepts/role-of-a-solver) [Understanding the Contract Architecturechevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/core-concepts/understanding-the-contract-architecture) [Intent Lifecycle and Event Monitoringchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/core-concepts/intent-lifecycle-and-event-monitoring) [Hedging Strategieschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/core-concepts/hedging-strategies) [Settlement and Profit Realizationchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/core-concepts/settlement-and-profit-realization) [Instant Tradingchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/core-concepts/instant-trading) [PreviousSolver Docs (Github)chevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/solver-docs-github) [NextRole of a Solverchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/core-concepts/role-of-a-solver) sun-brightdesktopmoon sun-brightdesktopmoon --- # Instant Login (EOA) | SYMMIO Protocol Gitbook ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/instant-login-eoa#instant-login-for-instant-open-close) Instant Login for Instant Open/Close Before you can perform instant open or instant close actions, your sub‑account must delegate access to the solver (Party B) for these functions. Once delegated, you must obtain an access token through a two-step SIWE (Sign-In With Ethereum) login flow. This process ensures that you are authorized to execute instant actions and that your request includes a validated expiration date. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/instant-login-eoa#flow-overview) Flow Overview 1. **Delegate Access:** First, delegate access from your sub‑account to the solver’s address so that they can call functions (such as open, request to close, or cancel close) on your behalf. 2. **Fetch a Nonce:** Query the hedger’s [nonce](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#nonce-retrieval) endpoint using your sub‑account address. The nonce ensures the uniqueness of your SIWE message and prevents replay attacks. 3. **Build and Sign the SIWE Message:** Construct a SIWE message that includes your wallet address, the nonce, a statement (the sub-account), and timestamps (issued and expiration). This message must be signed by your wallet to confirm your intent. 4. **Send Login Request:** Submit your signed SIWE message to the hedger’s [`/login`](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#user-login) endpoint. Upon successful verification, you will receive an access token. This token is then used for subsequent instant open or close operations. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/instant-login-eoa#delegating-access) Delegating Access To enable instant actions on the frontend, users must delegate specific functions to solvers so they can perform actions on the user's behalf without requiring signatures for each request. Front-ends should ensure that the following functions are delegated to the solver addresses through the `delegateAccesses()` method on the [MultiAccount](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount#delegateaccesses) contract, passing these function signatures.: * `sendQuote`: **0x7f2755b2** * `sendQuoteWithAffiliate`: **0x40f1310c** * `requestToClosePosition`: **0x501e891f** * `requestToCancelQuote`: **0xa8ffc7ab** * `requestToCancelCloseRequest`: **0xa63b9363** * `allocate`: **0x90ca796b** **After Delegating Access you can proceed with the login process.** #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/instant-login-eoa#example-script) Example Script Below is a Node.js script (using ethers and axios) that demonstrates the nonce fetch and instant login flow: circle-info **Delegation of Access:** Ensure that your sub‑account has already delegated access to the solver for instant actions before starting the login flow. Upon successful login, the response includes an access token. This token must be attached in the headers of any instant open or close requests that you subsequently send. [PreviousInstant Tradingchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading) [NextSending a Quote (Instant Open)chevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/sending-a-quote-instant-open) Last updated 7 months ago * [Instant Login for Instant Open/Close](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/instant-login-eoa#instant-login-for-instant-open-close) * [Flow Overview](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/instant-login-eoa#flow-overview) * [Delegating Access](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/instant-login-eoa#delegating-access) sun-brightdesktopmoon Copy // Load environment variables from a .env file // activeAccount is the sub-account require("dotenv").config(); // Import required libraries: ethers for Ethereum utilities, axios for HTTP requests, and siwe for Sign-In With Ethereum const { ethers } = require("ethers"); const axios = require("axios"); const { SiweMessage } = require("siwe"); // Retrieve the private key from environment variables const PRIVATE_KEY = process.env.PRIVATE_KEY; // Convert the active account address from the env into a checksummed Ethereum address. // Using ethers.getAddress ensures the address format is correct. This is the sub-account. const activeAccount = ethers.getAddress(process.env.activeAccount); const wallet = new ethers.Wallet(PRIVATE_KEY); // Define the base URL of the authentication (solver) server. In this example we'll use Perps Hub on Arbitrum const SOLVER_BASE_URL = "https://www.perps-streaming.com/v1/42161a/0x141269E29a770644C34e05B127AB621511f20109"; const DOMAIN = "localhost"; const ORIGIN = "http://localhost:3000"; const CHAIN_ID = 42161; const LOGIN_URI = `${SOLVER_BASE_URL}/login`; const ISSUED_AT = new Date().toISOString(); const EXPIRATION_DATE = new Date(Date.now() + (24 * 60 * 60 * 10 * 1000)).toISOString(); //Longer expiration //Fetching Nonce from Solver async function getNonce(address) { const url = `${SOLVER_BASE_URL}/nonce/${address}`; const { data } = await axios.get(url); return data.nonce; } // ----------------------------- // MAIN EXECUTION BLOCK // ----------------------------- (async function main() { try { console.log(`\n[1/4] Wallet Address: ${wallet.address}`); console.log(`[1.5/4] Active Account (Checksum): ${activeAccount}`); // Fetch the nonce for the active account from the server const nonce = await getNonce(activeAccount); console.log(`[2/4] Got nonce: ${nonce}`); // Create the SIWE message using the SIWE library const siweMessage = new SiweMessage({ domain: DOMAIN, address: wallet.address, statement: `msg: ${activeAccount}`, uri: LOGIN_URI, version: "1", chainId: CHAIN_ID, nonce: nonce, issuedAt: ISSUED_AT, expirationTime: EXPIRATION_DATE, }); // Convert the SIWE message object to string format for signing const messageToSign = siweMessage.prepareMessage(); console.log("\n[3/4] SIWE message to sign:\n", messageToSign); // Sign the SIWE message using the wallet's private key const signature = await wallet.signMessage(messageToSign); console.log("\nSignature:", signature); // Construct the request body to send to the login endpoint, including the signature and nonce const body = { account_address: activeAccount, expiration_time: EXPIRATION_DATE, issued_at: ISSUED_AT, signature, nonce }; console.log("body: ", body); // Define HTTP headers including content type and origin (used for CORS validation on the server) const headers = { "Content-Type": "application/json", Origin: ORIGIN, Referer: ORIGIN, }; console.log("\n[4/4] Sending login request..."); // Send the login request (POST) to the server with the constructed body and headers const response = await axios.post( `${SOLVER_BASE_URL}/login`, body, { headers } ); console.log("Login response:", response.data); } catch (err) { console.error("Error in SIWE login flow:", err.response?.data || err.message); } })(); sun-brightdesktopmoon --- # Creating an Account and Depositing Funds | SYMMIO Protocol Gitbook In SYMM, managing your trading capital starts with creating a dedicated sub‑account via the [MultiAccount](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/multiaccount) contract. These sub‑accounts allow you to interact with the SYMM system by forwarding your calls through your deployed account contract. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/creating-an-account-and-depositing-funds#step-1-creating-a-sub-account) Step 1: Creating a Sub‑Account 1. **Navigate to the MultiAccount Contract:** * Use your preferred blockchain explorer or development tool to interact with the MultiAccount contract. 2. **Call** `**addAccount()**`**:** * Call `addAccount(string name)` function, passing a name for your sub‑account. * **Example Call:** Copy multiAccount.addAccount("TradingAccount"); 3. **Check Transaction Logs:** * Once the transaction is mined, look for the `AddAccount` event in the transaction logs. An AddAccount event will be emitted: Copy AddAccount(address owner, address account, string name) 4. **Query Your Accounts:** * You can also use the view function `getAccounts(address user, uint256 start, uint256 size)` on the MultiAccount contract to retrieve an array of your sub‑accounts. * **Parameters:** * `user`: Your wallet address. * `start`: The starting index (for pagination). * `size`: The number of accounts to return. * This returns a list of Account structs that include both the sub‑account addresses and their assigned names. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/creating-an-account-and-depositing-funds#step-2-depositing-and-allocating-funds) Step 2: Depositing and Allocating Funds After creating your sub‑account, the next step is to fund it. SYMM uses a two‑step process where you first deposit funds and then allocate those funds for trading. circle-info Use the `depositAndAllocateForAccount()` function on the **MultiAccount** contract rather than the deposit/allocate functions on the Diamond contract to deposit and allocate to a sub-account. 1. **Call** [`**depositAndAllocateForAccount**`](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/multiaccount-0.8.4#depositandallocateforaccount) `**()**`**:** * This function deposits collateral into your sub‑account and immediately allocates it for trading. * **Function Signature:** * **Parameters:** * `account`: The address of your sub‑account. * `amount`: The amount of collateral you wish to deposit (in the token's native decimals). 2. **Process:** * The function retrieves the collateral token address from the Symmio platform. * It then transfers the specified amount from your wallet to the MultiAccount contract. * The contract approves the Symmio contract to spend the collateral. * It calls the `depositFor(account, amount)` function on the Symmio contract. * The amount is converted into 18‑decimals and passed to the `allocate(uint256)` function via an internal call. * **Example Call (JavaScript with web3):** 3. **Events:** * On successful execution, the function emits two events: * **DepositForAccount:** Indicates that funds have been deposited into the sub‑account. * **AllocateForAccount:** Confirms that the deposited funds have been allocated for trading. circle-info The collateral token address can be found by calling `getCollateral()` on the SYMM Diamond's view facet [PreviousMultiAccountchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/multiaccount) [NextSending a Quotechevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote) Last updated 29 days ago * [Step 1: Creating a Sub‑Account](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/creating-an-account-and-depositing-funds#step-1-creating-a-sub-account) * [Step 2: Depositing and Allocating Funds](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/creating-an-account-and-depositing-funds#step-2-depositing-and-allocating-funds) sun-brightdesktopmoon Copy function depositAndAllocateForAccount(address account, uint256 amount) external onlyOwner(account, msg.sender) whenNotPaused; Copy const depositAmount = web3.utils.toWei("10", "ether"); await multiAccountContract.methods .depositAndAllocateForAccount(subAccountAddress, depositAmount) .send({ from: myWalletAddress }); sun-brightdesktopmoon --- # Frequently Used Queries | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#useful-query-functions) Useful Query Functions -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- The following functions allow you to retrieve essential information from the SYMM system. These functions are designed to help frontend applications display account data. All functions are to be called on the Diamond contract, which will delegate the call to the appropriate facets. You can use a diamond inspection tool like [Louperarrow-up-right](https://louper.dev/) to interact with the contracts in a more user-friendly way. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#allocatedbalanceofpartya) `**allocatedBalanceOfPartyA()**` Returns the allocated balance for a given sub‑account. This balance represents the collateral that is “free”—i.e., not locked in open positions. Full documentation [here](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/view-facet-0.8.4#allocatedbalanceofpartya-and-allocatedbalanceofpartyb) . ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#balanceinfoofpartya) `**balanceInfoOfPartyA()**` Provides detailed balance information for Party A. This includes allocated balances, locked balances, pending locked funds, and other relevant metrics. Full documentation [here](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/view-facet-0.8.4#balanceinfoofpartya) . ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#deallocatecooldown) `**deallocateCooldown()**` Retrieves the cooldown period required before funds can be withdrawn following a deallocation. This period is typically set to 12 hours. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#getpartyaopenpositions) `**getpartyAOpenPositions()**` Returns an array of all open positions held by Party A. Full documentation [here](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/view-facet-0.8.4#getpartyaopenpositions-and-getpartybopenpositions) . ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#getquote) `**getQuote()**` Fetches detailed information about a specific quote. Use this function to review all parameters of a quote submitted by a user. Full documentation [here](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/view-facet-0.8.4#getquote) . ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#getsymbol) `**getSymbol()**` Returns details about a trading symbol, including its name, trading fee, and other configuration parameters. Full documentation [here](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/view-facet-0.8.4#getsymbol-9-and-getsymbols) . ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#partyapositionscount) `**partyAPositionsCount()**` Provides the total number of open positions held by Party A. This is useful for quickly assessing account exposure. Full documentation [here](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/view-facet-0.8.4#partyapositionscount) . ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#withdrawcooldownof) `**withdrawCooldownOf()**` Retrieves the withdrawal cooldown timestamp for a sub‑account, indicating when funds will next be available for withdrawal. Full documentation [here](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/view-facet-0.8.4#withdrawcooldownof) . [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#data-structures) Data Structures ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ These data structures form the backbone of SYMM’s trading engine. They define the various states and parameters associated with quotes and positions. When querying the Diamond, functions like `getQuote()` return these structures to provide a complete picture of a trade’s configuration and status. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#structs) Structs -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#lockedvalues) **LockedValues** This structure holds the risk and margin parameters for a quote. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#quote) **Quote** The `Quote` struct contains comprehensive information about a trade request, including pricing, quantities, and state. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#field-explanations) Field Explanations * `**id**`**:** Unique identifier for the quote. * `**partyBsWhiteList**`**:** Array of addresses representing the Party B (hedger/solver) candidates eligible to accept the quote. * `**symbolId**`**:** Identifier for the trading symbol associated with the quote. * [`**positionType**`](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#positiontype) **:** Indicates whether the position is LONG or SHORT. * [`**orderType**`](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#ordertype) **:** Specifies the order type: LIMIT or MARKET. (See Enums) * `**openedPrice**`**:** The price at which Party B opened the position . * `**initialOpenedPrice**`**:** The initial opened price when the position was first executed. * `**requestedOpenPrice**`**:** The price that Party A requested for opening the position (in 18 decimals). * `**marketPrice**`**:** The current market price as provided by the Muon signature (in 18 decimals). * `**quantity**`**:** The total quantity requested by Party A (expressed in 18 decimals). * `**closedAmount**`**:** The amount of the position that has been closed so far (in 18 decimals). * [`**initialLockedValues**`](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#lockedvalues) **:** The original locked values as set by Party A. * [`**lockedValues**`](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#lockedvalues) **:** The current locked risk parameters. In partial fill scenarios, this reflects the remaining locked values after part of the quote has been executed. * `**maxFundingRate**`**:** The maximum funding rate that Party A requested for the quote (in 18 decimals). * `**partyA**`**:** Party A (the trader). * `**partyB**`**:** Party B (the hedger/solver), if assigned. * [`**quoteStatus**`](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#quote) **:** The current state of the quote (e.g., PENDING, OPENED, CLOSED). * `**avgClosedPrice**`**:** The average price at which parts of the quote have been closed. * `**requestedClosePrice**`**:** The price at which Party A requests the position to be closed. * `**quantityToClose**`**:** The amount of the position that Party A intends to close. * `**parentId**`**:** The identifier of a parent quote, used when the quote is partially filled. * `**createTimestamp**`**:** The timestamp when the quote was created. * `**statusModifyTimestamp**`**:** The timestamp of the last update to the quote’s status. * `**lastFundingPaymentTimestamp**`**:** The time at which the last funding payment was charged on this quote. * `**deadline**`**:** The deadline by which the quote must be executed or closed. * `**tradingFee**`**:** The fee associated with trading, deducted from the quote (this is only charged on **open**) * `**affiliate**`**:** The affiliate address associated with the quote, linking the quote to a frontend. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#symbol) Symbol The Symbol struct contains data related to each symbol. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#enums) Enums ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#positiontype) **PositionType** ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#ordertype) **OrderType** ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#quotestatus) **QuoteStatus** [PreviousClosing a Quote (Instant Close)chevron-left](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/closing-a-quote-instant-close) [NextFrontend Builder SDK Setup Guidechevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/frontend-builder-sdk-setup-guide) Last updated 11 months ago * [Useful Query Functions](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#useful-query-functions) * [allocatedBalanceOfPartyA()](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#allocatedbalanceofpartya) * [balanceInfoOfPartyA()](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#balanceinfoofpartya) * [deallocateCooldown()](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#deallocatecooldown) * [getpartyAOpenPositions()](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#getpartyaopenpositions) * [getQuote()](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#getquote) * [getSymbol()](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#getsymbol) * [partyAPositionsCount()](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#partyapositionscount) * [withdrawCooldownOf()](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#withdrawcooldownof) * [Data Structures](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#data-structures) * [Structs](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#structs) * [LockedValues](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#lockedvalues) * [Quote](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#quote) * [Symbol](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#symbol) * [Enums](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#enums) * [PositionType](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#positiontype) * [OrderType](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#ordertype) * [QuoteStatus](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/frequently-used-queries#quotestatus) sun-brightdesktopmoon Copy struct LockedValues { uint256 cva; // Credit Value Adjustment uint256 lf; // Liquidator Fee uint256 partyAmm; // Party A Maintenance Margin uint256 partyBmm; // Party B Maintenance Margin } Copy struct Quote { uint256 id; address[] partyBsWhiteList; uint256 symbolId; PositionType positionType; OrderType orderType; // Price of quote which PartyB opened in 18 decimals uint256 openedPrice; uint256 initialOpenedPrice; // Price of quote which PartyA requested in 18 decimals uint256 requestedOpenPrice; uint256 marketPrice; // Quantity of quote which PartyA requested in 18 decimals uint256 quantity; // Quantity of quote which PartyB has closed until now in 18 decimals uint256 closedAmount; LockedValues initialLockedValues; LockedValues lockedValues; uint256 maxFundingRate; address partyA; address partyB; QuoteStatus quoteStatus; uint256 avgClosedPrice; uint256 requestedClosePrice; uint256 quantityToClose; // handle partially open position uint256 parentId; uint256 createTimestamp; uint256 statusModifyTimestamp; uint256 lastFundingPaymentTimestamp; uint256 deadline; uint256 tradingFee; address affiliate; } Copy struct Symbol { uint256 symbolId; //id string name; bool isValid; //Valid if the symbol is listed uint256 minAcceptableQuoteValue; //Smallest acceptable notional value uint256 minAcceptablePortionLF; //Minimum acceptable fee to be rewarded to the liquidator uint256 tradingFee; //Trading fee, this is only charged on open uint256 maxLeverage; //Max Leverage uint256 fundingRateEpochDuration; //How long each funding rate epoch is uint256 fundingRateWindowTime; //The window of time in which funding can be charged per epoch } Copy enum PositionType { LONG, //0 SHORT //1 } Copy enum OrderType { LIMIT, //0 MARKET //1 } Copy enum QuoteStatus { PENDING, //0 LOCKED, //1 CANCEL_PENDING, //2 CANCELED, //3 OPENED, //4 CLOSE_PENDING, //5 CANCEL_CLOSE_PENDING, //6 CLOSED, //7 LIQUIDATED, //8 EXPIRED, //9 LIQUIDATED_PENDING //10 } sun-brightdesktopmoon --- # Glossary | SYMMIO Protocol Gitbook ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/glossary#hedger-solver-partyb) Hedger / Solver (PartyB) A liquidity provider on SYMMIO who sees user “Intents” (trades) and decides whether to accept or reject them. Can hedge trades off-chain (e.g., with a centralized or decentralized broker) or choose to stay unhedged. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/glossary#broker) Broker Any external platform or strategy a Hedger uses to hedge. This could be a centralized exchange (Binance, ByBit), a DEX, an OTC desk, or even an internal algorithm. SYMMIO does not require Hedgers to hedge; it is entirely optional. Off-chain actions have no bearing on on-chain states or trust assumptions. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/glossary#partya) PartyA A user who creates Intents (trading requests). PartyA trades through a frontend. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/glossary#intent) Intent A proposed trade from PartyA. Examples: “I want to open a LONG position for BTCUSDT at price X with quantity Y.” Hedgers see these Intents on-chain and can lock them if they meet their criteria. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/glossary#off-chain-vs.-on-chain) Off-Chain vs. On-Chain SYMMIO’s on-chain contracts control positions, collateral, liquidations, etc. Off-chain hedging (if any) is the Hedger’s private business logic and does not affect the contract’s rules or solvency checks. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/glossary#directional-exposure) Directional Exposure If a Hedger chooses not to hedge its exposure, it is essentially taking a directional bet on the market. A fully hedged approach (1:1) is “delta-neutral,” meaning the Hedger never maintains directional exposure. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/glossary#position-and-liquidation) Position & Liquidation Once an Intent is opened on-chain, it becomes a position. If either side (PartyA or Hedger) becomes insolvent, a liquidator can step in to close the position forcibly. No trust is placed on the Hedger’s off-chain solvency; only on-chain collateral and UPNL. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/glossary#platform-fee) Platform Fee: Charged to PartyA upon opening a position. The hedger spread is embedded in the price. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/glossary#liquidator-fee-lf) Liquidator Fee (LF) Incentive for liquidators in a forced liquidation. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/glossary#counterparty-valuation-adjustment-cva) Counterparty Valuation Adjustment (CVA) Portion of notional position value paid in case one side gets liquidated—paid to the other side. Read more [here](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/maintenance-margin-cva-calculations) . ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/glossary#funding-rate) Funding Rate A periodic charge, often determined by oracles. If a Hedger or PartyA is short, they may pay a funding rate to the long side (or vice versa). [PreviousRecommended Architecture for Solverschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/recommended-architecture-for-solvers) [NextConditional Orderschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders) Last updated 1 year ago * [Hedger / Solver (PartyB)](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/glossary#hedger-solver-partyb) * [Broker](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/glossary#broker) * [PartyA](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/glossary#partya) * [Intent](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/glossary#intent) * [Off-Chain vs. On-Chain](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/glossary#off-chain-vs.-on-chain) * [Directional Exposure](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/glossary#directional-exposure) * [Position & Liquidation](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/glossary#position-and-liquidation) * [Platform Fee:](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/glossary#platform-fee) * [Liquidator Fee (LF)](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/glossary#liquidator-fee-lf) * [Counterparty Valuation Adjustment (CVA)](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/glossary#counterparty-valuation-adjustment-cva) * [Funding Rate](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/glossary#funding-rate) sun-brightdesktopmoon sun-brightdesktopmoon --- # Solver Flow Summary Example | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-flow-summary-example#detect-intent) Detect Intent ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ The Event Poller sees a user’s limit Intent for BTCUSDT at price X. This event is queued into the Position Manager. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-flow-summary-example#decision-and-lock) Decision & Lock ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ The Position Manager checks risk policy: “Is the price acceptable? Do we have enough allocated balance with the user? Are we whitelisted?” If yes, requests Web3 Agent to call `allocateAndLockQuote()`. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-flow-summary-example#broker-hedge) Broker Hedge ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- Simultaneously, the Position Manager instructs the Broker-Order Maker: “Place a limit order on Binance at price X for the same quantity.” The Broker-Order Monitoring module watches for partial fills or a fill event from the exchange. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-flow-summary-example#open-position-on-chain) Open Position On-Chain ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Once the broker fill is confirmed (full or partial), the Position Manager calls `openPosition()`. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-flow-summary-example#user-closing) User Closing ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- At some point, PartyA requests a limit close. The Position Manager again places a corresponding close order on Binance. When the broker fill is confirmed, the Hedger calls fillCloseRequest() on-chain. The position is fully closed on both the broker and SYMMIO sides. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-flow-summary-example#auditor-optional) Auditor (Optional) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- A Position Validator confirms the final state matches: “Broker: no open position, Hedger DB: position closed, On-chain: position closed.” Monitoring & Developer Alerts remain watchful in case any mismatch arises (e.g., on-chain position open but broker order canceled, etc.). ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FRDs6PRV38gSZDCkvF9aP%252Fimage.png%3Falt%3Dmedia%26token%3D9931e2f6-da91-49f0-b292-4e0d3afaed22&width=768&dpr=3&quality=100&sign=a6700502&sv=2) **Recommended Architecture for the Hedger** **Green objects** codes will be open sourced and provided by the SYMMIO team (ETA Nov/Dec 2023) **Red objects** should be developed by the MarketMaker. **Purple objects** are optional. [PreviousPOST Position Statechevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/post-position-state) [NextRecommended Architecture for Solverschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/recommended-architecture-for-solvers) Last updated 1 year ago * [Detect Intent](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-flow-summary-example#detect-intent) * [Decision & Lock](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-flow-summary-example#decision-and-lock) * [Broker Hedge](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-flow-summary-example#broker-hedge) * [Open Position On-Chain](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-flow-summary-example#open-position-on-chain) * [User Closing](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-flow-summary-example#user-closing) * [Auditor (Optional)](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-flow-summary-example#auditor-optional) sun-brightdesktopmoon sun-brightdesktopmoon --- # Overview | SYMMIO Protocol Gitbook The Symmio Options Protocol is a decentralized, intent-based options trading system that enables peer-to-peer options trading without the need for traditional market makers. Built on the Ethereum Virtual Machine (EVM), the protocol implements a bilateral settlement mechanism, allowing two parties (Party A and Party B) to engage in option contracts with advanced collateral management. The system employs the EIP-2535 Diamond Pattern architecture, organizing functionality into modular facets while maintaining shared storage. Symmio options are implemented as ERC-721 NFTs, granting holders the right (but not the obligation) to buy or sell underlying tokens at specified prices and expiration dates. [PreviousGlossarychevron-left](https://docs.symm.io/protocol-architecture/glossary) [NextCore Financial Conceptschevron-right](https://docs.symm.io/options-protocol-architecture/core-financial-concepts) Last updated 2 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Depositing and Allocating Collateral | SYMMIO Protocol Gitbook Before trading, you need to deposit collateral to your sub-account.The process involves two steps: 1. Approving the MultiAccount contract to spend your ERC20 tokens 2. Calling the `depositAndAllocateForAccount` function More information on this process [here](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/creating-an-account-and-depositing-funds) : Copy # Approve the MultiAccount contract to spend your tokens client.approve_erc20(CONFIG["multiaccount_address"], deposit_amount) # Deposit and allocate the tokens to your sub-account client.deposit_and_allocate_for_account(sub_account_address, deposit_amount) The deposit amount should be in wei (1 ETH = 10^18 wei). For example, to deposit 100 tokens, use: Copy deposit_amount = Web3.to_wei(100, "ether") **Example Code:** Copy from dotenv import load_dotenv import os import json from web3 import Web3 load_dotenv() CONFIG = { "rpc_url": os.getenv("RPC_URL"), "private_key": os.getenv("PRIVATE_KEY"), "multiaccount_address": os.getenv("MULTIACCOUNT_ADDRESS"), "erc20_address": os.getenv("COLLATERAL_ADDRESS"), } class MultiAccountClient: def __init__(self, config): self.config = config multiaccount_abi_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "abi", "MultiAccount.json")) erc20_abi_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "abi", "ERC20.json")) with open(multiaccount_abi_path, "r") as abi_file: self.multiaccount_abi = json.load(abi_file) with open(erc20_abi_path, "r") as abi_file: self.erc20_abi = json.load(abi_file) self.w3 = Web3(Web3.HTTPProvider(config["rpc_url"])) self.account = self.w3.eth.account.from_key(config["private_key"]) self.multiaccount = self.w3.eth.contract( address=Web3.to_checksum_address(config["multiaccount_address"]), abi=self.multiaccount_abi ) self.erc20 = self.w3.eth.contract( address=Web3.to_checksum_address(config["erc20_address"]), abi=self.erc20_abi ) def approve_erc20(self, spender_address: str, amount: int): """Approve the MultiAccount contract to spend ERC20 tokens""" try: txn = self.erc20.functions.approve( Web3.to_checksum_address(spender_address), amount ).build_transaction({ "from": self.account.address, "nonce": self.w3.eth.get_transaction_count(self.account.address, "pending"), "gas": 100000, "gasPrice": self.w3.eth.gas_price, }) signed_txn = self.w3.eth.account.sign_transaction(txn, private_key=self.config["private_key"]) tx_hash = self.w3.eth.send_raw_transaction(signed_txn.raw_transaction) print(f"Approval transaction sent: {tx_hash.hex()}") self.w3.eth.wait_for_transaction_receipt(tx_hash) print("Approval transaction confirmed.") except Exception as e: print(f"Error approving ERC20 tokens: {e}") raise def deposit_and_allocate_for_account(self, account_address: str, amount: int): """Deposit and allocate funds for a specific account""" try: txn = self.multiaccount.functions.depositAndAllocateForAccount( Web3.to_checksum_address(account_address), amount ).build_transaction({ "from": self.account.address, "nonce": self.w3.eth.get_transaction_count(self.account.address, "pending"), "gas": 300000, "gasPrice": self.w3.eth.gas_price, }) signed_txn = self.w3.eth.account.sign_transaction(txn, private_key=self.config["private_key"]) tx_hash = self.w3.eth.send_raw_transaction(signed_txn.raw_transaction) print(f"Deposit and allocate transaction sent: {tx_hash.hex()}") self.w3.eth.wait_for_transaction_receipt(tx_hash) print("Deposit and allocate transaction confirmed.") except Exception as e: print(f"Error depositing and allocating for account: {e}") raise def main(): """Main function to demonstrate depositing and allocating for an account""" client = MultiAccountClient(CONFIG) sub_account_address = "0x4921a5fC974d5132b4eba7F8697236fc5851a3fA" deposit_amount = Web3.to_wei(100, "ether") #Depositing 100 tokens print("Approving ERC20 tokens...") client.approve_erc20(CONFIG["multiaccount_address"], deposit_amount) print("Depositing and allocating for account...") client.deposit_and_allocate_for_account(sub_account_address, deposit_amount) if __name__ == "__main__": main() [PreviousCreating a Sub-Accountchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/creating-a-sub-account) [NextDelegating Access to the Solverchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-traders/learn-how-to-build-a-trading-bot-using-symmio/delegating-access-to-the-solver) Last updated 5 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # 1. Intent Creation | SYMMIO Protocol Gitbook The lifecycle of an Intent begins with **PartyA** (traders) initiating a trade request on the SYMMIO platform by specifying key parameters for the desired trade. This request, known as an "Intent," is broadcast on-chain via the platform's core contracts. Once posted, it becomes visible to **PartyB**, the hedgers or market makers, who have the option to review and respond. Hedgers/Solvers monitor these on-chain requests using tools such as event listeners or subgraphs. They evaluate the parameters of each Intent against their strategy, risk profile, and market conditions. If a hedger decides to proceed, they can claim the Intent and respond by submitting a corresponding transaction on-chain. This transaction indicates their agreement to the proposed terms or includes any modifications they deem necessary, such as an adjusted price or collateral requirement. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/1.-intent-creation#partya-sendquote-flow-overview) PartyA SendQuote Flow Overview ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Creates a Sub-Account: Through A [MultiAccount](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount) contract deployed by a frontend. * Deposits and Allocates Collateral: To the created sub-account. * `sendQuote()` with the desired parameters. This requires two things: * A Muon Signature is fetched verifying the partyA's ability to open a position, and the price of the asset (this is usually handled by the frontend) * The transaction is encoded via the `_call()` function on the MultiAccount contract, which will forward to `sendQuote()` on the Diamond contract. After being whitelisted as a PartyB by the SYMMIO developers, hedgers can use the Cloverfield interface to allow them to send quotes using the `sendQuote` functionality. This interface enables hedgers to easily verify the functionality of their service and test their strategies and workflows in real time. More documentation on sendQuote is available here ([0.8.2](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/facets/partya-facet) , [0.8.3](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/partya-facet) ) [PreviousSolver Implementation Guide (High Level Overview)chevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-implementation-guide-high-level-overview) [Next2\. Seeing the Intentchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/2.-seeing-the-intent) Last updated 1 month ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Solver Addresses & Endpoints | SYMMIO Protocol Gitbook [Perps Hubchevron-right](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/perps-hub) [Rasa Capitalchevron-right](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/rasa-capital) [Rasa Capital (Zero Spread)chevron-right](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/rasa-capital-zero-spread) [Zenithchevron-right](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/zenith) [PreviousSonicchevron-left](https://docs.symm.io/protocol-architecture/contract-addresses/sonic) [NextPerps Hubchevron-right](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/perps-hub) sun-brightdesktopmoon sun-brightdesktopmoon --- # PartyB | SYMMIO Protocol Gitbook ### [hashtag](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/partyb#partyb-solvers-hedgers-counterparty-or-marketmaker-describe-the-same-entity-in-symmio-they-describe) PartyB, Solvers, Hedgers, Counterparty or MarketMaker describe the same entity in Symmio, they describe the Executing party of a Trade contrarian to the requesting entity, which would be referred to as PartyA, Trader or User. [hashtag](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/partyb#partyb) PartyB ------------------------------------------------------------------------------------------------------------------ PartyB is the TradFi term used to describe a counterparty in a Swap Agreement. It was the first term we gave to counterparties in the Symmio ecosystem, a PartyA is the Trader that initiates the trade, a PartyB is the counterparty that accepts the trade. In Symmio PartyB is the counterparty which is declared as an Address on the Symmio core contract. [hashtag](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/partyb#solver) Solver ------------------------------------------------------------------------------------------------------------------ Solver is the established industry term for counterpartys in intent-based systems, PartyBs in Symmio can also be referred as Solver, it makes sense to especially refer to the onchain parts of a PartyB as "Solver", there could be Counterparties that exist as multiple entities, solvers that handle the onchain execution and MarketMakers or Hedgers that handle offchain liquidity. [https://www.linkedin.com/pulse/realizing-user-centric-experiences-promise-intent-based-bao-ngoc-le/arrow-up-right](https://www.linkedin.com/pulse/realizing-user-centric-experiences-promise-intent-based-bao-ngoc-le/) [PreviousProtocol higher level architecturechevron-left](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture) [NextSolver Settingschevron-right](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/solver-settings) Last updated 25 days ago * [PartyB, Solvers, Hedgers, Counterparty or MarketMaker describe the same entity in Symmio, they describe the Executing party of a Trade contrarian to the requesting entity, which would be referred to as PartyA, Trader or User.](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/partyb#partyb-solvers-hedgers-counterparty-or-marketmaker-describe-the-same-entity-in-symmio-they-describe) * [PartyB](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/partyb#partyb) * [Solver](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/partyb#solver) sun-brightdesktopmoon sun-brightdesktopmoon --- # Contract Addresses | SYMMIO Protocol Gitbook [Polygon (0.2.1)chevron-right](https://docs.symm.io/options-protocol-architecture/contract-addresses/polygon-0.2.1) [PreviousSymmioPartyB Contractchevron-left](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/symmiopartyb-contract) [NextPolygon (0.2.1)chevron-right](https://docs.symm.io/options-protocol-architecture/contract-addresses/polygon-0.2.1) sun-brightdesktopmoon sun-brightdesktopmoon --- # Role of a Solver | SYMMIO Protocol Gitbook On SYMMIO, traders don’t match against a central order book. They express intents, which are requests which say “I want to go long or short this market, here’s my size, my price, and the counterparties I wish to trade with._”_ Those intents are picked up by a network of independent counterparties called [solvers](https://docs.symm.io/protocol-architecture/glossary) . A solver is the party that decides whether to take the other side of a trade, quote prices, and manage the risk that comes with it. When you run a solver, you are acting as the [Party B](https://docs.symm.io/protocol-architecture/glossary) in the protocol. Your address is whitelisted on the SYMMIO contracts so you are allowed to lock quotes, open positions, and hold shared risk with traders. Once a trader sends a quote on-chain, your infrastructure listens for the event, pulls in the quote details, and runs internal checks: is this symbol supported, is the account allowed, do you have enough collateral, and does the price fit your strategy? If everything passes, you lock the quote and open the position on-chain, optionally hedging the exposure elsewhere at the same time. Solvers are also responsible for collateral management and solvency on their side. Before opening or closing a position, the contracts and [Muon oracle](https://docs.symm.io/protocol-architecture/architecture-deep-dive/muon-api) verify that both you and the trader have enough margin, and that the prices you’re using are valid. You decide how much capital to allocate to each trader, how much open interest to allow per market, and when to settle unrealized profits so that positions can be safely closed. Your risk model is entirely up to you, however it must conform to the protocol's solvency rules enforced on the contracts. Solvers also play a key role in the user experience. Frontend Applications rely on solver APIs to show things like markets, prices and funding data. When a trader wishes to do things like [instantly open a trade](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/instant-trading) , they delegate certain functions to you so that you can open and close positions without asking them to sign every transaction. When they'd like to set a [take profit or stop loss](https://docs.symm.io/protocol-architecture/documentation-for-traders/concepts-in-symmio/using-take-profit-and-stop-loss) , your **conditional orders** service will watch the market and submit the close request when their conditions are hit. From the trader’s perspective, the frontend application feels like a fast, seamless exchange. [PreviousCore Conceptschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/core-concepts) [NextUnderstanding the Contract Architecturechevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/core-concepts/understanding-the-contract-architecture) Last updated 25 days ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Intent Lifecycle and Event Monitoring | SYMMIO Protocol Gitbook Every trade on SYMMIO starts with an **intent** from a trader. Party A sends a quote on-chain that says, in effect: _“I want to trade this symbol, in this direction, with this size and these conditions.”_ That quote includes things like symbol ID, position type (long/short), order type (market/limit), requested price, quantity, and the list of Party B addresses they’re willing to trade with. Once the transaction is confirmed, the quote is stored in the diamond’s state and an event is emitted. From that moment on, it’s visible to every solver listening. On your side, a core piece of your solver is an [**event listener**](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/2.-seeing-the-intent) that watches the chain for these quote events. Whenever a new quote shows up where your Party B address is whitelisted, your system pulls in the full details of that intent and hands it off to your risk and pricing logic. This is where you decide: _Do I want this trade or not?_ You might check symbol settings, notional limits, spread, available hedging inventory, or internal risk scores before you make a decision. If you like the intent, the next step is to [**lock**](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/4.-opening-closing-a-position-on-chain) it. Locking a quote tells the protocol, “I’m taking this one, no one else can fill it now.” You allocate the required collateral on your side, call the appropriate Party B function on the diamond. Assuming all checks pass, the quote status moves from `PENDING` to `LOCKED`. From there you either immediately open the position or, in a two-step flow, open it shortly after once your hedge is in place. If you only want to fill part of the size, you open a partial amount and the remaining quantity can be re-posted as a new quote. Solvers ought to track the life cycle of each quote. This is done by listening for events that tell you when a trader has requests to cancel their quote, to close a position, or cancel that close request. You monitor status changes like `OPENED`, `CLOSE_PENDING`, `CANCELED`, and `LIQUIDATED`, and keep your own internal state in sync. When something unexpected happens (like a force close or a failed transaction) you use those same events to reconcile your positions and risk engine. [PreviousUnderstanding the Contract Architecturechevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/core-concepts/understanding-the-contract-architecture) [NextHedging Strategieschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/core-concepts/hedging-strategies) Last updated 25 days ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Instant Trading | SYMMIO Protocol Gitbook Instant trading is where solvers really shape the user experience. From a trader’s perspective, it feels like a CEX: they click “Buy” or “Sell” and the trade just goes through, without a wallet popup for every action. Under the hood, that’s only possible because the trader has delegated certain permissions to you, the solver, and you’ve wired your systems to act immediately when they send an instruction. The flow starts with the trader creating a sub-account through the Multi-Account contract and then delegating a small set of functions to your Party B address. They approve things like `sendQuote`, `requestToClosePosition`, `requestToCancelQuote`, and `requestToCancelCloseRequest` for that sub-account. This doesn’t give you custody of their funds; it just lets you submit the same trading calls they could make themselves, without needing their wallet to sign every time. On top of that, they go through a login flow (often SIWE-based), where they sign a message off-chain to prove they control the account. Your backend verifies that signature and returns an access token that frontends can attach to every API call. Once that is in place, instant trading becomes possible through simple [API calls](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-solvers) . When the user hits “Open Long 10x” in the UI, the frontend sends a request to your hedger API with their sub-account, market, size, and any extra parameters. Your system does all the same [work as it would when opening a regular position](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-condition-checks) and then calls the SYMMIO contracts directly using the delegated functions. There is no pause to wait for a wallet signature because you are the one submitting the transaction. When the user hits “Close,” the same thing happens: the frontend calls you, you verify, and you submit the close on-chain on their behalf. [PreviousSettlement and Profit Realizationchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/core-concepts/settlement-and-profit-realization) [NextBuilding a Solver on SYMMIOchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio) Last updated 25 days ago sun-brightdesktopmoon sun-brightdesktopmoon --- # 3. Hedging Off-Chain | SYMMIO Protocol Gitbook If the Hedger chooses a 1:1 approach, it can place a matching order on its preferred broker (Binance, BYBIT) to remain delta-neutral. Once the broker fill is confirmed, the Hedger proceeds on-chain. circle-info Hedging the position opened on-chain elsewhere is entirely optional. [Previous2\. Seeing the Intentchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/2.-seeing-the-intent) [Next4\. Opening/Closing a Position On-Chainchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/4.-opening-closing-a-position-on-chain) Last updated 1 month ago sun-brightdesktopmoon sun-brightdesktopmoon --- # How to Add a Market as a Solver | SYMMIO Protocol Gitbook ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/how-to-add-a-market-as-a-solver#listing-a-market) Listing a Market #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/how-to-add-a-market-as-a-solver#step-1-modify-the-muon-oracle) Step 1: Modify the Muon Oracle To add a new market as a solver, first add the new price source to the Muon Oracle. This involves modifying the function to fetch prices from the new source and then integrating it with the existing price fetching function. The repo to modify can be found [herearrow-up-right](https://github.com/SYMM-IO/protocol-muon-crypto) . Here's the relevant code to modify if the market isn't available on Binance, Kucoin or MEXC: Copy async function getNewExchangePrices() { return withSpan( getNewExchangePrices.name, spanTypes.newExchangePriceFetch, // You need to define this span type async function () { const newExchangeUrl = priceUrl + "/newExchange"; let data; try { const result = await axios.get(newExchangeUrl); data = result.data; } catch (e) { console.log(e); throw new Error("FAILED_TO_GET_NEW_EXCHANGE_PRICES"); } const pricesMap = {}; data.forEach((el) => { try { pricesMap[el.symbol] = scaleUp(Number(el.price).toFixed(10)).toString(); } catch (e) {} }); return pricesMap; }, [] ); } const getSorucePrices = { binance: getBinancePrices, kucoin: getKucoinPrices, mexc: getMexcPrices, newExchange: getNewExchangePrices, // Add the new exchange function here };s #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/how-to-add-a-market-as-a-solver#step-2-make-a-pull-request) Step 2: Make a Pull Request Once the necessary changes are made to the Muon Oracle, the next step is to create a pull request to integrate these changes into the SYMMIO codebase. Ensure that your pull request includes: * A detailed description of the changes made. * Any dependencies or configurations required for the new symbol. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/how-to-add-a-market-as-a-solver#step-3-add-the-symbol-to-solver-endpoints) Step 3: Add the Symbol to Solver Endpoints Update your solver API endpoints to include the new symbol. This ensures that the frontends are made aware of the new markets you've made available for users to trade. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/how-to-add-a-market-as-a-solver#step-4-add-the-market-on-the-contracts) Step 4: Add the Market on the Contracts This step is currently permissioned, but the goal is to make it permissionless. For now, an admin of the SYMMIO contract can add a new market by calling the [`addSymbol()`](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/control-facet-0.8.4#addsymbol-and-addsymbols) function with all the required parameters. Example: To add a new market for NEWUSDT: ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/how-to-add-a-market-as-a-solver#de-listing-a-market) De-Listing a Market **Step 1: Announce the Delisting** The first step in de-listing a market is to communicate the upcoming changes to both frontends (FEs) and users. This includes announcing: * The specific markets that will be delisted. * The date when the delisting will take effect. * Any other relevant information such as the last date to open new positions in these markets. **Step 2: Stop Accepting New Positions** After the announcement, you should ensure that no new positions are accepted for the markets that are scheduled for delisting. This can be internally achieved by modifying the relevant API endpoints so that these markets are no longer accepting quotes. Step 3: Activating the Emergency Status In the current implementation, there is a [function](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/control-facet-0.8.4#emergency-mode) that allows the admin to activate and deactivate the emergency status of your partyB. This emergency status enables you to manage the closing of existing positions for the delisted markets. To do this: 1. **Activate Emergency Status**: Use the contract to activate the emergency status for the relevant markets. This should be done once the delisting date is reached or as part of the delisting process. 2. **Close Positions**: Existing positions should be closed using the Muon market price as the settlement price. After delisting, the Muon market price will default to the settlement price of Binance. You typically have a one-month window after the delisting to ensure all positions are closed in an orderly fashion. Information on how the settlement price is calculated can be found [herearrow-up-right](https://www.binance.com/en/support/faq/delivery-and-settlement-of-quarterly-futures-a3401595e1734084959c61491bc0dbe3) : [PreviousInstant Trading Condition Checkschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-condition-checks) [NextFetching Gas Prices Scriptchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script) Last updated 9 months ago * [Listing a Market](https://docs.symm.io/protocol-architecture/documentation-for-solvers/how-to-add-a-market-as-a-solver#listing-a-market) * [De-Listing a Market](https://docs.symm.io/protocol-architecture/documentation-for-solvers/how-to-add-a-market-as-a-solver#de-listing-a-market) sun-brightdesktopmoon Copy addSymbol( "NEWUSDT", 10e18, // minAcceptableQuoteValue 1e17, // minAcceptablePortionLF 5e16, // tradingFee (0.05%) 50, // maxLeverage 3600, // fundingRateEpochDuration (1 hour) 1800 // fundingRateWindowTime (30 minutes) ); sun-brightdesktopmoon --- # Understanding the Contract Architecture | SYMMIO Protocol Gitbook At the center of the protocol is a diamond contract (EIP-2535). This serves as a single “hub” address that exposes many different modules, called facets. Each facet handles one area of the system: opening and closing positions, funding, liquidations, force actions, viewing state, and so on. When you call the diamond, it forwards your call to the right facet behind the scenes while sharing the same storage. For you as a solver, that means you mostly interact with one main contract address, but you still get access to all the protocol’s features. On the trader side, SYMMIO uses a [**MultiAccount**](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/multiaccount) system. Instead of trading directly from their normal wallet, a user creates one or more sub-accounts. Each sub-account is its own little trading environment with its own margin and positions. This lets traders isolate risk: a liquidation event in one sub-account doesn’t automatically liquidate everything else. As a solver, you will see intents and positions tied to these sub-account addresses (Party A), not the user’s main wallet. When traders enable instant trading or conditional orders, they delegate permission from their sub-account to you via the MultiAccount contract so that you can request closes, cancels, or instant opens on their behalf. Your address acts as Party B inside this same architecture. Before you can trade, your solver must be whitelisted as a Party B on the diamond. Once that’s done, you can use the Party B functions: locking quotes, opening positions, closing, settling, charging funding, and so on. The protocol tracks your allocated balances, reserve vault, and open exposure in shared storage, alongside every Party A account. Whenever you call an action, the facets check both sides for solvency and valid pricing, often with the help of Muon signatures. Finally, data like symbols, minimum position value, funding configuration, open interest caps etc. is exposed through [view functions on the diamond](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/view-facet-0.8.4) . The solver architecture listens for events from the diamond, reads state from the Diamond, and then reacts with its own custom logic. [PreviousRole of a Solverchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/core-concepts/role-of-a-solver) [NextIntent Lifecycle and Event Monitoringchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/core-concepts/intent-lifecycle-and-event-monitoring) Last updated 25 days ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Main Flow | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/main-flow#deposit) Deposit ----------------------------------------------------------------------------------------------------------------------------------------- To start sending and accepting INTENTs, the user needs to deposit collateral into the Symmio contracts. **Allocate:** After depositing collateral, the user cannot trade with it yet. It is required to allocate that money to a subaccount, then he will be able to start trading, subaccounts are isolated instances. As Symmio is 100% economically sound, all PartyA <> PartyB instances are isolated in subaccounts. All collateral deposited into a subaccount is in cross with all positions opened using that subaccount. To have an isolated position, a separate subaccount should be created. Subaccounts also enable further customization down the road, where collateral could be allocated to a specific contract instance, with customized code written by PartyA or PartyB. [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/main-flow#send-quote-send-intent) Send Quote (Send INTENT) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- To start the process of opening a trade, he chooses to open long or short positions by giving some criteria (symbol, price etc.) & by calling `sendQuote` function. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/main-flow#party-b-sees-the-position-request) Party B sees the position request At this time, Party B will see the request, and he can decide whether to accept or ignore it. If he accepts it, first he locks(reserves) the quote through `lockQuote` and then calls `openPosition`. At the time of locking(reserving) the quote before opening the position, no other party Bs can accept the quote until it gets unlocked for any possible reason. (user requests to cancel or Party B cannot open the position) Reserving Quotes is a "training wheel" feature to make it easier for MarketMakers to respond to quotes, by giving them the ability to reserve a quote, then fulfill their needed hedging operations and then fill the quote afterwards. It could be removed in later versions. **Cancel Quote:** It is possible that the user wants to cancel his quote(intent) before it gets opened. If the quote isn’t locked(reserved), then it will be canceled immediately. But if it’s locked and isn’t opened yet, depending if it’s partially filled or not, the quote will be canceled. (If it was partially filled already, the unfilled part will be canceled, and the partially filled will be opened.) [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/main-flow#open-position) Open Position ----------------------------------------------------------------------------------------------------------------------------------------------------- After locking(reserving) a quote if nothing unusual happens, the position will be opened by PartyB calling `openPosition` [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/main-flow#close-request) Close Request ----------------------------------------------------------------------------------------------------------------------------------------------------- The PartyA (user) can close the position whenever they want to. This will happen by calling `requestToClosePosition`, Please note that PartyBs are not able to request to close a position. [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/main-flow#cancel-close-request) Cancel Close Request ------------------------------------------------------------------------------------------------------------------------------------------------------------------- It is possible for the user to cancel their close request (or when using limit order for closing if he wants to make any changes to his order) In these cases if the close request isn’t filled yet, it will be canceled and the position status would change from close pending to a regular position. But if the close request was already partially filled, the already filled portion will remain closed and the remaining amount will be added back to his position and re-opened. [arrow-up-right](https://symmdocs.gitbook.io/symm-smart-contracts-documentation-0.8.2) [PreviousContracts Documentation 0.8.2chevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2) [NextThe SYMM Diamondchevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/the-symm-diamond) Last updated 1 year ago * [Deposit](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/main-flow#deposit) * [Send Quote (Send INTENT)](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/main-flow#send-quote-send-intent) * [Party B sees the position request](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/main-flow#party-b-sees-the-position-request) * [Open Position](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/main-flow#open-position) * [Close Request](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/main-flow#close-request) * [Cancel Close Request](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/main-flow#cancel-close-request) sun-brightdesktopmoon sun-brightdesktopmoon --- # Solver Settings | SYMMIO Protocol Gitbook > **Disclaimer:** > > **The configurations and parameters outlined below pertain specifically to the Rasa - Demo Solver setting and may not reflect the settings, requirements, or methodologies adopted by other Solvers/Hedgers. It's important to note that different Solvers might utilize distinct CVA (Credit Value Adjustment) formulas or have varying requirements. Additionally, Market Makers or Solvers are under no obligation to disclose their respective calculation methodologies.** > > Learn more about: [Max Leverage](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/max-leverage) > for each Market provided by Rasa. > > & how [Maintenance Margin (CVA) Calculations](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/maintenance-margin-cva-calculations) > are being done. [PreviousPartyBchevron-left](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/partyb) [NextMax Leveragechevron-right](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/max-leverage) Last updated 25 days ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Facets | SYMMIO Protocol Gitbook Facets are a key component in the diamond architecture, designed to modify the storage of the diamond for enhanced upgradeability. Each facet contract is paired with an associated implementation contract that manages the logic component, simplifying updates and modifications to the system's functionality. The following sections delve into the specifics of SYMM's facet contracts, outlining the functions within each. [PreviousThe SYMM Diamondchevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/the-symm-diamond) [NextAccount Facetchevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/facets/account-facet) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Closing a Quote | SYMMIO Protocol Gitbook Closing a quote is a critical step for Party A to exit an open position. The process involves sending a close request that specifies which portion of the position to close, at what price, and by when. Similar to sending a quote, you must encode your function call with the SYMM Diamond’s ABI and forward it via your MultiAccount contract. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/closing-a-quote#function-signature) Function Signature Copy function requestToClosePosition( uint256 quoteId, uint256 closePrice, uint256 quantityToClose, OrderType orderType, uint256 deadline ) external; [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/closing-a-quote#parameter-breakdown) Parameter Breakdown ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/closing-a-quote#quoteid) `**quoteId**` The unique identifier of the quote that you want to close. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/closing-a-quote#closeprice) `**closePrice**` For **LIMIT** orders: This is the exact price (in 18 decimals) at which you wish to open the position. For **MARKET** orders: The price a quote is opened at includes the spread that a solver charges. In order for your MARKET quote to be accepted, you should send an price slightly adjusted from the current market price depending on the position type. This is an adjusted price includes a slippage buffer (e.g., 5%). * **For LIMIT orders:** This is the price at which you wish to close the position, expressed in 18 decimals. **Important:** If you are using a MARKET order (where a slippage buffer is applied), you must adjust the closePrice accordingly. * For a LONG position, increase the current market price by your chosen slippage percentage. (e.g. 5%) * For a SHORT position, decrease the market price by that percentage. (e.g. 5%) This adjusted price accounts for the hedger’s spread and ensures that your close request can be accepted. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/closing-a-quote#quantitytoclose) `**quantityToClose**` The amount of the position (in 18‑decimal format) that you want to close. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/closing-a-quote#ordertype) `**orderType**` An enum value indicating the type of closing order: * `0` for LIMIT orders * `1` for MARKET orders ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/closing-a-quote#deadline) `**deadline**` A Unix timestamp by which the close request must be executed. If no action is taken by this time, the request will expire. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/closing-a-quote#parameter-encoding) Parameter Encoding All function calls must be encoded using the SYMM Diamond’s ABI. For closing a quote, you must encode the parameters for the `requestToClosePosition()` function and pass the resulting calldata to your MultiAccount contract’s `_call()` method. For example: [PreviousSending a Quotechevron-left](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote) [NextInstant Tradingchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading) Last updated 29 days ago * [Function Signature](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/closing-a-quote#function-signature) * [Parameter Breakdown](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/closing-a-quote#parameter-breakdown) * [quoteId](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/closing-a-quote#quoteid) * [closePrice](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/closing-a-quote#closeprice) * [quantityToClose](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/closing-a-quote#quantitytoclose) * [orderType](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/closing-a-quote#ordertype) * [deadline](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/closing-a-quote#deadline) * [Parameter Encoding](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/closing-a-quote#parameter-encoding) sun-brightdesktopmoon Copy // Prepare close position parameters const nowInSeconds = Math.floor(Date.now() / 1000); const deadlineInSeconds = nowInSeconds + deadline; // 'deadline' is a duration in seconds const closePositionParameters = [\ quoteId.toString(), \ closePrice.toString(), \ quantityToClose.toString(), \ orderType, \ deadlineInSeconds.toString()\ ]; // Encode the function call using the Diamond’s ABI const encodedClosePositionData = web3.eth.abi.encodeFunctionCall( requestToClosePositionFunctionAbi, // ABI definition for requestToClosePosition closePositionParameters ); // Prepare call data for MultiAccount const _callData = [accountAddress, [encodedClosePositionData]]; // Estimate gas and send the transaction via the MultiAccount contract const gasPrice = await web3.eth.getGasPrice(); const gasEstimate = await multiAccountContract.methods._call(..._callData).estimateGas({ from: process.env.WALLET_ADDRESS }); const gasEstimateBigInt = BigInt(gasEstimate); const bufferPercentage = 0.20; // 20% buffer for gas const adjustedGasLimit = gasEstimateBigInt + (gasEstimateBigInt * BigInt(20) / BigInt(100)); const transactionReceipt = await multiAccountContract.methods._call(..._callData).send({ from: process.env.WALLET_ADDRESS, gas: adjustedGasLimit.toString(), gasPrice: gasPrice.toString() }); console.log("Transaction Receipt:", transactionReceipt); sun-brightdesktopmoon --- # Contracts Documentation 0.8.4 | SYMMIO Protocol Gitbook [Main Flow (0.8.4)chevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/main-flow-0.8.4) [The SYMM Diamond (0.8.4)chevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/the-symm-diamond-0.8.4) [Facetschevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets) [MultiAccount (0.8.4)chevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/multiaccount-0.8.4) [SYMM App (Muon)chevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/symm-app-muon) [PreviousMuonStoragechevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/muonstorage) [NextMain Flow (0.8.4)chevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/main-flow-0.8.4) Last updated 29 days ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Protocol higher level architecture | SYMMIO Protocol Gitbook [PartyBchevron-right](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/partyb) [Solver Settingschevron-right](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/solver-settings) [Max Leveragechevron-right](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/max-leverage) [Maintenance Margin (CVA) Calculationschevron-right](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/maintenance-margin-cva-calculations) [12-Hour Fraud Proof Windowchevron-right](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/12-hour-fraud-proof-window) [PreviousZenithchevron-left](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/zenith) [NextPartyBchevron-right](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/partyb) sun-brightdesktopmoon sun-brightdesktopmoon --- # Mode | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/mode#contract-addresses) Contract Addresses ------------------------------------------------------------------------------------------------------------------------ Name Address Diamond **0x3d17f073cCb9c3764F105550B0BCF9550477D266** AccountFacet 0x464873026877c9D947E2778a1B4cB4A3CbC688F0 DiamondCutFacet 0x7e6DC84041E33e20Ac4529a84C8e8201Db785237 ControlFacet 0x2Ecc7da3Cc98d341F987C85c3D9FC198570838B5 DiamondLoupeFacet 0xb74629900981F2977cd7a8E37052fee0D7a4C395 LiquidationFacet 0x0b60140dCC98a6A9e9985aB165Dc54903861D50A PartyAFacet 0x6AE14800C45aE9383db2C3f2eE6019Ebe1E32403 PartyBFacet 0xCF74C49be20351EF069E3F32B6e646d4B2Ba69D9 ViewFacet 0x9D4c169703BB0116751A6965952A5E4aDfDFfB05 FundingRateFacet 0x4D8e97f44cD90504E790827137334d9a42bbec55 BridgeFacet 0x5E0663DEb8683B70E0Ff36E6E6e0DFa0f0069934 [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/mode#affiliate-addresses) Affiliate Addresses -------------------------------------------------------------------------------------------------------------------------- [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/mode#bmx) BMX ------------------------------------------------------------------------------------------ ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/mode#multiaccount) MultiAccount `0xC0ff4B56f62f20bA45f4229CC6BAaD986FA2a904` ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/mode#fee-collector) Fee Collector `0x5d51a2d77111f6A0aa1e0144f8025752cb1CEbA4` [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/mode#horizon) Horizon -------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/mode#multiaccount-1) MultiAccount `0xDE6446197Cd1AE02E1C5B7191a626Fb0c1757377` ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/mode#fee-collector-1) Fee Collector `0x46b7763dCBddb72b303675B623BA480B3c145F9B` [PreviousMantlechevron-left](https://docs.symm.io/protocol-architecture/contract-addresses/mantle) [NextBasechevron-right](https://docs.symm.io/protocol-architecture/contract-addresses/base) Last updated 2 months ago * [Contract Addresses](https://docs.symm.io/protocol-architecture/contract-addresses/mode#contract-addresses) * [Affiliate Addresses](https://docs.symm.io/protocol-architecture/contract-addresses/mode#affiliate-addresses) * [BMX](https://docs.symm.io/protocol-architecture/contract-addresses/mode#bmx) * [MultiAccount](https://docs.symm.io/protocol-architecture/contract-addresses/mode#multiaccount) * [Fee Collector](https://docs.symm.io/protocol-architecture/contract-addresses/mode#fee-collector) * [Horizon](https://docs.symm.io/protocol-architecture/contract-addresses/mode#horizon) * [MultiAccount](https://docs.symm.io/protocol-architecture/contract-addresses/mode#multiaccount-1) * [Fee Collector](https://docs.symm.io/protocol-architecture/contract-addresses/mode#fee-collector-1) sun-brightdesktopmoon sun-brightdesktopmoon --- # The SYMM Diamond | SYMMIO Protocol Gitbook Symmio's core contracts are implemented with **EIP-2535**, a solution for building modular and upgradeable contracts. [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/the-symm-diamond#eip-2535-diamond-standard-overview) **EIP-2535: Diamond Standard Overview** ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- EIP-2535 introduces the Diamond Standard in smart contract development. This standard centralizes around the concept of a "Diamond" contract, which is constructed from multiple "facets," each responsible for different functionalities. This modular design enhances maintainability by allowing facets to be upgraded or modified independently without affecting the entire contract. Key to this architecture are function selectors, which serve as unique identifiers for each function within the facets. These selectors efficiently direct function calls to the correct facet, facilitating organized and conflict-free code execution. For further reading and technical details, refer to the [official EIP-2535 documentationarrow-up-right](https://eips.ethereum.org/EIPS/eip-2535) . [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/the-symm-diamond#symmios-diamond-implementation) Symmio's Diamond Implementation ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- A **diamond** is a facade smart contract that `delegatecall`s into its facets to execute function calls. Facets are separate, independent contracts that can share internal functions, libraries, and state variables. All the data used and manipulated by the facets is stored in the Diamond contract. The facets contain the code that operates on this data, but the state itself is held in the storage of the Diamond contract. Libraries help define the structure of data and the methods to interact with it. When a facet needs to interact with shared data, it uses the library to define how to access and manipulate this data. Each of the storage libraries define: * A `bytes32` storage slot that is the keccak hash of a unique identifier string (e.g. `diamond.standard.storage.quote`) * A `Layout` struct, which organizes and manages state variables. It centralizes state management to ensure that different facets of a contract can access and modify shared data in a consistent manner. The `layout()` function in each of the storage files uses inline assembly to calculate the exact storage slot where the `Layout` struct is stored using a keccak256 hash of a unique identifier string. It returns a reference to the `Layout` struct, specifically pointing to the designated storage slot. This returned reference allows other parts of the contract to read from and write to the shared state variables defined within the `Layout`. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/the-symm-diamond#storage-libraries) Storage Libraries * `GlobalAppStorage.sol:` Storage related to Symmio emergency functions. * `MAStorage.sol:` This is the Master Agreement Storage. It outlines all the variables related to the conditions of partyB (the solver), such as cooldowns related to the forced canceling of closed positions, liquidator shares, and the liquidation statuses across partyB's * `QuoteStorage.sol:` This defines the Quote, OrderType, QuoteStatus and PositionType. The Layout Struct contains mappings related to Quotes. * `MuonStorage.sol:` This defines the structure of signatures required for verifying the price of a symbol, user uPnl and liquidation state. * `AccountStorage.sol:` This is primarily used to store locked and available balances. * `SymbolStorage.sol:` Defines a Symbol struct, which contains details about the trading symbol. The Layout contains a mapping of symbols. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/the-symm-diamond#facet-interaction-with-diamond-storage) Facet Interaction with Diamond Storage The Diamond contract itself doesn't need to import these storage libraries because it does not directly use them. When a facet, which imports and uses one of these storage libraries, is invoked via a `delegatecall` from the Diamond, it operates directly on the Diamond’s storage. The facet uses the slot address computed by the library to access or modify the data in the specific storage slot. This operation is transparent to the Diamond itself. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/the-symm-diamond#idiamondcut-interface) `**IDiamondCut**` **Interface** A diamond contains within it a mapping of function selectors to facet addresses. Functions are added/replaced/removed by modifying this mapping. The SYMM Diamond implements the `IDiamondCut` interface to allow modifications to the function selector mapping. The `diamondCut` function updates any number of functions from any number of facets in a single transaction. Executing all changes within a single transaction prevents data corruption which could occur in upgrades done over multiple transactions. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/the-symm-diamond#overview-of-the-symm-diamond) Overview of The SYMM Diamond The diagram below shows the relationship of facets with the Diamond ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FkWimYLpIxPtsaxGZvjeH%252Fimage.avif%3Falt%3Dmedia%26token%3Dfa141e64-3649-4867-9d8d-ece3c794c57d&width=768&dpr=3&quality=100&sign=5cefcabc&sv=2) Diagram showing the facets and libraries that interact with the core diamond ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/the-symm-diamond#finding-facet-contracts) Finding Facet Contracts In the SYMM Diamond, the `facets()` function of the `DiamondLoupeFacet` plays a crucial role in inspecting the contract's structure and behaviour. When this function is called on the Diamond, it returns an array of `Facet` structs, each containing the address of a facet along with the specific function selectors associated with that facet. For a user-friendly examination of all facets associated with a Diamond contract, consider using the [louper.devarrow-up-right](https://louper.dev/) tool. [PreviousMain Flowchevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/main-flow) [NextFacetschevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/facets) Last updated 1 year ago * [EIP-2535: Diamond Standard Overview](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/the-symm-diamond#eip-2535-diamond-standard-overview) * [Symmio's Diamond Implementation](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/the-symm-diamond#symmios-diamond-implementation) * [Storage Libraries](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/the-symm-diamond#storage-libraries) * [Facet Interaction with Diamond Storage](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/the-symm-diamond#facet-interaction-with-diamond-storage) * [IDiamondCut Interface](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/the-symm-diamond#idiamondcut-interface) * [Overview of The SYMM Diamond](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/the-symm-diamond#overview-of-the-symm-diamond) * [Finding Facet Contracts](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/the-symm-diamond#finding-facet-contracts) sun-brightdesktopmoon sun-brightdesktopmoon --- # Contracts Documentation 0.8.3 | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3#general-changes) General Changes: ------------------------------------------------------------------------------------------------------------------------------------------------ ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3#remove-unnecessary-nonce-increase) Remove unnecessary nonce increase There were some scenarios before in the contracts where we increased the nonce to make everything more secure. However, upon further consideration, we realized that it is not necessary and makes other processes in the system, like liquidation, more complex. Therefore, we've removed the nonce increase in the following methods: * `allocate()` * `deallocate()` * `transferAllocation()` * `allocateForPartyB()` * `deallocateForPartyB()` [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3#other-bug-fixed-and-enhancements) Other Bug Fixed And Enhancements --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Add `notSuspended` modifier to `depositAndAllocate`, `internalTransfer` * Add `newAllocatedAmount` in `InternalTransfer`, `transferDeallocation` events * Skip the check in `openPosition` that checks whether the remaining position value is acceptable if the rest is going to be cancelled [PreviousMuonStoragechevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/symm-app-muon/muonstorage) [NextFacetschevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets) Last updated 1 year ago * [General Changes:](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3#general-changes) * [Remove unnecessary nonce increase](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3#remove-unnecessary-nonce-increase) * [Other Bug Fixed And Enhancements](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3#other-bug-fixed-and-enhancements) sun-brightdesktopmoon sun-brightdesktopmoon --- # Instant Trading (Solvers) | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-solvers#instant-trading-on-symmio-a-comprehensive-introduction) Instant Trading on SYMMIO: A Comprehensive Introduction ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- SYMMIO is revolutionizing decentralized derivatives trading with the introduction of **Instant Trading**. This feature significantly improves the trading experience by drastically reducing trade execution times and providing immediate feedback to users. This document provides a thorough overview of Instant Trading, its benefits, how it works, and guidance on implementation for developers and solvers. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-solvers#what-is-instant-trading) What is Instant Trading? Instant Trading is a feature that allows traders to execute trades almost instantaneously on the SYMMIO platform. By delegating certain functions to trusted solvers, users can open and close positions without the need for signing each transaction individually. This results in trade execution and price lock times of under one second, closely matching the responsiveness of centralized exchanges. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-solvers#why-implement-instant-trading) Why Implement Instant Trading? #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-solvers#speed-and-efficiency) Speed and Efficiency * **Reduced Execution Time**: Achieve trade execution and price lock times under **1000 milliseconds**. * **Faster On-Chain Settlement**: Transactions settle on-chain within **5–30 seconds**, depending on the blockchain network. * **Enhanced Trading Strategies**: Enables strategies like scalp trading due to quicker price lock-in times. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-solvers#improved-user-experience) Improved User Experience * **Immediate Feedback**: Users receive trade confirmations almost instantly, significantly improving the trading experience. * **Reduced Waiting Times**: Eliminates the previous wait of **20–60 seconds** for price lock-in, offering a **50–100x improvement**. * **Competitive Edge**: Positions SYMMIO as a leader in decentralized trading by matching the speed of centralized exchanges. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-solvers#how-does-instant-trading-work) How Does Instant Trading Work? ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Instant Trading leverages delegated access and session management to enable solvers to act on behalf of users without requiring individual signatures for each transaction. Here's how it operates: 1. **Delegation of Functions**: Users delegate specific trading functions to solvers through the [**MultiAccount**](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount) contract. This allows solvers to execute trades on the user's behalf. 2. **Authentication and Session Creation**: * Users authenticate with solvers by signing a message containing essential details like wallet address, nonce, domain, URI, issued at, and expiration time. * Solvers verify the signature and issue an access token, which the frontend stores for subsequent requests. 3. **Executing Trades**: * With delegated access and authentication in place, solvers can open and close positions instantly when users initiate trades. * Temporary quote IDs are generated to track pending trades until they are confirmed on-chain. 4. **Security and Control**: * Users maintain control by setting expiration times for access tokens and can revoke delegated access at any time. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-solvers#adopting-rasas-instant-trading-implementation) Adopting RASA's Instant Trading Implementation RASA provides a standardized and efficient approach to handling instant actions— solvers are encouraged to follow [RASA's implementation](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation) for Instant Trading. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-solvers#frontends-and-implementation-flexibility) Frontends and Implementation Flexibility Frontends play a crucial role in delivering the Instant Trading experience to users. While there are minimum requirements, frontends have the flexibility to implement the feature in a way that best suits their users. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-solvers#minimum-requirements) Minimum Requirements * **Function Delegation**: Implement the delegation of necessary functions to solvers as described. * **Authentication Flow**: Integrate the authentication and session management processes. * **API Integration**: Connect with solver APIs for instant actions, ensuring secure communication and token handling. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-solvers#future-roadmap) Future Roadmap \--TBA [PreviousInstant Tradingchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading) [NextRasa Instant Trading Implementationchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation) Last updated 2 months ago * [Instant Trading on SYMMIO: A Comprehensive Introduction](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-solvers#instant-trading-on-symmio-a-comprehensive-introduction) * [What is Instant Trading?](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-solvers#what-is-instant-trading) * [Why Implement Instant Trading?](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-solvers#why-implement-instant-trading) * [How Does Instant Trading Work?](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-solvers#how-does-instant-trading-work) * [Adopting RASA's Instant Trading Implementation](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-solvers#adopting-rasas-instant-trading-implementation) * [Frontends and Implementation Flexibility](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-solvers#frontends-and-implementation-flexibility) * [Future Roadmap](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-solvers#future-roadmap) sun-brightdesktopmoon sun-brightdesktopmoon --- # Zenith | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/zenith#zenith-api-url) Zenith API URL ------------------------------------------------------------------------------------------------------------------------------ **Base:** [https://intentx-solver.uc.r.appspot.com/solver\_api/arrow-up-right](https://intentx-solver.uc.r.appspot.com/solver_api/) ### [hashtag](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/zenith#zenith-endpoints) Zenith Endpoints: The Zenith endpoints use the same format as the [Rasa Hedger Endpoints](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/rasa-capital) [hashtag](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/zenith#partyb-contract-addresses) PartyB Contract Addresses ---------------------------------------------------------------------------------------------------------------------------------------------------- Chain PartyB Address BASE 0x5f3525db7589640dae87d6040a85c49fa43feb2f 0x94D2c48821F7667923d7656ACc3529b953b40D09 [PreviousRasa Capital (Zero Spread)chevron-left](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/rasa-capital-zero-spread) [NextProtocol higher level architecturechevron-right](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture) Last updated 8 months ago * [Zenith API URL](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/zenith#zenith-api-url) * [Zenith Endpoints:](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/zenith#zenith-endpoints) * [PartyB Contract Addresses](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/zenith#partyb-contract-addresses) sun-brightdesktopmoon sun-brightdesktopmoon --- # Polygon (0.2.1) | SYMMIO Protocol Gitbook Name Address Diamond 0x6cA4F50154451031f32A12834746D210d47d606c Collateral 0x50E88C692B137B8a51b6017026Ef414651e0d5ba Instant Layer 0xA90b7EDcC470D3e060936eE2b84A8b3A14FA91c8 AccountFacet 0xe53F3760E516086e8F7D447305EaCCCa18CB63cc ClearingHouseFacet 0x77E7067c23d992E5D76e571D543626167BD876b6 ControlFacet 0x32DDd03A0a95FDAD2168D6fc334819Fa50D99b4f CounterPartyRelationsFacet 0xA2cFA4aCb0c1b9F6D490ecD8B3441537ef9fAA0e DiamondLoupeFacet 0x4ae643bbc267ECAA098A750B78b873bB199ECe6F ForceActionsFacet 0xE5274e20822a6023a1A0DAf46Fe3cA54cA53DEDe PartyACloseFacet 0xe91eEe765568d4277E8D592C95EFf0f424993208 PartyAOpenFacet 0x7A539B3D340cC677A16CE195C5b931166c7d1A7c PartyBCloseFacet 0xA88B8be9006Eb0fD9E8F7ffdf87cE66b32ff381a PartyBOpenFacet 0x1dD8FdcC334e82De3D4af89814Bff20720F0f553 TradeFacet 0x2c6381A398A96f8c5EB6CF9a6c62188CaA5E7903 ViewFacet 0x0Ee6a1b48ea15B9018865aDe7535059970DeFd9C [PreviousContract Addresseschevron-left](https://docs.symm.io/options-protocol-architecture/contract-addresses) [NextBuilders introductionchevron-right](https://docs.symm.io/building-on-symmio/builders-introduction) Last updated 2 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Base | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/base#contract-addresses) Contract Addresses ------------------------------------------------------------------------------------------------------------------------ Name Address Diamond 0x91Cf2D8Ed503EC52768999aA6D8DBeA6e52dbe43 AccountFacet 0xd1315a8880A783f0773606675F6f335F070e770B DiamondCutFacet 0x74aa0c998F83e6C164C6D2444b1C3cbc233EF2BC ControlFacet 0x6f93Caba41cF10983711608Cb521fb060aAe054a DiamondLoupeFacet 0x8D3ABB31Cdd6b254f8C3ca2B8173593f269CbeFc LiquidationFacet 0xB558fcd793c541da56D2720e8b18948926C8588C PartyAFacet 0x6Caee219c128617B64B7a89C29CbdcE854278fbA PartyBFacet 0x91BA24C9786CF52Ca9162838C82745a4f438f2eF ViewFacet 0xf79F272205ba7E2Cc741E46bff7ff0faCb941611 FundingRateFacet 0x3E70311e7d93D96aBD8F0eEf5247486e562Af1Ab BridgeFacet 0x2948D25814fC0D58E94af32a3173613b9AA78469 ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/base#affiliate-addresses) Affiliate Addresses Affiliate MultiAccount Fee Collector **Befi** `0xc6Ecf3AB3D09ba6f1565Ad6E139B5D3ba30bB774` `0xDaa78e134665a277cFAD722F71ffBa0C58d55592` **BMX** `0x6D63921D8203044f6AbaD8F346d3AEa9A2719dDD` `0xc9577c97782F3cd1B61895A3ca2f9fEBd19505a4` **IntentX** `0x8Ab178C07184ffD44F0ADfF4eA2ce6cFc33F3b86` `0x1279655FEED886F44958733BBB6b26252D1D4F99` **Based** `0x1c03B6480a4efC2d4123ba90d7857f0e1878B780` `0x97F1dCeC1A4038F72a9a7A9EC2501D942F66e1B0` **Vibe** `0x8a98f69139534Ef85775b473082CE4Af1373cd63` `0xc2C7D07AE9Af9E758ED45268451c3e84E6629766` **Cloverfield** `0xF7F56d7E02D5c7bF33525AE2eecB049a17Ef4580` `0xeBEc8d18358f117629DDf1D2049d2b0D21f9C38D` **Privex** `0x921Dd892D67Aed3d492F9ad77b30b60160B53Fe1` `0x68aEFE794b0CcC01BeCFbbcabd0c7B375B0A8AAf` **Peppy** `0xdfC2a55a44aD3d3aAbFe8D1C498Ea923c6D39526` `0x65b19B57517Ba60e744F206deABA75F08607f60F` **Xpanse** `0xDE6446197Cd1AE02E1C5B7191a626Fb0c1757377` `0xA234F375d1733994720547BB12D92a84122648E1` **Carbon** `0x39EcC772f6073242d6FD1646d81FA2D87fe95314` `0x3c6EB71ffB66D3694eEd9FC63F2e5BeED1029270` **Pear** `0xE43166cE17d3511B09438a359dAa53513225101D` `0x6332B2461AF9BF22733E6A2d88441dfde8c37403` **QuickSwap** `0x0B4779a37C5E6cD7060cc265105Ff44a03b47b26` `0x86AAc363B8471206Eb5b52e121783027d7bc62E1` **Treble** `0x72b03E85B40A745B07f3a15e7A02E66F7f8352F3` `0x76bc5889c0cfcC20960b0D81F541595d81a95122` [PreviousModechevron-left](https://docs.symm.io/protocol-architecture/contract-addresses/mode) [NextBSCchevron-right](https://docs.symm.io/protocol-architecture/contract-addresses/bsc) Last updated 2 months ago * [Contract Addresses](https://docs.symm.io/protocol-architecture/contract-addresses/base#contract-addresses) * [Affiliate Addresses](https://docs.symm.io/protocol-architecture/contract-addresses/base#affiliate-addresses) sun-brightdesktopmoon sun-brightdesktopmoon --- # Sending a Quote | SYMMIO Protocol Gitbook Sending a quote is a core action on the SYMM platform. It allows Party A to signal an intent to trade by submitting a detailed quote request. To ensure that the quote is accepted and ultimately opened by a hedger (Party B), you must follow the steps below and provide accurate parameters. Debugging is difficult with MultiAccount as the transaction could fail for a number of reasons. circle-info `sendQuoteWithAffiliate()` should be used to send quotes. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#function-signature) Function Signature Copy function sendQuoteWithAffiliate( address[] memory partyBsWhiteList, uint256 symbolId, PositionType positionType, OrderType orderType, uint256 price, uint256 quantity, uint256 cva, uint256 lf, uint256 partyAmm, uint256 partyBmm, uint256 maxFundingRate, uint256 deadline, address affiliate, SingleUpnlAndPriceSig memory upnlSig ) external returns (uint256); [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#parameter-breakdown) Parameter Breakdown ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#partybswhitelist) `**partyBsWhiteList[]**` An array of Party B addresses (hedgers/solvers) that Party A is willing to trade with. _Example:_ * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#symbolid) `**symbolId**` The identifier for the trading symbol. circle-info Use the [`getSymbols()`](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/view-facet-0.8.4#getsymbol-9-and-getsymbols) function on the SYMM Diamond to see available symbols, or query a solver’s supported symbols from the [contract-symbols endpoint](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/rasa-capital#get-contract-symbols) (RASA). * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#positiontype) `**positionType**` Enum indicating the type of position: Use `0` for LONG positions and `1` for SHORT positions. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#ordertype) `**orderType**` Enum indicating the order type: Use `0` for LIMIT orders and `1` for MARKET orders. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#price) `**price**` For **LIMIT** orders: This is the exact price (in 18 decimals) at which you wish to open the position. For **MARKET** orders: The price a quote is opened at includes the spread that a solver charges. In order for your MARKET quote to be accepted, you should send an price slightly adjusted from the current market price depending on the position type. This is an adjusted price includes a slippage buffer (e.g., 5%). * **LONG Order:** Increase the price you receive from Muon by 5% (your position opens slightly higher to reflect the hedger's spread) * **SHORT Order:** Decrease the price you receive from Muon by 5% (your position opens slightly lower to reflect the hedger's spread) * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#quantity) `**quantity**` The total order quantity in 18‑decimal format. For example, a 5 ETH order would be 5e18. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#cva-lf-partyamm-partybmm) `**cva, lf, partyAmm, partyBmm**` These represent the locked value parameters—fractions (as percentages) of the notional value that define the risk and margin requirements. * `**cva**`: Credit Valuation Adjustment. Either `partyA` (the user) or `partyB` (the hedger) can get liquidated and `cva` is the penalty that the liquidated side should pay to the other. * `**lf**` **(Liquidator Fee):** Fee reserved for liquidators. * `**partyAmm**` **(Party A Maintenance Margin):** Margin required for Party A. * `**partyBmm**` **(Party B Maintenance Margin):** Margin required for Party B. circle-info Query the solver’s [`get_locked_params`](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/rasa-capital#get-get_locked_params) endpoint. Multiply the notional value by the returned percentage (divided by 100) for each parameter. If you sent a MARKET order, make sure that the notional is calculated based on the adjustedPrice you sent (with the slippage included) **The general formula to send these values as parameters are described below:** **LockedParam (Wei)** \= (Notional Value \* lockedParam) / (100 \* leverage) circle-info **The notional value must be calculated based on the price you wish to send to the contract, not the Muon price. It should reflect the hedger's spread.** **Formula for MARKET orders:** _notionalValue = (quantity \* adjustedPrice)_ **Formula for LIMIT orders:** _notionalValue = (quantity \* requestedPrice)_ _Example Response:_ ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#maxfundingrate) `**maxFundingRate**` The maximum funding rate allowed by Party A, converted to 18 decimals (this is usually 200e18) circle-info You can obtain this from the solver's [`contract-symbols`](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/rasa-capital#get-contract-symbols) endpoint (RASA) ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#deadline) `**deadline**` A Unix timestamp marking the expiry of the quote. Ensure it’s set far enough in the future for a solver to act. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#affiliate) `**affiliate**` The affiliate address. This is the frontend's MultiAccount contract address. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#upnlsig) `**upnlSig**` This is A `SingleUpnlAndPriceSig` struct that confirms: * `**reqId**`**:** A unique request identifier. * `**timestamp**`**:** When the signature was generated. * `**upnl**`**:** The unrealized profit and loss for Party A. * `**price**`**:** The verified asset price (in 18 decimals). * `**gatewaySignature**`**:** A signature from the trusted gateway. * `**sigs**`**:** A Schnorr signature (with `signature`, `owner`, and `nonce` fields). circle-info This data is obtained from the Muon oracle by calling the `uPnl_A_withSymbolPrice` method. _Example Query:_ _Script Example for fetching and formatting the upnlSig for a sendQuoteWithAffiliate using axios and web3:_ * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#parameter-encoding-for-sendquotewithaffiliate) Parameter Encoding for sendQuoteWithAffiliate When sending a quote using `sendQuoteWithAffiliate()`, you must encode the function call with the SYMM Diamond’s ABI before forwarding it through your MultiAccount contract. This ensures that the parameters are formatted correctly and that the Diamond delegates the call to the appropriate facet. The transaction payload before encoding should be formatted like this: **Steps to Encode and Send a Quote:** 1. **Encode the Function Call:** Use Web3’s ABI encoding to convert the `sendQuoteWithAffiliate` function call into a byte string. For example: * **sendQuoteWithAffiliateFunctionAbi:** The ABI definition for the `sendQuoteWithAffiliate` function. * **sendQuoteParameters:** An array containing all parameters in the order defined by the function signature. 2. **Prepare the Call Data:** The MultiAccount contract’s `_call()` method expects an array where: * The first element is the sub‑account address. * The second element is an array containing your encoded function call. 3. **Send the Transaction:** Finally, forward the encoded call through your MultiAccount contract. By following these steps, you can successfully encode and send a quote with affiliate information using the `sendQuoteWithAffiliate()` function in SYMM. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#finding-the-quote-id) Finding the Quote ID Once you send a quote using the `sendQuoteWithAffiliate()` function, the system will emit a **SendQuote** event. This event confirms that your quote has been successfully submitted and provides a unique identifier (the `quoteId`) along with key details of your quote. For example, the event is defined as follows: You can use this ID to track and query your quote later, using [getQuote()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/view-facet-0.8.4#getquote) . * * * [PreviousCreating an Account and Depositing Fundschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/creating-an-account-and-depositing-funds) [NextClosing a Quotechevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/closing-a-quote) Last updated 29 days ago * [Parameter Breakdown](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#parameter-breakdown) * [partyBsWhiteList\[\]](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#partybswhitelist) * [symbolId](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#symbolid) * [positionType](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#positiontype) * [orderType](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#ordertype) * [price](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#price) * [quantity](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#quantity) * [cva, lf, partyAmm, partyBmm](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#cva-lf-partyamm-partybmm) * [maxFundingRate](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#maxfundingrate) * [deadline](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#deadline) * [affiliate](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#affiliate) * [upnlSig](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#upnlsig) * [Parameter Encoding for sendQuoteWithAffiliate](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#parameter-encoding-for-sendquotewithaffiliate) * [Finding the Quote ID](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#finding-the-quote-id) sun-brightdesktopmoon Copy const partyBsWhiteList = [solverAddress1, solverAddress2]; Copy enum PositionType { LONG, SHORT } Copy enum OrderType { LIMIT, MARKET } Copy //CVA const cvaWei = notionalValue * (new BigNumber(lockedParams.cva)) / (new BigNumber(100)) / (new BigNumber(lockedParams.leverage)) / (new BigNumber(1e18)); console.log("cva: ", cvaWei); //LF const lfWei = notionalValue * (new BigNumber(lockedParams.lf)) / (new BigNumber(100)) / (new BigNumber(lockedParams.leverage)) / (new BigNumber(1e18)); //Maintenance Margins const partyAmmWei = notionalValue * (new BigNumber(lockedParams.partyAmm)) / (new BigNumber(100)) / (new BigNumber(lockedParams.leverage)) / (new BigNumber(1e18)); const partyBmmWei = notionalValue * (new BigNumber(lockedParams.partyBmm)) / (new BigNumber(100)) / (new BigNumber(1e18)); Copy {"cva":"0.7","lf":"0.3","leverage":"1.0","partyAmm":"99.0","partyBmm":"0","message":"Success"} Copy https://muon-oracle4.rasa.capital/v1/?app=symmio&method=uPnl_A_withSymbolPrice¶ms[partyA]=0xYourAddress¶ms[chainId]=42161¶ms[symbolId]=4¶ms[symmio]=0xSymmioDiamondAddress Copy require('dotenv').config() const { Web3 } = require('web3'); // Provide a valid provider URL; you can use your own Infura project URL or another provider. const web3 = new Web3(new Web3.providers.HttpProvider(process.env.PROVIDER_URL)); const axios = require("axios"); async function getMuonSig(account, chainId, contractAddress, symbolId) { const url = "https://muon-oracle4.rasa.capital/v1/"; const params = { app: "symmio", method: "uPnl_A_withSymbolPrice", "params[partyA]": account, "params[chainId]": chainId.toString(), "params[symbolId]": symbolId.toString(), "params[symmio]": contractAddress }; try { const response = await axios.get(url, { params }); if (!response.data || !response.data.result) { throw new Error("Unexpected response structure: " + JSON.stringify(response.data)); } const result = response.data.result; if (!result.data) { throw new Error("Missing data in result"); } const data = result.data; const reqId = result.reqId; const timestamp = data.timestamp ? data.timestamp : "0"; const uPnl = data.result && data.result.uPnl ? data.result.uPnl : "0"; const price = data.result && data.result.price ? data.result.price : "0"; const gatewaySignature = result.nodeSignature; const sigs = (result.signatures && result.signatures.length > 0) ? result.signatures[0] : { signature: "0", owner: "0x0" }; const nonce = data.init && data.init.nonceAddress ? data.init.nonceAddress : "0x0"; const upnlSigFormatted = { reqId: web3.utils.hexToBytes(reqId), timestamp: timestamp.toString(), upnl: uPnl.toString(), price: price.toString(), gatewaySignature: web3.utils.hexToBytes(gatewaySignature), sigs: { signature: sigs.signature.toString(), owner: sigs.owner, nonce: nonce } }; return upnlSigFormatted; } catch (error) { console.error("Error fetching Muon signature:", error); throw error; } } // Example usage: (async () => { try { const account = ""; // Replace with your Party A address const chainId = 42161; // Example: Arbitrum chain ID const contractAddress = ""; // SYMM Diamond address const symbolId = 1; // Example symbolId 1 = BTCUSDT const muonSig = await getMuonSig(account, chainId, contractAddress, symbolId); console.log("Muon Signature:", muonSig); } catch (error) { console.error(error); } })(); Copy //Max funding and deadline const sendQuoteWithAffiliateParameters = [\ partyBsWhiteList,\ symbolId,\ positionType,\ orderType,\ requestPrice.toString(), //the MARKET price (with added slippage) or if LIMIT, any price\ requestedQuantityWei.toString(),\ cvaWei.toString(), \ lfWei.toString(),\ partyAmmWei.toString(),\ partyBmmWei.toString(), \ maxFundingRate.toString(), \ deadline.toString(),\ affiliate,\ upnlSigFormatted //signature from muon\ ]; Copy const encodedSendQuoteWithAffiliateData = web3.eth.abi.encodeFunctionCall( sendQuoteWithAffiliateFunctionAbi, sendQuoteWithAffiliateParameters ); Copy const _callData = [ subAccountAddress, [ encodedSendQuoteWithAffiliateData ] ]; Copy const sendQuoteWithAffiliateReceipt = await multiAccountContract.methods._call(..._callData).send({ from: account.address, gas: adjustedGasLimit.toString(), gasPrice: sendQuotePrice.toString() }); Copy event SendQuote( address partyA, uint256 quoteId, address[] partyBsWhiteList, uint256 symbolId, PositionType positionType, OrderType orderType, uint256 price, uint256 marketPrice, uint256 quantity, uint256 cva, uint256 lf, uint256 partyAmm, uint256 partyBmm, uint256 tradingFee, uint256 deadline ); sun-brightdesktopmoon --- # Contract Addresses | SYMMIO Protocol Gitbook [Mantlechevron-right](https://docs.symm.io/protocol-architecture/contract-addresses/mantle) [Modechevron-right](https://docs.symm.io/protocol-architecture/contract-addresses/mode) [Basechevron-right](https://docs.symm.io/protocol-architecture/contract-addresses/base) [BSCchevron-right](https://docs.symm.io/protocol-architecture/contract-addresses/bsc) [Arbitrumchevron-right](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum) [Polygonchevron-right](https://docs.symm.io/protocol-architecture/contract-addresses/polygon) [Berachainchevron-right](https://docs.symm.io/protocol-architecture/contract-addresses/berachain) [Cotichevron-right](https://docs.symm.io/protocol-architecture/contract-addresses/coti) [Sonicchevron-right](https://docs.symm.io/protocol-architecture/contract-addresses/sonic) [PreviousMuon APIchevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/muon-api) [NextMantlechevron-right](https://docs.symm.io/protocol-architecture/contract-addresses/mantle) sun-brightdesktopmoon sun-brightdesktopmoon --- # Perps Hub | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/perps-hub#perps-hub-api-urls) Perps Hub API URLs ----------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/perps-hub#format) Format [https://www.domainPerEnv/v1/{symmDeploymentId}/{multiaccount}arrow-up-right](https://domainperenv/rfq/v1/:multiaccount) ⚠️Multiaccounts must be valid checksummed addresses Copy { "BSC (56a)": { "prod": "https://www.perps-streaming.com/v1/56a/{multiaccount}" }, "ARBITRUM (42161a)": { "prod": "https://www.perps-streaming.com/v1/42161a/{multiaccount}" }, "MANTLE (5000a)": { "prod": "https://www.perps-streaming.com/v1/5000a/{multiaccount}" }, "MODE (34443a)": { "prod": "https://www.perps-streaming.com/v1/34443a/{multiaccount}" }, "BASE (8453a)": { "prod": "https://www.perps-streaming.com/v1/8453a/{multiaccount}" }, "BERACHAIN (80094a)": { "prod": "https://www.perps-streaming.com/v1/80094a/{multiaccount}" }, "COTI (2632500a)": { "prod": "https://www.perps-streaming.com/v1/2632500a/{multiaccount}" }, "SPOOKY (250a)": { "prod": "https://www.perps-streaming.com/v1/250a/{multiaccount}" } } [hashtag](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/perps-hub#perps-hub-endpoints) Perps Hub Endpoints: -------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/perps-hub#streaming) Streaming ### [hashtag](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/perps-hub#paths) Paths 1. GET `/contract-symbols` 2. GET `/get_locked_params/` 3. GET `/price-range/` 4. GET `/open-interest` 5. GET `/notional_cap/` 6. GET `/mark-price/` 7. GET `/get_funding_info` 8. POST `/position_state//` 1. Request Body: `{quote_id: number}` 2. Response Status: `200` or `404` 3. Response Body (200): `{ count: number; position_state: { id: string; quote_id: number; filled_amount_open: number; filled_amount_close: number; action_status: 'failed' | 'success'; last_seen_action: string; failure_type: string; order_type: number; create_time: number; modify_time: number; counterparty_address: string; error_code: string; state_type: string; }[]; };` ### [hashtag](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/perps-hub#examples) Examples Get locked params on 56a (BSC) [https://www.perps-streaming.com/v1/56a/0x650a2D6C263A93cFF5EdD41f836ce832F05A1cF3/get\_locked\_params/BTCUSDTarrow-up-right](https://www.perps-streaming.com/v1/56a/0x650a2D6C263A93cFF5EdD41f836ce832F05A1cF3/get_locked_params/BTCUSDT) Get mark price of symbol on 5000a (Mantle) [https://www.perps-streaming.com/v1/5000a/0xecbd0788bb5a72f9dfdac1ffeaaf9b7c2b26e456/mark-price/ETHUSDTarrow-up-right](https://www.perps-streaming.com/v1/5000a/0xecbd0788bb5a72f9dfdac1ffeaaf9b7c2b26e456/mark-price/ETHUSDT) [hashtag](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/perps-hub#instant-trading) Instant trading ----------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/perps-hub#paths-1) Paths 1. GET `/instant_close/` 1. Response Status: `200` 2. Response: `{quote_id: number, quantity_to_close: number, close_price: number}[]` 2. POST /`instant_open` 1. Request body: * Response Status: `200` or `400` * Response Body: In case of `400` there will be a message string in body 1. POST `/instant_close` **(⚠️This endpoint requires an authorization: Bearer {token} header. This can be obtained from the /login endpoint.)** 1. Request Body: `{close_price: string, quantity_to_close: string, quote_id: number}` 2. Response Status: `200` or `400` 3. Response Body: In case of `400` there will be a message string in body 2. GET `/nonce/` 1. Response Status: `200` 2. Response Body: `{nonce: string}` 3. POST /login 1. Response Status: `200` or `400` 2. Response Body: In case of `400` there will be a message string in body giving further details ### [hashtag](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/perps-hub#examples-1) Examples Get instant close status of a quote on Mantle [https://www.perps-streaming.com/v1/5000a/0xecbd0788bb5a72f9dfdac1ffeaaf9b7c2b26e456/instant\_close/0xBd047C4F108282745E0c4DFE2f97fFaF2e67032barrow-up-right](https://www.perps-streaming.com/instant/v1/5000a/0x614bB1F3e0Ae5A393979468ED89088F05277312c/instant_close/0xBd047C4F108282745E0c4DFE2f97fFaF2e67032b) [hashtag](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/perps-hub#partyb-contract-addresses) PartyB Contract Addresses ------------------------------------------------------------------------------------------------------------------------------------------------------- Chain PartyB Address BASE 0x1EcAbF0Eba136920677C9575FAccee36f30592cf ARBITRUM 0x00c069d68bc7420740460dbc3cc3fff9b3742421 MANTLE 0x12de0352dd4187af5797f5147c4179f9624346e2 BNB 0xd5a075c88a4188d666fa1e4051913be6782982da MODE 0x87fc464fa528260f1eeab94fa20f73fed8536eb7 BERA 0x8141c1840F7D190Cd24239C22b1e560e08999B12 SONIC 0x7D387771f6E23f353a4afCE21af521875C0825D0 COTI 0x61109A6Eb070a860B1Da2A38f93ca2B884B54f90 [hashtag](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/perps-hub#conditional-orders-handler) Conditional Orders Handler --------------------------------------------------------------------------------------------------------------------------------------------------------- [PerpsHub TP/SL Implementation](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/perpshub-tp-sl-implementation) [PreviousSolver Addresses & Endpointschevron-left](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints) [NextRasa Capitalchevron-right](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/rasa-capital) Last updated 4 days ago * [Perps Hub API URLs](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/perps-hub#perps-hub-api-urls) * [Format](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/perps-hub#format) * [Perps Hub Endpoints:](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/perps-hub#perps-hub-endpoints) * [Streaming](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/perps-hub#streaming) * [Paths](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/perps-hub#paths) * [Examples](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/perps-hub#examples) * [Instant trading](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/perps-hub#instant-trading) * [Paths](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/perps-hub#paths-1) * [Examples](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/perps-hub#examples-1) * [PartyB Contract Addresses](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/perps-hub#partyb-contract-addresses) * [Conditional Orders Handler](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/perps-hub#conditional-orders-handler) sun-brightdesktopmoon Copy { "symbolId": "string", "positionType": 0, // 0 for long, 1 for short "orderType": 0, // 0 for limit, 1 for market "price": "string", "quantity": "string", "cva": "string", "lf": "string", "partyAmm": "string", "partyBmm": "string", "maxFundingRate": "string", "deadline": 1625234523 // Unix timestamp } sun-brightdesktopmoon --- # Trade on Symmio | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/trade-on-symmio#to-trade-symmio-markets-please-visit-our-3rd-party-frontend-providers) To trade Symmio Markets, please visit our 3rd party frontend providers: ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/trade-on-symmio#for-live-status-https-symm.io-frontends) For Live status: ​[https://symm.io/frontendsarrow-up-right](https://symm.io/frontends) ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/trade-on-symmio#undefined) [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/trade-on-symmio#alpha-by-thena) ALPHA by Thena --------------------------------------------------------------------------------------------------------------------------------- [ALPHAarrow-up-right](https://alpha-test-2.vercel.app/trade/BTCUSDT) , operating on the BNB ecosystem [https://alpha-test-2.vercel.app/trade/BTCUSDTalpha-test-2.vercel.appchevron-right](https://alpha-test-2.vercel.app/trade/BTCUSDT) [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/trade-on-symmio#intentx) IntentX ------------------------------------------------------------------------------------------------------------------- IntentX operating on the Base ecosystem [![Logo](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2Fintentx.io%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=3193a855&sv=2)IntentX | Homeintentx.iochevron-right](https://intentx.io/) [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/trade-on-symmio#live) Based Markets ---------------------------------------------------------------------------------------------------------------------- Based Markets is operating on the Base ecosystem [![Logo](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2Ftrade.based.markets%2Fimages%2F512x512_App_Icon.png&width=20&dpr=3&quality=100&sign=d820c480&sv=2)Basedtrade.based.marketschevron-right](https://trade.based.markets/) triangle-exclamation ### [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/trade-on-symmio#cloverfield-demo-deactive) Cloverfield (DEMO - DEACTIVE) [Cloverfieldarrow-up-right](https://cloverfield.exchange/trade/BTCUSDT) is the demo frontend built on SYMMIO which is used for testing new features and showcasing the SYMMIO tech. Cloverfield is deployed on Fantom & Binance Chain; follow this link & don't hesitate to contact admins or staff via [Discordarrow-up-right](https://discord.gg/symmio) if you require assistance. [![Logo](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2Fcloverfield.exchange%2Fimages%2F512x512_App_Icon.png&width=20&dpr=3&quality=100&sign=ed1be52&sv=2)Cloverfieldcloverfield.exchangechevron-right](https://cloverfield.exchange/trade/BTCUSDT) [PreviousSDK - SYMM clientchevron-left](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/sdk-symm-client) [NextSecurity (Audits / Bugbounty)chevron-right](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty) Last updated 1 year ago * [To trade Symmio Markets, please visit our 3rd party frontend providers:](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/trade-on-symmio#to-trade-symmio-markets-please-visit-our-3rd-party-frontend-providers) * [For Live status: ​https://symm.io/frontends](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/trade-on-symmio#for-live-status-https-symm.io-frontends) * [](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/trade-on-symmio#undefined) * [ALPHA by Thena](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/trade-on-symmio#alpha-by-thena) * [IntentX](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/trade-on-symmio#intentx) * [Based Markets](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/trade-on-symmio#live) sun-brightdesktopmoon sun-brightdesktopmoon --- # Trading Fees | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/building-on-symmio/trading-fees#settlement-costs-in-symmio) Settlement Costs in Symmio -------------------------------------------------------------------------------------------------------------------------- **Solvers and Market Makers enjoy zero fees.** Symmio’s settlement cost structure is designed to encourage the participation of professional market makers and solvers. Solvers and Market Makers do **not** pay settlement fees. This approach mirrors the “Market Maker programs” seen in Order Book DEX environments, where liquid and efficient markets are rewarded by charging makers differently—often zero fees—to encourage tighter spreads and better liquidity for all users. **User-facing Product-Specific Settlement Costs** Settlement costs are not one-size-fits-all. The exact fee structure varies depending on the product type. Every product category has different settlement costs, read more in each respective category: [Perps - Settlement Costs](https://docs.symm.io/building-on-symmio/trading-fees/perps-settlement-costs) [Pair Trading - Settlement costs](https://docs.symm.io/building-on-symmio/trading-fees/pair-trading-settlement-costs) **Platform Fees and Affiliate Credits** A portion of each platform fee is allocated to the exchange’s affiliate partner—the frontend builder. This means that if you run a frontend interface integrated with Symmio, you can earn a share of the fees generated when traders execute orders through your platform. To learn more about becoming a frontend partner and start building with our toolkit, visit the [Exchanges (Frontend Builders)](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders) section and explore the [Frontend SDKarrow-up-right](https://github.com/SYMM-IO/frontend-sdk) . * * * **Overview** As a B2B-focused solution, Symmio provides a “Derivatives as a Service” model that empowers builders to launch their own decentralized perpetual or derivatives exchanges. Whenever traders execute trades through the Symmio clearing layer, a platform fee is applied. This fee supports the ecosystem, incentivizes liquidity provision, and helps maintain the high-performance clearing infrastructure. [PreviousSolver - Example Flowchevron-left](https://docs.symm.io/building-on-symmio/solving-for-symmio/solver-example-flow) [NextPerps - Settlement Costschevron-right](https://docs.symm.io/building-on-symmio/trading-fees/perps-settlement-costs) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Security (Audits / Bugbounty) | SYMMIO Protocol Gitbook [Bug bounty / Coveragechevron-right](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/bug-bounty-coverage) [Auditschevron-right](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits) [PreviousTrade on Symmiochevron-left](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/trade-on-symmio) [NextBug bounty / Coveragechevron-right](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/bug-bounty-coverage) sun-brightdesktopmoon sun-brightdesktopmoon --- # Glossary | SYMMIO Protocol Gitbook ### [hashtag](https://docs.symm.io/protocol-architecture/glossary#hedger-solver-partyb) Hedger / Solver (PartyB) A liquidity provider on SYMMIO who sees user “Intents” (trades) and decides whether to accept or reject them. Can hedge trades off-chain (e.g., with a centralized or decentralized broker) or choose to stay unhedged. ### [hashtag](https://docs.symm.io/protocol-architecture/glossary#broker) Broker Any external platform or strategy a Hedger uses to hedge. This could be a centralized exchange (Binance, ByBit), a DEX, an OTC desk, or even an internal algorithm. SYMMIO does not require Hedgers to hedge; it is entirely optional. Off-chain actions have no bearing on on-chain states or trust assumptions. ### [hashtag](https://docs.symm.io/protocol-architecture/glossary#partya) PartyA A user who creates Intents (trading requests). PartyA trades through a frontend. ### [hashtag](https://docs.symm.io/protocol-architecture/glossary#intent) Intent A proposed trade from PartyA. Examples: “I want to open a LONG position for BTCUSDT at price X with quantity Y.” Hedgers see these Intents on-chain and can lock them if they meet their criteria. ### [hashtag](https://docs.symm.io/protocol-architecture/glossary#off-chain-vs.-on-chain) Off-Chain vs. On-Chain SYMMIO’s on-chain contracts control positions, collateral, liquidations, etc. Off-chain hedging (if any) is the Hedger’s private business logic and does not affect the contract’s rules or solvency checks. ### [hashtag](https://docs.symm.io/protocol-architecture/glossary#directional-exposure) Directional Exposure If a Hedger chooses not to hedge its exposure, it is essentially taking a directional bet on the market. A fully hedged approach (1:1) is “delta-neutral,” meaning the Hedger never maintains directional exposure. ### [hashtag](https://docs.symm.io/protocol-architecture/glossary#position-and-liquidation) Position & Liquidation Once an Intent is opened on-chain, it becomes a position. If either side (PartyA or Hedger) becomes insolvent, a liquidator can step in to close the position forcibly. No trust is placed on the Hedger’s off-chain solvency; only on-chain collateral and UPNL. ### [hashtag](https://docs.symm.io/protocol-architecture/glossary#platform-fee) Platform Fee: Charged to PartyA upon opening a position. The hedger spread is embedded in the price. ### [hashtag](https://docs.symm.io/protocol-architecture/glossary#liquidator-fee-lf) Liquidator Fee (LF) Incentive for liquidators in a forced liquidation. ### [hashtag](https://docs.symm.io/protocol-architecture/glossary#counterparty-valuation-adjustment-cva) Counterparty Valuation Adjustment (CVA) Portion of notional position value paid in case one side gets liquidated and paid to the other side. Read more [here](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/maintenance-margin-cva-calculations) . ### [hashtag](https://docs.symm.io/protocol-architecture/glossary#funding-rate) Funding Rate A periodic charge, often determined by oracles. If a Hedger or PartyA is short, they may pay a funding rate to the long side (or vice versa). [Previous12-Hour Fraud Proof Windowchevron-left](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/12-hour-fraud-proof-window) [NextOverviewchevron-right](https://docs.symm.io/options-protocol-architecture/overview) Last updated 25 days ago * [Hedger / Solver (PartyB)](https://docs.symm.io/protocol-architecture/glossary#hedger-solver-partyb) * [Broker](https://docs.symm.io/protocol-architecture/glossary#broker) * [PartyA](https://docs.symm.io/protocol-architecture/glossary#partya) * [Intent](https://docs.symm.io/protocol-architecture/glossary#intent) * [Off-Chain vs. On-Chain](https://docs.symm.io/protocol-architecture/glossary#off-chain-vs.-on-chain) * [Directional Exposure](https://docs.symm.io/protocol-architecture/glossary#directional-exposure) * [Position & Liquidation](https://docs.symm.io/protocol-architecture/glossary#position-and-liquidation) * [Platform Fee:](https://docs.symm.io/protocol-architecture/glossary#platform-fee) * [Liquidator Fee (LF)](https://docs.symm.io/protocol-architecture/glossary#liquidator-fee-lf) * [Counterparty Valuation Adjustment (CVA)](https://docs.symm.io/protocol-architecture/glossary#counterparty-valuation-adjustment-cva) * [Funding Rate](https://docs.symm.io/protocol-architecture/glossary#funding-rate) sun-brightdesktopmoon sun-brightdesktopmoon --- # PartyA | SYMMIO Protocol Gitbook The `SymmioPartyA` contract serves as a proxy for users to interact with the Symmio platform via their respective sub-accounts. Each sub-account, represented by an instance of `SymmioPartyA`, can forward calls to the Symmio diamond. Here's a detailed breakdown of the functionalities and features provided by this contract: [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partya#constructor) **Constructor** --------------------------------------------------------------------------------------------------------------------------------------------------------------- Initializes a new `SymmioPartyA` contract with specific roles and addresses. Copy constructor(address admin, address multiAccountAddress, address symmioAddress_) { _grantRole(DEFAULT_ADMIN_ROLE, admin); _grantRole(MULTIACCOUNT_ROLE, multiAccountAddress); symmioAddress = symmioAddress_; } * **Parameters**: * `admin`: The administrator of the contract who is granted the `DEFAULT_ADMIN_ROLE`. * `multiAccountAddress`: The address of the `MultiAccount` contract, granted the `MULTIACCOUNT_ROLE` to allow it to make calls on behalf of the sub-account. * `symmioAddress_`: The initial address of the Symmio platform contract to which all calls will be forwarded. * **Operations**: * Grants `DEFAULT_ADMIN_ROLE` to `admin`. * Grants `MULTIACCOUNT_ROLE` to `multiAccountAddress`. * Sets the initial Symmio platform address (this is the Diamond). ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partya#setsymmioaddress) **setSymmioAddress()** Updates the address of the Symmio platform contract. Only an account with `DEFAULT_ADMIN_ROLE` can invoke this function. **Parameters**: * `symmioAddress_`: The new address of the Symmio platform. **Operations**: * Emits a `SetSymmioAddress` event containing the old and new addresses. * Updates the `symmioAddress` state variable. **Events**: [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partya#call) **\_call()** ----------------------------------------------------------------------------------------------------------------------------------------------------- Forwards calls from the `SymmioPartyA` contract to the Symmio platform. This method is crucial for interacting with the Symmio functionalities through sub-accounts. Only an account with `MULTIACCOUNT_ROLE` can invoke this function, meaning only the `MultiAccount` contract can direct actions. **Parameters**: * `_callData`: The bytecode of the function call to be forwarded to the Symmio platform. **Returns**: * `_success`: A boolean indicating whether the call was successful. * `_resultData`: The data returned from the call if successful, or error information if the call failed. [PreviousMultiAccountchevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount) [NextPartyBchevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partyb) Last updated 1 year ago * [Constructor](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partya#constructor) * [setSymmioAddress()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partya#setsymmioaddress) * [\_call()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partya#call) sun-brightdesktopmoon Copy function setSymmioAddress(address symmioAddress_) external onlyRole(DEFAULT_ADMIN_ROLE) { emit SetSymmioAddress(symmioAddress, symmioAddress_); symmioAddress = symmioAddress_; } Copy event SetSymmioAddress(address oldV3ContractAddress, address newV3ContractAddress); Copy function _call(bytes memory _callData) external onlyRole(MULTIACCOUNT_ROLE) returns (bool _success, bytes memory _resultData) { return symmioAddress.call{ value: 0 }(_callData); } sun-brightdesktopmoon --- # Recommended Architecture for Solvers | SYMMIO Protocol Gitbook In this section, we present a proposed architecture tailored for hedger services and components. This architecture is designed for hedgers intending to hedge their positions with a broker. Each micro-service in this architecture performs a specific function. The diagram below illustrates the architecture. ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FRDs6PRV38gSZDCkvF9aP%252Fimage.png%3Falt%3Dmedia%26token%3D9931e2f6-da91-49f0-b292-4e0d3afaed22&width=768&dpr=3&quality=100&sign=a6700502&sv=2) **Recommended Architecture for the Solver** **Green objects** codes will be open sourced and provided by the SYMMIO team (ETA Nov/Dec 2023) **Red objects** should be developed by the MarketMaker. **Purple objects** are optional. Each circle in the diagram represents a distinct micro-service within the hedger system. The micro-services within containers act as backup services for one another. It is imperative to ensure maximum isolation between these micro-services, facilitating communication via message brokers like RabbitMQ and Redis. Employing a micro-service architecture offers a plethora of advantages. For instance, any malfunction in one service will minimally impact others. Moreover, modifications to any individual module will not affect others, provided there's no change in its input or output specifications. It's strongly advised to utilize separate Docker containers for each micro-service to enhance isolation and streamline resource management. This modular approach promotes superior scalability and fault tolerance. Each micro-service can scale autonomously, and a failure in one won't compromise the others. In essence, a micro-service architecture offers numerous advantages, such as enhanced isolation, scalability, fault tolerance, and efficient resource management. A brief overview of each micro-service's function is as follows: * **Hedger Web-Server**: This micro-service offers the APIs and web-sockets essential for the front-end, as discussed in the preceding section. It extracts data from the Hedger database, processes it, and transmits it to the front-end. * **SYMMIO Blockchain Input Module**: This module's duty is to capture events from the blockchain. Given the critical nature of this information for the hedger, three separate micro-services, performing identical functions, have been established. This redundancy ensures that if one service falters, the others remain operational. These micro-services function as event-listeners, procuring a real-time stream of blockchain events via a websocket RPC. The subgraph fetcher extracts data from the subgraph, while the event poller captures events using an HTTP RPC. * **Web3 Agent**: This module facilitates transactions and view calls required by other micro-services. * **Balance Manager**: This component manages the allocation of the hedger's funds across its sub-accounts to virtually eliminate liquidation risks. For instance, if the hedger's health ratio is disparate across sub-accounts, this module will reallocate funds accordingly to maintain equilibrium. * **Position Manager**: Serving as the hedger's core service, the Position Manager handles pivotal actions and decisions. It processes events fetched from the blockchain and the status of pending broker positions. This module evaluates hedger policies and executes appropriate actions such as initiating or terminating positions on either the broker or contract side. Given its significance, it's advisable to deploy multiple instances of this service. * **Broker Order Monitoring**: This module oversees the status of limit orders with the broker and notifies the Position Manager upon order execution. Two micro-services, one relying on a WebSocket and the other on an API call, fetch these orders to ensure uninterrupted hedger availability. * **Broker Order Maker**: This module oversees necessary updates on the broker side, encompassing order creation, cancellation, and termination. * **Position Validator**: Every position is reflected across three platforms: the broker, the blockchain, and the hedger database. This module's role is to ensure uniformity across these platforms and alert developers in case of discrepancies. * **Monitoring and Developer Alerts**: This system monitors all micro-services, raising alerts to developers if any anomalies arise. [PreviousSolver Flow Summary Examplechevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-flow-summary-example) [NextGlossarychevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/glossary) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Staking and Vesting | SYMMIO Protocol Gitbook [Sherlock Audit - Mar 7, 2025chevron-right](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/staking-and-vesting/sherlock-audit-mar-7-2025) [PreviousSherlock Audit - Jan 2, 2024chevron-left](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/vaults/sherlock-audit-jan-2-2024) [NextSherlock Audit - Mar 7, 2025chevron-right](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/staking-and-vesting/sherlock-audit-mar-7-2025) sun-brightdesktopmoon sun-brightdesktopmoon --- # Force Actions Facet (0.8.4) | SYMMIO Protocol Gitbook The **Force Actions Facet** enables users to take action in situations where counterparties are unresponsive or when market conditions require intervention. It includes methods for: * Forcing the cancellation of quotes or close requests. * Forcing the closure of positions. * Settling UPnLs for the hedger and then forcing the closure of a position. These functions help protect the system from prolonged exposure to risk and ensure that positions can be closed even when normal procedures fail. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/force-actions-facet-0.8.4#forcecancelquote) forceCancelQuote() Forces the cancellation of a quote when Party B is unresponsive. This function requires that the quote is in a `CANCEL_PENDING` state and that the force-cancellation cooldown has elapsed. It then updates the quote’s status to `CANCELED` and returns any locked fees to Party A. **Function Signature:** Copy function forceCancelQuote(uint256 quoteId) external notLiquidated(quoteId) whenNotPartyAActionsPaused; **Parameters:** * `quoteId`: The unique identifier of the quote to be canceled. **Example Usage:** Copy // Force cancel a quote with ID 42 diamond.forceCancelQuote(42); **Events Emitted:** * `ForceCancelQuote(uint256 quoteId, QuoteStatus quoteStatus)` * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/force-actions-facet-0.8.4#forcecancelcloserequest) forceCancelCloseRequest() Force-cancels a pending close request when Party B fails to respond within the designated cooldown period. This function updates the quote status back to OPENED (thus canceling the close request) and resets associated close parameters. **Function Signature:** **Parameters:** * `quoteId`: The unique identifier of the quote for which the close request is to be canceled. **Example Usage:** **Events Emitted:** * `ForceCancelCloseRequest(uint256 quoteId, QuoteStatus quoteStatus, uint256 closeId)` * _(For backward compatibility, an additional event is emitted without the closeId.)_ * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/force-actions-facet-0.8.4#forcecloseposition) forceClosePosition() Force‑closes an open position when market conditions satisfy the force‑close criteria and Party B is either unresponsive or fails to maintain sufficient allocated balance. This function ensures that the quote is in a `CLOSE_PENDING` state and that all force‑close conditions are met. The conditions include: * **Cooldown Periods:** * The `startTime` specified in the HighLowPriceSig must be at least `quote.statusModifyTimestamp + forceCloseFirstCooldown`, ensuring that the hedger had enough time to consider the close request. * The `endTime` must be less than or equal to both `quote.deadline` and `block.timestamp - forceCloseSecondCooldown`, ensuring that the hedger had sufficient time to fill the close. * **Timeframe Requirement:** If the force‑close results in using the average price (to protect against extreme market moves), the timeframe (`endTime - startTime`) must exceed `forceCloseMinSigPeriod`. * **Price Verification Based on Position Type:** * **For LONG positions:** The function checks whether the highest price in the specified timeframe meets or exceeds the requested close price plus a gap ratio (a percentage buffer that accounts for market fluctuations). * If true, the close price is set to the requested close price plus a penalty ratio. * The final close price is then the higher value between this computed price and the average price over the timeframe. * **For SHORT positions:** The function verifies that the lowest price is less than or equal to the requested close price minus the gap ratio. * If true, the close price is computed as the requested close price minus the penalty ratio. * The final close price is the lower value between this computed price and the average price. * **Signature Verification:** The function uses the new **HighLowPriceSig** structure to verify that the market data (high, low, average, and current prices) is authentic and within the acceptable timeframe. This signature is obtained via the `priceRange` method on Muon. After all validations pass, the function updates nonce counters for both Party A and Party B, and then calls an internal helper to close the quote. If conditions fail (for example, if the market does not meet the necessary thresholds), Party B may instead be liquidated. * * * **Function Signature:** **Parameters:** * **quoteId:** The unique identifier of the quote associated with the position. * Hi**ghLowPriceSig:** * * * **Events Emitted:** **LiquidatePartyB:** If the validations determine that Party B is insolvent (e.g., if closing the position would leave Party B with insufficient funds), an event is emitted to indicate liquidation: **ForceClosePosition:** If the force‑close operation completes successfully, the following event is emitted: (A backward compatibility event without `closeId` is also emitted.) * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/force-actions-facet-0.8.4#settleandforcecloseposition) settleAndForceClosePosition() This method extends the force close mechanism to handle cases where the hedger (Party B) lacks sufficient allocated balance to close the position. In such scenarios, the function first settles the UPnL (unrealized profit and loss) for Party B, thereby adjusting the balances, and then force-closes the position. **Function Signature:** **Parameters:** * `quoteId`: The unique identifier of the quote corresponding to the position. * `highLowPriceSig`: A `HighLowPriceSig` structure containing market price data (including high, low, average, and current prices) and the associated timing information. * `settleSig`: A `SettlementSig` structure that includes data required for settling UPnLs (such as settlement values, quotes settlements data, etc.). * `updatedPrices`: An array of updated prices to be applied as the new opened prices for the specified quotes during settlement. **Example Usage:** **Events Emitted:** * If Party B is liquidated during the process, the event: `LiquidatePartyB(address initiator, address partyB, address partyA, uint256 partyBAllocatedBalance, int256 upnlPartyB)` is emitted. * Otherwise, two key events are emitted: * `SettleUpnl(...)`: Emitted with details of the settlement, including the settlement data, updated prices, and new allocated balances. * `ForceClosePosition(...)`: Emitted to indicate the successful force closure of the position (with both the current and a backward compatibility version). [PreviousControl Facet (0.8.4)chevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/control-facet-0.8.4) [NextFunding Rate Facet (0.8.4)chevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/funding-rate-facet-0.8.4) Last updated 11 months ago * [forceCancelQuote()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/force-actions-facet-0.8.4#forcecancelquote) * [forceCancelCloseRequest()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/force-actions-facet-0.8.4#forcecancelcloserequest) * [forceClosePosition()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/force-actions-facet-0.8.4#forcecloseposition) * [settleAndForceClosePosition()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/force-actions-facet-0.8.4#settleandforcecloseposition) sun-brightdesktopmoon Copy function forceCancelCloseRequest(uint256 quoteId) external notLiquidated(quoteId) whenNotPartyAActionsPaused; Copy // Force cancel the close request for quote ID 42 diamond.forceCancelCloseRequest(42); Copy function forceClosePosition(uint256 quoteId, HighLowPriceSig memory sig) external notLiquidated(quoteId) whenNotPartyAActionsPaused; Copy struct HighLowPriceSig { bytes reqId; uint256 timestamp; uint256 symbolId; uint256 highest; uint256 lowest; uint256 averagePrice; uint256 startTime; uint256 endTime; int256 upnlPartyB; int256 upnlPartyA; uint256 currentPrice; bytes gatewaySignature; SchnorrSign sigs; } Copy event LiquidatePartyB(address initiator, address partyB, address partyA, uint256 partyBAllocatedBalance, int256 upnlPartyB); Copy event ForceClosePosition( uint256 quoteId, address partyA, address partyB, uint256 filledAmount, uint256 closedPrice, QuoteStatus quoteStatus, uint256 closeId ); Copy function settleAndForceClosePosition( uint256 quoteId, HighLowPriceSig memory highLowPriceSig, SettlementSig memory settleSig, uint256[] memory updatedPrices ) external notLiquidated(quoteId) whenNotPartyAActionsPaused; Copy struct HighLowPriceSig { bytes reqId; uint256 timestamp; uint256 symbolId; uint256 highest; uint256 lowest; uint256 averagePrice; uint256 startTime; uint256 endTime; int256 upnlPartyB; int256 upnlPartyA; uint256 currentPrice; bytes gatewaySignature; SchnorrSign sigs; } Copy struct SettlementSig { bytes reqId; uint256 timestamp; QuoteSettlementData[] quotesSettlementsData; int256[] upnlPartyBs; int256 upnlPartyA; bytes gatewaySignature; SchnorrSign sigs; } Copy // Settle and force close a position with updated price data HighLowPriceSig memory highLowSig = /* obtain high/low signature data */; SettlementSig memory settleSig = /* obtain settlement data */; uint256[] memory newPrices = new uint256[](1); newPrices[0] = updatedPrice; diamond.settleAndForceClosePosition(42, highLowSig, settleSig, newPrices); sun-brightdesktopmoon --- # Mantle | SYMMIO Protocol Gitbook circle-info In case a Facet Address is incorrect/outdated, you can use the diamond inspection tool [here arrow-up-right](https://louper.dev/) and paste the diamond address to find the updated facet addresses of all contracts. [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/mantle#contract-addresses) Contract Addresses -------------------------------------------------------------------------------------------------------------------------- Name Address Diamnond 0x2Ecc7da3Cc98d341F987C85c3D9FC198570838B5 AccountFacet 0x9f8f9D8B8bfCcF3D782564e6D9cC09371792c2cb DiamondCutFacet 0x464873026877c9D947E2778a1B4cB4A3CbC688F0 ControlFacet 0x0e35FA030fd3Bbed41993BC288B7378cC43F39Ac DiamondLoupeFacet 0xCF74C49be20351EF069E3F32B6e646d4B2Ba69D9 LiquidationFacet 0x50154e11eDf5D7d528cBc7Ec0D507dDB70B8B1c6 PartyAFacet 0x8F00a481C046e98FDEe4ea673dF2984376946953 PartyBFacet 0xa46E5D77a18b93803fa0d3641d868DC9bdd381B4 ViewFacet 0x7E8b57477727c46d13d573340D72DD27e4dD98d3 FundingRateFacet 0x8c466c5aF916a7ef6250Bc82FC7C7d022e3114F2 BridgeFacet 0x20dD479C8210ca675f9351b8dAAF439026541A5A [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/mantle#affiliate-addresses) Affiliate Addresses ---------------------------------------------------------------------------------------------------------------------------- [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/mantle#intentx) IntentX ---------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/mantle#multiaccount) MultiAccount `0xECbd0788bB5a72f9dFDAc1FFeAAF9B7c2B26E456` ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/mantle#fee-collector) Fee Collector `0xA2C779F0950Aa771663cf1b0B8Ce64D5B3B29c19` [PreviousContract Addresseschevron-left](https://docs.symm.io/protocol-architecture/contract-addresses) [NextModechevron-right](https://docs.symm.io/protocol-architecture/contract-addresses/mode) Last updated 29 days ago * [Contract Addresses](https://docs.symm.io/protocol-architecture/contract-addresses/mantle#contract-addresses) * [Affiliate Addresses](https://docs.symm.io/protocol-architecture/contract-addresses/mantle#affiliate-addresses) * [IntentX](https://docs.symm.io/protocol-architecture/contract-addresses/mantle#intentx) * [MultiAccount](https://docs.symm.io/protocol-architecture/contract-addresses/mantle#multiaccount) * [Fee Collector](https://docs.symm.io/protocol-architecture/contract-addresses/mantle#fee-collector) sun-brightdesktopmoon sun-brightdesktopmoon --- # Instant Trading Condition Checks | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-condition-checks#instant-open) Instant Open --------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-condition-checks#instant-open-and-sendquote-condition-checks) Instant Open and sendQuote Condition Checks This section outlines the required checks necessary for executing Instant Open and sendQuote actions with SYMMIO. These checks ensure that the operations meet all necessary criteria before they are processed in order to minimize the likelihood of an order being invalid when attempting to write it to the contract. Overview As a solver/FE there should be several validation checks on a quote that must be passed before an Instant Open or Regular sendQuote action can be executed. These checks cover various aspects, such as user account status, market conditions, and master agreement rules. **Purpose** The condition checks are designed to: 1. Verify user and account status: Ensure that the user (Party A) is eligible to perform the requested action. 2. Validate market conditions: Confirm that the requested operation adheres to current market rules and conditions, and the order is able to be hedged. 3. Enforce platform constraints: Ensure the action complies with the Master Agreement limits, such as maximum number of open orders and solvency checks. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-condition-checks#key-checks-and-validations) Key Checks and Validations * Conditions: * * Check Suspension(FE/Solver): Ensure that Party A is not suspended on Symmio contract. If they are, refuse the quote. * Check RFQ is enabled(FE): Verify whether RFQ is enabled for the requested symbol and that the symbol is not blacklisted in the solver. * Check the quote deadline(FE/Solver): Check if the deadline for processing the quote is sufficient. * Check the number of open orders(Solver): Ensure that the number of open orders for the symbol does not exceed Binance's limits. (200 quotes per symbol) * Check the usage cap(FE/Solver): Verify that the order would not violate your notional cap limit. * Check the Binance bracket condition(Solver): (this check can be ignored if it is considered in notional cap value). Check if a given quote falls within a "bracket" on Binance depending on the current position on the same symbol of Binance, determined by the current notional value of the position. Also find the maintenance margin ratio Additionally, verify that the leverage used in the quote is within the limits set by Binance for that bracket. * Check the counterparty health ratio(FE/Solver): Ensure that the counterparty's (partyA) health ratio is adequate to fulfill their request. * Check the mark price(Solver): Ensure that the difference between the mark price in the quote (given from Muon) and the actual market price is within an acceptable threshold (for MARKET orders). * Check the quote data(Solver): Verify that the quote data from the contract matches the expected data. Check various attributes like state, quantity, cva, party A and B maintenance margin and the requestedOpenPrice. * Check whether the quote was unlocked(Solver): Prevent locking of quotes that have already been unlocked by the solver. * Check the max funding rate of the quote(Solver): Validate that the funding rate specified in the quote matches the allowed funding rate on the solver. * Validate the partyB mm(Solver): Validate that the maintenance margin (MM) for Party B is within an acceptable boundary. * Validate the price range (FE/Solver): Validate that the requested price for the quote is within the allowable range according to Binance's rules (solver rule). * Validate the notional value of the quote(FE/Solver): Ensure that the notional value of the quote is within the solver defined upper and lower boundaries. * Check the quote locked values percentage(FE/Solver): Verify that the locked values (CVA, LF, and Party A’s MM) are within the acceptable percentage ranges for the quote. * Check the number of pending quotes for partyA(FE/Solver): Ensure that partyA’s pending quotes do not exceed the maximum for the Master Agreement. Include both the regular sendQuotes and instant orders. * Check whether Party A has a sufficient available balance(FE/Solver): Check whether Party A’s available balance will cover his order. Also in Instant Open, verify that Party A’s allocated balance covers the Symmio platform fee for the quote. * Check the partyA is not liquidated(FE/Solver): Check that the partyA is not liquidated or just about to face liquidation [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-condition-checks#instant-close) Instant Close ----------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-condition-checks#request-to-close-and-instant-close-condition-checks) Request to Close and Instant Close Condition Checks This section outlines the required checks necessary for executing requestToClosePosition and Instant Close actions with SYMMIO. These checks are crucial for ensuring that a position can be safely and successfully closed without causing issues such as insufficient allocated balance. By implementing these checks at both the UI level and within the solver logic, scenarios where a user’s request to close a position fails can be minimized. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-condition-checks#ui-checks-and-solver-responsibilities) UI Checks and Solver Responsibilities Before a requestToClosePosition or Instant Close, several condition checks must be conducted by both the user interface (UI) and the solvers. These should checks include: * Solvency Verification: Ensure that the user’s allocated balance is sufficient to cover the position being closed. The UI should prevent users from initiating a close if their balance does not meet the required threshold. * Position Count Check (This policy is valid until Symmio v0.8.4, after that parties can use settleUpnl function to tackle the issue):If a user holds more than one position in a subaccount, certain actions like setting a stop-loss should be restricted to prevent scenarios where conflicting positions might cause issues during closure. **Checking PartyA has enough Allocated Balance** This function should verify whether Party A (the user) has sufficient allocated balance to close the requested position, especially in the case of a non-profitable close. Details: * Profitable Close Check: First determine if the close is profitable by comparing the current market price with the price at which the position was opened. * * For a LONG position, check if the market price is greater than or equal to the opened price. * For a SHORT position, check if the market price is less than or equal to the opened price. Allocated Balance Check: If the close is not profitable, it checks if the user’s allocated balance is sufficient to cover the potential loss calculated as: **Check the Quote Deadline** This check should ensure that the deadline provided in the close request is adequate to process the request on time. **Details**: * Retrieve the minimum time required for processing the request based on the symbol and order type. * Compare the current time plus the required processing time against the provided deadline in the close request. Check PartyA’s remaining amount This check verifies that the remaining amount after the close request is acceptable based on predefined conditions. **Details:** Calculate the remaining quantity after the close using: * The check should then confirm if the remaining amount is acceptable. If the remaining amount is acceptable, the check passes. **Check the number of open orders** This check ensures that the number of open orders does not exceed the maximum limit allowed by Binance. Details: * First verify if the position is hedged. * If it is hedged, it should check the number of open orders for the symbol. Check PartyA’s solvency after the close This check should ensure that the counterparty remains solvent after the close request is processed. Details: * Retrieve Party A’s account information, including their allocated balance, unrealized profit and loss (Upnl), and locked funds. * Calculate the unlock amount based on the proportion of the position being closed. * Compute the available balance after considering the uPnl, unlocked amount, and the locked funds. The check should then verify: * Long Position: The function should check if the approximate close price is at or below the current market price and ensures that Party A's available balance can cover any potential loss. * Short Position: The function should check if the approximate close price is at or above the current market price and ensures that Party A's available balance can cover any potential loss. If the position is not profitable, the function should ensure that the available balance is greater than or equal to the expected loss, which is calculated as the difference between the close price and the market price multiplied by the quantity being closed. **Validate Close Request Data** This check should validate that the close request data matches the contract's current data. Details: * Retrieve the current quote data from the SYMMIO Diamond. * Compare various attributes like `quoteStatus`, `requestedClosePrice`, and `quantityToClose` between the quote data and the close request data. **Check the Price Range of the Close Request** This check should ensure that the requested close price is within an acceptable range according to Binance’s trading rules. [PreviousRasa Instant Trading Implementationchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation) [NextHow to Add a Market as a Solverchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/how-to-add-a-market-as-a-solver) Last updated 1 year ago * [Instant Open](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-condition-checks#instant-open) * [Instant Open and sendQuote Condition Checks](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-condition-checks#instant-open-and-sendquote-condition-checks) * [Instant Close](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-condition-checks#instant-close) * [Request to Close and Instant Close Condition Checks](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-condition-checks#request-to-close-and-instant-close-condition-checks) sun-brightdesktopmoon Copy loss = abs(opened_price - approximate_close_price) * quantityToClose Copy remaining_amount = filled_opened_amount - filled_closed_amount - quantityToClose Copy # position.cva, position.lf and position.mm dont update during position lifetime unlock_amount = ( (position.cva + position.lf) * close_request_struct.quantityToClose / position.quantity Copy available_balance = ( account_info.allocated_balance + upnl + unlock_amount - (account_info.cva + account_info.lf) ) Copy approximate_close_price=close_request_struct.approximate_close_price ) if ( position.position_type == PositionType.LONG and close_request_struct.approximate_close_price <= price ) or ( position.position_type == PositionType.SHORT and close_request_struct.approximate_close_price >= price ): return Comparator.gte( Operands(available_balance, "available_balance"), Operands( ( close_request_struct.quantityToClose * abs(close_request_struct.approximate_close_price - price) ), "solvency_threshold", ), ) return True sun-brightdesktopmoon --- # 12-Hour Fraud Proof Window | SYMMIO Protocol Gitbook Symmio is designed with a structure akin to an **optimistic layer 2 solution**, enabling a robust, efficient, and decentralized trading system. At its core, Symmio operates on the principle of **optimistic finality**, assuming that all transactions are valid and finalized instantly, regardless of the underlying blockchain's finality. This approach not only enhances the speed and usability of the platform but also integrates a **12-hour fraud proof window** to provide critical security and reliability benefits. #### [hashtag](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/12-hour-fraud-proof-window#benefits-of-the-12-hour-fraud-proof-window) Benefits of the 12-Hour Fraud Proof Window 1. **Instant Finality with Layered Protection** By assuming transactions are instantly final, Symmio eliminates delays typically associated with blockchain finality, such as the 15-minute wait for confirmation on certain chains. This ensures seamless and real-time trading experiences for users while maintaining a safety mechanism to review potentially malicious activities during the fraud proof window. 2. **Zero-Day Exploit Mitigation** The 12-hour fraud proof window acts as a protective layer against unforeseen vulnerabilities or zero-day exploits. This buffer period allows the system to detect, verify, and address any anomalies before they can propagate further. * * * #### [hashtag](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/12-hour-fraud-proof-window#symmios-layered-verification-model) Symmio’s Layered Verification Model Symmio employs a multi-layered verification system to ensure trust and fairness, even within its optimistic framework. The roles and interactions between key participants are structured as follows: **Layer 1: User ↔ Solver Relationship** * **Users and Solvers** interact directly to execute trades and transactions. * In the event of a dispute, the **Oracle** serves as an impartial arbiter to resolve disagreements based on predefined rules. **Layer 2: Oracle Fraud Protection** * Should a malicious actor compromise or manipulate the Oracle, the **Fraud Proof Checkers** serve as an additional safeguard. * These checkers are empowered to **suspend users** and address discrepancies, acting as a failsafe mechanism. **Fraud Proof Checkers: Final Security Layer** * Fraud proof checkers monitor for issues such as **double spends**—a scenario usually prevented by blockchain finality. * In Symmio, solvers can’t afford to wait for on-chain finality (e.g., 15 minutes). Instead, they act optimistically, trusting the system’s layered security to catch and address any violations during the 12-hour fraud proof window. * * * #### [hashtag](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/12-hour-fraud-proof-window#why-this-approach-works-for-symmio) Why This Approach Works for Symmio Symmio’s unique blend of optimistic finality and layered verification ensures that: * Transactions are processed in real time for optimal user experience. * System integrity is maintained through a combination of oracles and fraud proof checkers. * The 12-hour fraud proof window provides a secure fallback to address any irregularities, reinforcing trust in the ecosystem. By combining instant usability with robust security, Symmio strikes the perfect balance between speed and reliability, paving the way for a decentralized and censorship-resistant derivatives market. [PreviousMaintenance Margin (CVA) Calculationschevron-left](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/maintenance-margin-cva-calculations) [NextGlossarychevron-right](https://docs.symm.io/protocol-architecture/glossary) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Builders introduction | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/building-on-symmio/builders-introduction#want-to-provide-liquidity-to-symmio) Want to provide Liquidity to Symmio? ------------------------------------------------------------------------------------------------------------------------------------------------------ Learn how to become: [Solving for Symmio](https://docs.symm.io/building-on-symmio/solving-for-symmio) [hashtag](https://docs.symm.io/building-on-symmio/builders-introduction#want-to-tap-into-symmio-liquidity-and-launch-your-own-derivatives-exchange) Want to tap into Symmio Liquidity and launch your own derivatives exchange? ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Go to: [Exchanges (Frontend Builders)](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders) [hashtag](https://docs.symm.io/building-on-symmio/builders-introduction#want-to-trade-on-symmio) Want to Trade on Symmio? ------------------------------------------------------------------------------------------------------------------------------ Select an: [Exchangearrow-up-right](https://symm.io/frontends) [PreviousPolygon (0.2.1)chevron-left](https://docs.symm.io/options-protocol-architecture/contract-addresses/polygon-0.2.1) [NextSolving for Symmiochevron-right](https://docs.symm.io/building-on-symmio/solving-for-symmio) Last updated 9 months ago * [Want to provide Liquidity to Symmio?](https://docs.symm.io/building-on-symmio/builders-introduction#want-to-provide-liquidity-to-symmio) * [Want to tap into Symmio Liquidity and launch your own derivatives exchange?](https://docs.symm.io/building-on-symmio/builders-introduction#want-to-tap-into-symmio-liquidity-and-launch-your-own-derivatives-exchange) * [Want to Trade on Symmio?](https://docs.symm.io/building-on-symmio/builders-introduction#want-to-trade-on-symmio) sun-brightdesktopmoon sun-brightdesktopmoon --- # MuonStorage | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/muonstorage#deferred-liquidation) Deferred Liquidation --------------------------------------------------------------------------------------------------------------------------------------------------------------------- Previously, the `upnlValidTime` variable in the Muon configuration prevented the liquidator from liquidating a user after a certain amount of time. This update allows the liquidator to liquidate the user if they haven't increased their nonce, provided the Muon app can supply signatures for a specific block requested by the liquidator. The `LiquidationSig` struct has been updated accordingly: Copy // From struct LiquidationSig { bytes reqId; uint256 timestamp; bytes liquidationId; int256 upnl; int256 totalUnrealizedLoss; uint256[] symbolIds; uint256[] prices; bytes gatewaySignature; SchnorrSign sigs; } // To struct LiquidationSig { bytes reqId; uint256 timestamp; // Timestamp when the liquidation signature was created uint256 liquidationBlockNumber; // Block number at which the user became insolvent uint256 liquidationTimestamp; // Timestamp when the user became insolvent uint256 liquidationAllocatedBalance; // User's allocated balance at the time of insolvency bytes liquidationId; int256 upnl; // User's unrealized profit and loss at the time of insolvency int256 totalUnrealizedLoss; // Total unrealized loss of the user at the time of insolvency uint256[] symbolIds; uint256[] prices; bytes gatewaySignature; SchnorrSign sigs; } [PreviousNew Eventschevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events) [NextContracts Documentation 0.8.4chevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Bug bounty / Coverage | SYMMIO Protocol Gitbook 1. **Critical Level:** * Up to $800,000 or 10% of the (potential) economic damage on contracts with more funds locked than 1 million USD. * The 10% rule also applies to funds already removed without authorization from respective contracts. In such cases, 90% of the funds must be immediately returned, and 10% can be kept as a Whitehat bounty reward. * The 10% rule can also be claimed as a general bug bounty on contracts above $1m TVL, by providing a PoC or by assisting the team in creating a PoC. #### [hashtag](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/bug-bounty-coverage#critical) Critical * 808,808 USDC maximum payout * 80,000 USDC minimum payout * Payout shall not exceed 10% of funds at risk at time of submission ### [hashtag](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/bug-bounty-coverage#severity-criteria) Severity Criteria ### [hashtag](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/bug-bounty-coverage#critical-definition) Critical Definition * Definite and significant loss of funds without limitations of external conditions * Definite and significant freezing of funds for >1 year without limitations of external conditions ### [hashtag](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/bug-bounty-coverage#general-notes) General Notes * Sherlock’s Criteria for Issue Validity guide (used in Sherlock audit contests) can be a helpful resource for more context on out-of-scope issues, etc. but nothing in the guide should overrule the definitions above * A coded Proof of Concept (POC) with instructions to run the POC is required * If the protocol team has the ability to take measures (upgrade the contract, pause the contract, etc.) against an exploit, the potential damage is limited to a 1-hour exploit period before it is assumed that the protocol team takes measures to prevent further damage ### [hashtag](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/bug-bounty-coverage#platform-rules) Platform Rules Please review the [Sherlock Bug Bounty Platform Rulesarrow-up-right](https://docs.google.com/document/d/1fHM85t-nJb9F2T_vk28YUF34jey_uQP5aZyS9om3Dq4/edit?usp=sharing) before submitting any vulnerability. ### [hashtag](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/bug-bounty-coverage#known-issues-and-acceptable-risks) Known Issues and Acceptable Risks * In the liquidation system, we allow liquidators to liquidate a user if they were insolvent before. The nonce should not be changed from that time (essentially, the user's positions should remain unchanged during this period). If the user adds funds to become solvent, the liquidator can still liquidate the user and return the extra funds. ### [hashtag](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/bug-bounty-coverage#previous-audits) Previous Audits * [https://audits.sherlock.xyz/contests/427arrow-up-right](https://audits.sherlock.xyz/contests/427) * [https://audits.sherlock.xyz/contests/144arrow-up-right](https://audits.sherlock.xyz/contests/144) * [https://audits.sherlock.xyz/contests/108arrow-up-right](https://audits.sherlock.xyz/contests/108) * [https://audits.sherlock.xyz/contests/85arrow-up-right](https://audits.sherlock.xyz/contests/85) * [Smart Statearrow-up-right](https://github.com/SYMM-IO/audits/blob/main/26092306_Symmio_report.pdf) The 10% rule only applies for contracts that are live, and have a TVL more than $1M 1. **High Level:** * $50,000 or up to 1% of the (potential) economic damage. * The 10% rule, as outlined in the Critical Level section, also applies. 2. **Medium Level:** * USD $5,000 Payout. * Runnable PoC required. 3. **Low Level:** * USD $1,000 Payout. * Runnable PoC required. circle-exclamation Please note that for a Bug Bounty submission to be seen as critical the actual funds need to be able to be withdrawn by the Attacker from the system, that means the [12 hour withdrawal](https://docs.symm.io/protocol-architecture/protocol-higher-level-architecture/12-hour-fraud-proof-window) window has to be circumvented by the attacker, otherwise the submission would be counted as High. #### [hashtag](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/bug-bounty-coverage#smart-contracts) Smart Contracts Level Impact 5\. Critical \- Direct theft of any user funds, whether at-rest or in-motion, other than unclaimed yield - Permanent freezing of funds 4\. High \- Theft of unclaimed yield - Theft of unclaimed royalties - Permanent freezing of unclaimed yield - Permanent freezing of unclaimed royalties - Griefing (e.g. no profit motive for an attacker, but damage to the users or the protocol) 3\. Medium \- Block stuffing for profit - Unbounded gas consumption - Temporary freezing of funds 2\. Low \- Contract fails to deliver promised returns, but doesn't lose value - Miner-extractable value (MEV) 1\. None \- Best practices - Smart contract unable to operate due to lack of token funds Payouts are handled by **SYMMIO Team or DAO** directly and are denominated in **USDC or SYMM**. Payment in maximum 70% stable & minimum 30% native token. [PreviousSecurity (Audits / Bugbounty)chevron-left](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty) [NextHow to contact ?chevron-right](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/bug-bounty-coverage/how-to-contact) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Solver documentation | SYMMIO Protocol Gitbook ![](https://images.gitbook.com/__img/width=256,format=auto,signature=485166135/https%3A%2F%2Ffiles.gitbook.com%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fintegrations%252Fgithub-files%252Ficon%252FyLv8rmwlZaZ4xBFdwZLt%252Ficon.png%3Falt%3Dmedia) Not found **The term "Hedger" is referred to a MarketMaker or Solver that provides Liquidity on Symmio.** more information can also be found on Gitbook [https://github.com/SYMM-IO/docs/tree/main/hedger\_docsarrow-up-right](https://github.com/SYMM-IO/docs/tree/main/hedger_docs) **Scope and Perspective:** This documentation is curated from the perspective of an "example hedger" that adopts a precise 1:1 A-Book hedging strategy. This Strategy ensures that this "example hedger" remains delta neutral at every point in time, eliminating any directional exposure. This approach should be interpreted as an example and not as an absolute when interacting with the Symmio system, every MarketMaker has full control to, at any point when interacting with the core protocol, design his own hedging strategy, or not hedge at all. But the Symmio protocol is specifiically designed in a way that gives MarketMakers the time and ability to hedge their trades comfortably if they decide to do so. **Operational Context:** When this "example hedger" initiates a trade on Symmio, they directly open a direct countertrade on their chosen broker platform (for instance, Binance) before filling the order onchain. A unique aspect of this strategy is its sequential nature: a trade is only filled onchain when its hedging counterpart is confirmed, and conversely, it's only closed after the hedging trade is conclusively settled. **Documentation Purpose:** This liquidity provision strategy and the ensuing documentation serve as a template for what can be perceived as the lowest risk profile attainable in the hedging arena. However, a note of clarity: while this approach is streamlined and minimizes risks, we recognize it's somewhat rudimentary. Veteran market makers, armed with profound expertise, may devise intricate strategies that could potentially yield heightened profits, the Symmio system gives MarketMakers one hundred percent control over the hedging strategy they want to apply. Any segments of this documentation that could be interpreted differently should be perceived purely as guidelines. They document aims to explain how a basic strategy could be seamlessly implemented, but in no way restrict or limit the development of other strategic avenues one might pursue. ### [hashtag](https://docs.symm.io/building-on-symmio/solving-for-symmio/solver-documentation#user-content-additional-disclaimer---symmio-core-systems-and-hedger-relationship) [Additional Disclaimer - SYMMIO core systems and Hedger relationshiparrow-up-right](https://github.com/SYMM-IO/docs/blob/main/hedger_docs/How%20To%20Implement%20Your%20Own%20Hedger%20For%20SYMMIO.md#additional-disclaimer---symmio-core-systems-and-hedger-relationship) **Educational Use:** This Hedger documentation is crafted with a singular goal in mind: to provide a fundamental understanding of the hedger's role in the Symmio system to it's readers. (MarketMakers, Investors and everyone who is interested in becoming a Hedger himself) The Hedger documentation is educational and not a comprehensive reflection of the entire Symmio protocol. It is structured to provide an introductory grasp of what it means to be a hedger and offers a primer on how one can undertake this role. **Misconceptions:** Some readers might have concluded that the Symmio system depends on MarketMakers hedging themselves, leading to assumed trust dependencies on the MarketMaker side or that user funds and hedger funds are somehow dependent on off-chain brokers or results of hedging strategies. However, this understanding needs to be revised and could lead to erroneous interpretations of the system's architecture. **Top-Down Relationship:** To reiterate and clarify, the relationship between a Hedger and the Symmio protocol is top-down. That means whatever actions a hedger takes off-chain have no bearing on the on-chain events. Thus, there are no trust assumptions regarding the hedger side of things as they use off-chain systems to hedge themselves or the connection between these off-chain systems and Symmio itself. **Independent On-Chain Contracts:** The Symmio contracts function independently of any off-chain actions a hedger performs. They operate exclusively within the on-chain environment and are not influenced or impacted by external actions. The Symmio system is fully isolated from any issues that may or may not arise in combination with MarketMakers and the off-chain systems, centralized exchanges, trading desks, or any other forms of hedging they use. We strongly recommend readers to familiarize themselves with these points to understand Hedger's role and its interaction with the Symmio protocol. It's essential to interpret the Hedger section in light of these clarifications to avoid misrepresentations of the Symmio protocol's actual functioning. #### [hashtag](https://docs.symm.io/building-on-symmio/solving-for-symmio/solver-documentation#user-content-broker-definition) [Broker definitionarrow-up-right](https://github.com/SYMM-IO/docs/blob/main/hedger_docs/How%20To%20Implement%20Your%20Own%20Hedger%20For%20SYMMIO.md#broker-definition) Within the scope of Hedger's documentation, the term "Broker" holds a specific connotation, distinct from conventional interpretations. Let’s elucidate that. When the term "Broker" is mentioned in the context of being a Hedger on Symmio, it is being referred to as a general "hedging strategy" that a MarketMaker (MM) can optionally design to hedge their Symmio trades. Importantly, it's vital to understand that our system doesn't necessitate a MarketMaker to hedge their trades. In fact, it's entirely optional. However, we've architected Symmio in such a way that if a MarketMaker decides to hedge, the system allows you to do so easily, it's entirely designed to make it simple and straightforward. Broad Application of the Term The term "Broker" is expansive in our context. It can encompass: Centralized Exchanges (CEX) Decentralized Exchanges (DEX) Over-The-Counter (OTC) Desks Spot holdings Any other hedging strategies, whether they exist on-chain or off-chain. A Note on Hedging Strategies We don’t categorize or prioritize one method of hedging over another. All are viewed through the same lens, and are designed by MarketMakers themselfs to be delta neutral or not, the system is designed to offer MarketMakers the potential to optimize their efficiency infinitely. Moreover, we acknowledge that the realm of hedging is vast, with potentially limitless strategies and methods for securing a position. Thus, when you come across "Broker" in our documentation, remember that it speaks to this broad, encompassing perspective. [PreviousSolving for Symmiochevron-left](https://docs.symm.io/building-on-symmio/solving-for-symmio) [NextSolver - Example Flowchevron-right](https://docs.symm.io/building-on-symmio/solving-for-symmio/solver-example-flow) Last updated 29 days ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Modified Events | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#accounting-events) **Accounting Events** ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#allocatepartya) `**AllocatePartyA**` **Old Event**: Copy event AllocatePartyA(address user, uint256 amount); **New Event**: Copy event AllocatePartyA(address user, uint256 amount, uint256 newAllocatedBalance); ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#deallocatepartya) `**DeallocatePartyA**` **Old Event**: Copy event DeallocatePartyA(address user, uint256 amount); **New Event**: Copy event DeallocatePartyA(address user, uint256 amount, uint256 newAllocatedBalance); ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#allocateforpartyb) `**AllocateForPartyB**` **Old Event**: Copy event AllocateForPartyB(address partyB, address partyA, uint256 amount); **New Event**: ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#deallocateforpartyb) `**DeallocateForPartyB**` **Old Event**: **New Event**: ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#transferallocation) `**TransferAllocation**` **Old Event**: **New Event**: [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#control-events) **Control Events** ----------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#setmuonconfig) `**SetMuonConfig**` **Old Event**: **New Event**: ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#setfeecollector) `**SetFeeCollector**` **Old Event**: **New Event**: ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#setforceclosecooldown) `**SetForceCloseCooldown**` **Old Event**: **New Event**: ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#setforceclosegapratio) `**SetForceCloseGapRatio**` **Old Event**: **New Event**: [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#liquidation-events) **Liquidation Events** ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#setsymbolsprices) `**SetSymbolsPrices**` **Old Event**: **New Event**: ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#liquidatepartya) `**LiquidatePartyA**` **Old Event**: **New Event**: ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#liquidatepositionspartya) `**LiquidatePositionsPartyA**` **Old Event**: **New Event**: ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#liquidatependingpositionspartya) `**LiquidatePendingPositionsPartyA**` **Old Event**: **New Event**: ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#settlepartyaliquidation) `**SettlePartyALiquidation**` **Old Event**: **New Event**: ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#liquidationdisputed) `**LiquidationDisputed**` **Old Event**: **New Event**: ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#resolveliquidationdispute) `**ResolveLiquidationDispute**` **Old Event**: **New Event**: ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#fullyliquidatedpartya) `**FullyLiquidatedPartyA**` **Old Event**: **New Event**: ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#liquidatepositionspartyb) `**LiquidatePositionsPartyB**` **Old Event**: **New Event**: [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#close-events) **Close Events** ------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#requesttocloseposition) `**RequestToClosePosition**` **Old Event**: **New Event**: ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#requesttocancelcloserequest) `**RequestToCancelCloseRequest**` **Old Event**: **New Event**: ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#forcecancelcloserequest) `**ForceCancelCloseRequest**` **Old Event**: **New Event**: ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#forcecloseposition) `**ForceClosePosition**` **Old Event**: **New Event**: ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#fillcloserequest) `**FillCloseRequest**` **Old Event**: **New Event**: ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#acceptcancelcloserequest) `**AcceptCancelCloseRequest**` **Old Event**: **New Event**: ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#emergencycloseposition) `**EmergencyClosePosition**` **Old Event**: **New Event**: [PreviousLiquidation Facet (Implementation)chevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/liquidation-facet-implementation) [NextNew Eventschevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events) Last updated 1 year ago * [Accounting Events](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#accounting-events) * [AllocatePartyA](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#allocatepartya) * [DeallocatePartyA](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#deallocatepartya) * [AllocateForPartyB](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#allocateforpartyb) * [DeallocateForPartyB](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#deallocateforpartyb) * [TransferAllocation](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#transferallocation) * [Control Events](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#control-events) * [SetMuonConfig](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#setmuonconfig) * [SetFeeCollector](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#setfeecollector) * [SetForceCloseCooldown](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#setforceclosecooldown) * [SetForceCloseGapRatio](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#setforceclosegapratio) * [Liquidation Events](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#liquidation-events) * [SetSymbolsPrices](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#setsymbolsprices) * [LiquidatePartyA](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#liquidatepartya) * [LiquidatePositionsPartyA](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#liquidatepositionspartya) * [LiquidatePendingPositionsPartyA](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#liquidatependingpositionspartya) * [SettlePartyALiquidation](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#settlepartyaliquidation) * [LiquidationDisputed](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#liquidationdisputed) * [ResolveLiquidationDispute](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#resolveliquidationdispute) * [FullyLiquidatedPartyA](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#fullyliquidatedpartya) * [LiquidatePositionsPartyB](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#liquidatepositionspartyb) * [Close Events](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#close-events) * [RequestToClosePosition](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#requesttocloseposition) * [RequestToCancelCloseRequest](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#requesttocancelcloserequest) * [ForceCancelCloseRequest](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#forcecancelcloserequest) * [ForceClosePosition](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#forcecloseposition) * [FillCloseRequest](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#fillcloserequest) * [AcceptCancelCloseRequest](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#acceptcancelcloserequest) * [EmergencyClosePosition](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events#emergencycloseposition) sun-brightdesktopmoon Copy event AllocateForPartyB(address partyB, address partyA, uint256 amount, uint256 newAllocatedBalance); Copy event DeallocateForPartyB(address partyB, address partyA, uint256 amount); Copy event DeallocateForPartyB(address partyB, address partyA, uint256 amount, uint256 newAllocatedBalance); Copy event TransferAllocation(uint256 amount, address origin, address recipient); Copy event TransferAllocation(uint256 amount, address origin, uint256 originNewAllocatedBalance, address recipient, uint256 recipientNewAllocatedBalance); Copy event SetMuonConfig(uint256 upnlValidTime, uint256 priceValidTime, uint256 priceQuantityValidTime); Copy event SetMuonConfig(uint256 upnlValidTime, uint256 priceValidTime); Copy event SetFeeCollector(address oldFeeCollector, address newFeeCollector); Copy event SetFeeCollector(address affiliate, address oldFeeCollector, address newFeeCollector); Copy event SetForceCloseCooldown(uint256 oldForceCloseCooldown, uint256 newForceCloseCooldown); Copy event SetForceCloseCooldowns(uint256 oldForceCloseFirstCooldown, uint256 newForceCloseFirstCooldown, uint256 oldForceCloseSecondCooldown, uint256 newForceCloseSecondCooldown); Copy event SetForceCloseGapRatio(uint256 oldForceCloseGapRatio, uint256 newForceCloseGapRatio); Copy event SetForceCloseGapRatio(uint256 symbolId, uint256 oldForceCloseGapRatio, uint256 newForceCloseGapRatio); Copy event SetSymbolsPrices(address liquidator, address partyA, uint256[] symbolIds, uint256[] prices); Copy event SetSymbolsPrices(address liquidator, address partyA, uint256[] symbolIds, uint256[] prices, bytes liquidationId); Copy event LiquidatePartyA(address liquidator, address partyA, uint256 allocatedBalance, int256 upnl, int256 totalUnrealizedLoss); Copy event LiquidatePartyA(address liquidator, address partyA, uint256 allocatedBalance, int256 upnl, int256 totalUnrealizedLoss, bytes liquidationId); Copy event LiquidatePositionsPartyA(address liquidator, address partyA, uint256[] quoteIds); Copy event LiquidatePositionsPartyA(address liquidator, address partyA, uint256[] quoteIds, uint256[] liquidatedAmounts, uint256[] closeIds, bytes liquidationId); Copy event LiquidatePendingPositionsPartyA(address liquidator, address partyA); Copy event LiquidatePendingPositionsPartyA(address liquidator, address partyA, uint256[] quoteIds, uint256[] liquidatedAmounts, bytes liquidationId); Copy event SettlePartyALiquidation(address partyA, address[] partyBs, int256[] amounts); Copy event SettlePartyALiquidation(address partyA, address[] partyBs, int256[] amounts, bytes liquidationId); Copy event LiquidationDisputed(address partyA); Copy event LiquidationDisputed(address partyA, bytes liquidationId); Copy event ResolveLiquidationDispute(address partyA, address[] partyBs, int256[] amounts, bool disputed); Copy event ResolveLiquidationDispute(address partyA, address[] partyBs, int256[] amounts, bool disputed, bytes liquidationId); Copy event FullyLiquidatedPartyA(address partyA); Copy event FullyLiquidatedPartyA(address partyA, bytes liquidationId); Copy event LiquidatePositionsPartyB(address liquidator, address partyB, address partyA, uint256[] quoteIds); Copy event LiquidatePositionsPartyB(address liquidator, address partyB, address partyA, uint256[] quoteIds, uint256[] liquidatedAmounts, uint256[] closeIds); Copy event RequestToClosePosition(address partyA, address partyB, uint256 quoteId, uint256 closePrice, uint256 quantityToClose, OrderType orderType, uint256 deadline, QuoteStatus quoteStatus); Copy event RequestToClosePosition(address partyA, address partyB, uint256 quoteId, uint256 closePrice, uint256 quantityToClose, OrderType orderType, uint256 deadline, QuoteStatus quoteStatus, uint256 closeId); Copy event RequestToCancelCloseRequest(address partyA, address partyB, uint256 quoteId, QuoteStatus quoteStatus); Copy event RequestToCancelCloseRequest(address partyA, address partyB, uint256 quoteId, QuoteStatus quoteStatus, uint256 closeId); Copy event ForceCancelCloseRequest(uint256 quoteId, QuoteStatus quoteStatus); Copy event ForceCancelCloseRequest(uint256 quoteId, QuoteStatus quoteStatus, uint256 closeId); Copy event ForceClosePosition(uint256 quoteId, address partyA, address partyB, uint256 filledAmount, uint256 closedPrice, QuoteStatus quoteStatus); Copy event ForceClosePosition(uint256 quoteId, address partyA, address partyB, uint256 filledAmount, uint256 closedPrice, QuoteStatus quoteStatus, uint256 closeId); Copy event FillCloseRequest(uint256 quoteId, address partyA, address partyB, uint256 filledAmount, uint256 closedPrice, QuoteStatus quoteStatus); Copy event FillCloseRequest(uint256 quoteId, address partyA, address partyB, uint256 filledAmount, uint256 closedPrice, QuoteStatus quoteStatus, uint256 closeId); Copy event AcceptCancelCloseRequest(uint256 quoteId, QuoteStatus quoteStatus); Copy event AcceptCancelCloseRequest(uint256 quoteId, QuoteStatus quoteStatus, uint256 closeId); Copy event EmergencyClosePosition(uint256 quoteId, address partyA, address partyB, uint256 filledAmount, uint256 closedPrice, QuoteStatus quoteStatus); Copy event EmergencyClosePosition(uint256 quoteId, address partyA, address partyB, uint256 filledAmount, uint256 closedPrice, QuoteStatus quoteStatus, uint256 closeId); sun-brightdesktopmoon --- # SDK - SYMM client | SYMMIO Protocol Gitbook ### [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/sdk-symm-client#user-content-an-sdk-to-interact-with-symmio-contracts-hedgers-and-peripherals) [An SDK to interact with SYMMIO contracts, hedgers and peripherals.arrow-up-right](https://github.com/SYMM-IO/frontend-sdk#an-sdk-to-interact-with-symmio-contracts-hedgers-and-peripherals) * To enable path completion suggestions in VSCode, first build the project by running yarn build. Then, in the VSCode settings, ensure that "TypeScript > Tsc: Auto Detect" is set to 'on'. * Be sure not to use the publicProvider from Wagmi, as it causes some errors in the SDK. [Wagmi Websitearrow-up-right](https://wagmi.sh/core/getting-started#configure-chains) : > Note: In a production app, it is not recommended to only pass publicProvider to configureChains as you will probably face rate-limiting on the public provider endpoints. It is recommended to also pass an alchemyProvider or infuraProvider as well. [PreviousFrontend Builder Introductionchevron-left](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/frontend-builder-introduction) [NextTrade on Symmiochevron-right](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/trade-on-symmio) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Brand - Assets Logos | SYMMIO Protocol Gitbook file-archive 40KB [Symmio\_Logo\_PNG\_Format.zip](https://1257875949-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FYQhBmTCs9MwhhuPQrV5v%2Fuploads%2FxNLhshESZwwAa4qcNkhy%2FSymmio_Logo_PNG_Format.zip?alt=media&token=a3b2fb27-ae34-490c-8eef-e83af139a261) archive downloadDownload[arrow-up-right-from-squareOpen](https://1257875949-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FYQhBmTCs9MwhhuPQrV5v%2Fuploads%2FxNLhshESZwwAa4qcNkhy%2FSymmio_Logo_PNG_Format.zip?alt=media&token=a3b2fb27-ae34-490c-8eef-e83af139a261) file-archive 14KB [Symmio\_Logo\_SVG\_Format.zip](https://1257875949-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FYQhBmTCs9MwhhuPQrV5v%2Fuploads%2FUzcwhxBJiCVEELdupP3n%2FSymmio_Logo_SVG_Format.zip?alt=media&token=366c62f7-6d4b-44bb-92c1-8ff5c57acf40) archive downloadDownload[arrow-up-right-from-squareOpen](https://1257875949-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FYQhBmTCs9MwhhuPQrV5v%2Fuploads%2FUzcwhxBJiCVEELdupP3n%2FSymmio_Logo_SVG_Format.zip?alt=media&token=366c62f7-6d4b-44bb-92c1-8ff5c57acf40) file-pdf 15MB [Symmio Brandbook.pdf](https://1257875949-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FYQhBmTCs9MwhhuPQrV5v%2Fuploads%2F8GKUUVy4tyjkVh8mwiX2%2FSymmio%20Brandbook.pdf?alt=media&token=b727655f-2edc-4749-8029-ffa60dec78b0) PDF downloadDownload[arrow-up-right-from-squareOpen](https://1257875949-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FYQhBmTCs9MwhhuPQrV5v%2Fuploads%2F8GKUUVy4tyjkVh8mwiX2%2FSymmio%20Brandbook.pdf?alt=media&token=b727655f-2edc-4749-8029-ffa60dec78b0) [PreviousContract Modificationschevron-left](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/contract-license/contract-modifications) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Liquidation Facet (Implementation) | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/liquidation-facet-implementation#changes) Changes: ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/liquidation-facet-implementation#liquidatependingpositionspartya) `**liquidatePendingPositionsPartyA()**` **Updated Return Type**: Updated to return `uint256[] memory liquidatedAmounts, bytes memory liquidationId`. **Updated Code**: Copy accountLayout.partyAReimbursement[partyA] += LibQuote.getTradingFee(quote.id); quote.quoteStatus = QuoteStatus.LIQUIDATED_PENDING; **Updated Functionality**: * Added a new pending state `QuoteStatus.LIQUIDATED_PENDING`. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/liquidation-facet-implementation#liquidatepositionspartya) `**liquidatePositionsPartyA()**` **Updated Return Type**: Updated to return `bool, uint256[] memory liquidatedAmounts, uint256[] memory closeIds, bytes memory liquidationId`. **Updated Code**: Copy liquidatedAmounts[index] = quote.quantity - quote.closedAmount; closeIds[index] = quoteLayout.closeIds[quote.id]; quote.quoteStatus = QuoteStatus.LIQUIDATED; **Updated Functionality**: * Added `closeIds` and `liquidatedAmounts` to capture detailed information about liquidated quotes. * Changed state to `QuoteStatus.LIQUIDATED`. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/liquidation-facet-implementation#resolveliquidationdispute) `**resolveLiquidationDispute()**` **Updated Return Type**: Updated to return `bytes memory`. **Updated Code**: ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/liquidation-facet-implementation#settlepartyaliquidation) `**settlePartyALiquidation()**` **Updated Return Type**: Updated to return `int256[] memory settleAmounts, bytes memory liquidationId`. **Updated Code**: [PreviousBridge Facetchevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/bridge-facet) [NextModified Eventschevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events) Last updated 11 months ago * [Changes:](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/liquidation-facet-implementation#changes) * [liquidatePendingPositionsPartyA()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/liquidation-facet-implementation#liquidatependingpositionspartya) * [liquidatePositionsPartyA()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/liquidation-facet-implementation#liquidatepositionspartya) * [resolveLiquidationDispute()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/liquidation-facet-implementation#resolveliquidationdispute) * [settlePartyALiquidation()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/liquidation-facet-implementation#settlepartyaliquidation) sun-brightdesktopmoon Copy accountLayout.settlementStates[partyA][partyBs[i]].actualAmount = amounts[i]; return accountLayout.liquidationDetails[partyA].liquidationId; Copy emit SharedEvents.BalanceChangePartyA(partyA, accountLayout.settlementStates[partyA][partyB].cva, SharedEvents.BalanceChangeType.CVA_OUT); emit SharedEvents.BalanceChangePartyB(partyB, partyA, accountLayout.settlementStates[partyA][partyB].cva, SharedEvents.BalanceChangeType.CVA_IN); sun-brightdesktopmoon --- # Berachain | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/berachain#contract-addresses) Contract Addresses ----------------------------------------------------------------------------------------------------------------------------- Name Address Diamond 0x3d17f073cCb9c3764F105550B0BCF9550477D266 AccountFacet 0x464873026877c9D947E2778a1B4cB4A3CbC688F0 DiamondCutFacet 0x7e6DC84041E33e20Ac4529a84C8e8201Db785237 ControlFacet 0x2Ecc7da3Cc98d341F987C85c3D9FC198570838B5 DiamondLoupeFacet 0xb74629900981F2977cd7a8E37052fee0D7a4C395 LiquidationFacet 0x0b60140dCC98a6A9e9985aB165Dc54903861D50A PartyAFacet 0x6AE14800C45aE9383db2C3f2eE6019Ebe1E32403 PartyBQuoteActionsFacet 0x8F06459f184553e5d04F07F868720BDaCAB39395 ViewFacet 0x5E0663DEb8683B70E0Ff36E6E6e0DFa0f0069934 FundingRateFacet 0x9D4c169703BB0116751A6965952A5E4aDfDFfB05 BridgeFacet 0xCF74C49be20351EF069E3F32B6e646d4B2Ba69D9 SettlementFacet 0x359AE1329F4070f81079B415249fb13664B6cE76 [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/berachain#affiliate-addresses) Affiliate Addresses ------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/berachain#fee-collector) Fee Collector `0xFa323f509F36919aF51c58d3E8593027C09f57a0` [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/berachain#lode) Lode ------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/berachain#multiaccount) MultiAccount `0x703c4927945Aac2B5a76f4c1D85Bc85e6fAaddB6` [PreviousPolygonchevron-left](https://docs.symm.io/protocol-architecture/contract-addresses/polygon) [NextCotichevron-right](https://docs.symm.io/protocol-architecture/contract-addresses/coti) Last updated 2 months ago * [Contract Addresses](https://docs.symm.io/protocol-architecture/contract-addresses/berachain#contract-addresses) * [Affiliate Addresses](https://docs.symm.io/protocol-architecture/contract-addresses/berachain#affiliate-addresses) * [Fee Collector](https://docs.symm.io/protocol-architecture/contract-addresses/berachain#fee-collector) * [Lode](https://docs.symm.io/protocol-architecture/contract-addresses/berachain#lode) * [MultiAccount](https://docs.symm.io/protocol-architecture/contract-addresses/berachain#multiaccount) sun-brightdesktopmoon sun-brightdesktopmoon --- # Terms of Service & Licensing | SYMMIO Protocol Gitbook [TRADEMARK & COPYRIGHT NOTICEchevron-right](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/trademark-and-copyright-notice) [CONTACT USchevron-right](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/contact-us) [TERMS OF SERVICEchevron-right](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/terms-of-service) [FRONTEND LICENSEchevron-right](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/frontend-license) [CONTRACT LICENSEchevron-right](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/contract-license) [PreviousSherlock Audit - Mar 7, 2025chevron-left](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/staking-and-vesting/sherlock-audit-mar-7-2025) [NextTRADEMARK & COPYRIGHT NOTICEchevron-right](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/trademark-and-copyright-notice) sun-brightdesktopmoon sun-brightdesktopmoon --- # Core Financial Concepts | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/options-protocol-architecture/core-financial-concepts#options-fundamentals) Options Fundamentals ------------------------------------------------------------------------------------------------------------------------------------ Options are derivative contracts that give the buyer the right to buy or sell a specific underlying asset at a predetermined price (the **strike price**) by a specific expiration date. The seller (or **writer**) of the option is obligated to fulfill the contract if the buyer chooses to exercise their right. **Option Types:** * **Call Options**: Grant the right to buy the underlying asset * **Put Options**: Grant the right to sell the underlying asset **Example:** A 100 ETH call option with a $3,000 strike price gives the buyer the right to purchase 100 ETH at $3,000 by expiration. If ETH trades at $4,000 in spot market at expiration, the buyer's profit would be (4,000 - 3,000) × 100 = $100,000. **Example:** A call option on 100 ETH with a $3,000 strike price gives the buyer the right to purchase 100 ETH at $3,000 by the expiration date. If ETH is trading at $4,000 in the spot market at expiration, the buyer’s profit would be: Copy profit = (4,000 - 3,000) × 100 = $100,000 **Option Styles:** * **European Options**: Can only be exercised at expiration (currently supported) * **American Options**: Can be exercised at any time before expiration (not supported yet) ### [hashtag](https://docs.symm.io/options-protocol-architecture/core-financial-concepts#profit-and-loss-pnl-calculation) Profit and Loss (PnL) Calculation PnL is determined by the difference between the settlement (execution) price and the strike price: * **Call Options**: `PnL = (Settlement Price - Strike Price) × Quantity` * **Put Options**: `PnL = (Strike Price - Settlement Price) × Quantity` The protocol automatically settles balances between Party A and Party B based on the calculated PnL. This mechanism eliminates the need to transfer the actual underlying assets. [hashtag](https://docs.symm.io/options-protocol-architecture/core-financial-concepts#collateral-liquidation-and-solvency) Collateral, Liquidation and Solvency ------------------------------------------------------------------------------------------------------------------------------------------------------------------- In options trading, the seller may be incentivized to default on their obligations when facing significant losses. To mitigate this risk, collateral-based mechanisms are used to ensure the seller’s financial commitment. Under this system, the seller is required to maintain a minimum balance of a designated token—referred to as the **collateral token**—as a guarantee. For simplified accounting, **Symmio** uses the same collateral token to pay the option premium. When a party fails to meet collateral requirements, the **liquidation system** is triggered. Symmio implements a comprehensive liquidation mechanism to manage counterparty risk and maintain protocol stability. [hashtag](https://docs.symm.io/options-protocol-architecture/core-financial-concepts#solvency-requirements) Solvency Requirements -------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/options-protocol-architecture/core-financial-concepts#party-b-solvency) **Party B Solvency** Party B must maintain solvency based on the **loss coverage ratio**, which defines the minimum collateral required relative to unrealized losses. * The **loss coverage ratio** sets the collateralization level required for Party B’s unrealized losses. * **Example**: With a 30% loss coverage ratio, Party B must maintain collateral equal to 30% of their unrealized losses. * **Effective UPNL calculation**: `effectiveUpnl = upnl > 0 ? upnl : (upnl * lossCoverage) / 1e18` * **Solvency check**: `balance + (effectiveUpnl * 1e18) / collateralPrice >= 0` ### [hashtag](https://docs.symm.io/options-protocol-architecture/core-financial-concepts#party-a-solvency) **Party A Solvency** Party A is required to maintain sufficient **maintenance margin** when writing (selling) options. * The maintenance margin must cover potential losses from Party A’s short positions. * **Solvency check**: `(balance - totalMM) + (upnl * 1e18) / collateralPrice >= 0` where `totalMM` represents the total maintenance margin across all open positions. [hashtag](https://docs.symm.io/options-protocol-architecture/core-financial-concepts#protocol-participants) Protocol Participants -------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/options-protocol-architecture/core-financial-concepts#party-a-trader-user) Party A (Trader/User) * Initiates trading by creating and sending intents * Can act as buyer or seller of options * Responsible for: * Providing premium payments (when buying) * Maintaining maintenance margin (when selling) * Paying trading and affiliate fees ### [hashtag](https://docs.symm.io/options-protocol-architecture/core-financial-concepts#party-b-liquidity-provider-market-maker) Party B (Liquidity Provider/Market Maker) * Responds to and fulfils trading intents * Provides liquidity by taking opposite positions * Must be whitelisted by Party A to participate * Responsible for maintaining solvency requirements [PreviousOverviewchevron-left](https://docs.symm.io/options-protocol-architecture/overview) [NextTechnical Architecturechevron-right](https://docs.symm.io/options-protocol-architecture/technical-architecture) Last updated 28 days ago * [Options Fundamentals](https://docs.symm.io/options-protocol-architecture/core-financial-concepts#options-fundamentals) * [Profit and Loss (PnL) Calculation](https://docs.symm.io/options-protocol-architecture/core-financial-concepts#profit-and-loss-pnl-calculation) * [Collateral, Liquidation and Solvency](https://docs.symm.io/options-protocol-architecture/core-financial-concepts#collateral-liquidation-and-solvency) * [Solvency Requirements](https://docs.symm.io/options-protocol-architecture/core-financial-concepts#solvency-requirements) * [Party B Solvency](https://docs.symm.io/options-protocol-architecture/core-financial-concepts#party-b-solvency) * [Party A Solvency](https://docs.symm.io/options-protocol-architecture/core-financial-concepts#party-a-solvency) * [Protocol Participants](https://docs.symm.io/options-protocol-architecture/core-financial-concepts#protocol-participants) * [Party A (Trader/User)](https://docs.symm.io/options-protocol-architecture/core-financial-concepts#party-a-trader-user) * [Party B (Liquidity Provider/Market Maker)](https://docs.symm.io/options-protocol-architecture/core-financial-concepts#party-b-liquidity-provider-market-maker) sun-brightdesktopmoon sun-brightdesktopmoon --- # Sherlock Audit -Aug 30, 2023 | SYMMIO Protocol Gitbook [![Logo](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2Faudits.sherlock.xyz%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=87b6773d&sv=2)Symmetrical Update Contest - 27,600 USDCaudits.sherlock.xyzchevron-right](https://audits.sherlock.xyz/contests/108) circle-info Sherlock is an audit marketplace and smart contract coverage protocol built on the Ethereum blockchain. Sherlock works to protect Decentralized Finance (DeFi) users from smart contract exploits with security reviews from top auditors backed by smart contract coverage on the audited contracts. You can find a brief overview of the Sherlock ecosystem below. [https://docs.sherlock.xyz/arrow-up-right](https://docs.sherlock.xyz/) View findings: [https://github.com/sherlock-audit/2023-08-symmetrical-judging/issuesarrow-up-right](https://github.com/sherlock-audit/2023-08-symmetrical-judging/issues) Audit report: [https://audits.sherlock.xyz/contests/108/reportarrow-up-right](https://audits.sherlock.xyz/contests/108/report) [PreviousSYMM - 0.82chevron-left](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-0.82) [NextSYMM - 0.83chevron-right](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-0.83) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Verifying Account Abstracted Instant Actions (ERC-4337) | SYMMIO Protocol Gitbook When using Account Abstraction with ERC-4337, you may need to verify a user’s signature on-chain (EIP-1271). This process allows smart contract wallets to sign off-chain data (via the user’s wallet logic) and then be validated on-chain by calling a contract’s isValidSignature() function. The example below uses: * SIWE (Sign-In with Ethereum) to structure the message (nonce, domain, expiration, etc.). * ERC-4337 style message hashing to produce the correct pre-hashed data. EIP-1271 on-chain validation via a contract call to `isValidSignature()`. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/verifying-account-abstracted-instant-actions-erc-4337#example-code-snippet) Example Code Snippet ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Copy import json from eth_typing import HexStr from eth_utils import keccak, to_bytes, to_hex from siwe import SiweMessage from siwe import siwe from web3 import Web3 RPC = '' web3 = Web3(Web3.HTTPProvider(RPC)) def _encode_erc4337(message: SiweMessage) -> HexStr: data_str = message.prepare_message() print(data_str) hex_message = data_str.encode('utf-8').hex() presign_message_prefix = f'\x19Ethereum Signed Message:\n{len(data_str)}' prefix = presign_message_prefix.encode('utf-8').hex() combined_message = f'0x{prefix}{hex_message}' return to_hex(keccak(to_bytes(hexstr=combined_message))) message_dict = { "account_address": "0x94b1e92397bC7Bc0964e1d6C736277AF27E5a76a", "expiration_time": "2024-12-19T08:09:21.231Z", "issued_at": "2024-12-16T08:09:21.231Z", "signature": "0xf8582d00465b648c7d3f0f06d1ca41553af52bf70e1f21b115c7a18a0f548dd032000319a7947d17575ffba4a358a9e5be4f9302216a41e22ba1f4aa7f5108ac20", "nonce": "1ESHS1N2VcQ" } domain = "vibe-ui-git-hedger-whitelist-link-vibe-tradings-projects.vercel.app" uri = "https://base-hedger82.rasa.capital/login" signature = message_dict['signature'] owner = "0x3Da94BF626065EF31dab46529ea0A69761a01a1e" fields = { "domain": domain, "address": owner, "uri": uri, "version": siwe.VersionEnum.one, "chain_id": "8453", "nonce": message_dict["nonce"], "issued_at": message_dict["issued_at"], "statement": f'msg: {message_dict["account_address"]}', "expiration_time": message_dict["expiration_time"] } siwe_message = SiweMessage(**fields) hash_message = _encode_erc4337(siwe_message) with open('SignerValidatorAbi.json') as f: abi = json.load(f) contract = web3.eth.contract(address=owner, abi=abi) try: magic_value = contract.functions.isValidSignature(hash_message, signature).call() print("Magic Value Returned:", magic_value.hex()) print(magic_value == Web3.to_bytes(hexstr=HexStr('0x1626ba7e'))) except Exception as e: print("Error calling isValidSignature:", e) Below is a breakdown of how this code example verifies Instant Trades in an AA context. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/verifying-account-abstracted-instant-actions-erc-4337#constructing-the-siwe-message) Constructing the SIWE Message ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ * SIWE (Sign-In with Ethereum) is used to define an off-chain message containing: * `domain`: The site or application domain. * `address`: The user’s (or smart wallets) address—this is an EIP-1271 contract in this example. * `nonce` & `issued_at`: Used to prevent replay attacks. * `expiration_time`: Defines how long this signed authorization is valid. * `statement`: here `account_address` is the ERC-4337 compliant wallet * `chain_id`: The chain on which the address is deployed. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/verifying-account-abstracted-instant-actions-erc-4337#encoding-the-message-for-eip-1271-verification) Encoding the Message for EIP-1271 Verification ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1. `message.prepare_message()` gives you the SIWE message as a string. 2. The code applies EIP-191 style prefix: `\x19Ethereum Signed Message:\n`. This is the same prefix typically used in MetaMask or other wallets for “personal\_sign.” 3. The prefixed message is then hashed with `keccak-256`. The resulting `hash_message` becomes the “message hash” that the smart contract will verify. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/verifying-account-abstracted-instant-actions-erc-4337#on-chain-signature-verification) On-Chain Signature Verification ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1. `owner` is not an EOA– it’s an EIP-1271-compatible contract (smart wallet). 2. `isValidSignature(bytes32 _hash, bytes _signature)` is part of EIP-1271. The contract checks internally if the provided signature is valid for \_hash. 3. A valid signature must return `0x1626ba7e` (the EIP-1271 magic value). 4. If the returned value is not `0x1626ba7e`, the signature is invalid. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/verifying-account-abstracted-instant-actions-erc-4337#account-abstracted-flow-verifying-instant-actions) Account Abstracted Flow– Verifying Instant Actions: ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 1. The frontend generates a SIWE message for "instant actions" * E.g., “I authorize solver XYZ to execute opens/closes until expiration\_time.” * The user (or user’s wallet) signs it off-chain, producing a signature. 2. The solver/backend calls `_encode_erc4337(siwe_message)` to construct the same SIWE string and get the `hash_message`. 3. The solver then invokes `isValidSignature(hash_message, signature)` on the user’s smart wallet contract: * Success (`0x1626ba7e`) means the user’s contract acknowledges the signature, so the solver can proceed with “instant actions.” * Failure (any other value or revert) means the signature is invalid or expired. This ensures no new signature is required for every single open/close, provided the user already authorized a “session.” [PreviousFetching Gas Prices Scriptchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script) [NextSolver Error Codeschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/solver-error-codes) Last updated 25 days ago * [Example Code Snippet](https://docs.symm.io/protocol-architecture/documentation-for-solvers/verifying-account-abstracted-instant-actions-erc-4337#example-code-snippet) * [Constructing the SIWE Message](https://docs.symm.io/protocol-architecture/documentation-for-solvers/verifying-account-abstracted-instant-actions-erc-4337#constructing-the-siwe-message) * [Encoding the Message for EIP-1271 Verification](https://docs.symm.io/protocol-architecture/documentation-for-solvers/verifying-account-abstracted-instant-actions-erc-4337#encoding-the-message-for-eip-1271-verification) * [On-Chain Signature Verification](https://docs.symm.io/protocol-architecture/documentation-for-solvers/verifying-account-abstracted-instant-actions-erc-4337#on-chain-signature-verification) * [Account Abstracted Flow– Verifying Instant Actions:](https://docs.symm.io/protocol-architecture/documentation-for-solvers/verifying-account-abstracted-instant-actions-erc-4337#account-abstracted-flow-verifying-instant-actions) sun-brightdesktopmoon Copy fields = { "domain": domain, "address": owner, "uri": uri, "version": siwe.VersionEnum.one, "chain_id": "8453", "nonce": message_dict["nonce"], "issued_at": message_dict["issued_at"], "statement": f'msg: {message_dict["account_address"]}', "expiration_time": message_dict["expiration_time"] } siwe_message = SiweMessage(**fields) Copy def _encode_erc4337(message: SiweMessage) -> HexStr: data_str = message.prepare_message() print(data_str) hex_message = data_str.encode('utf-8').hex() presign_message_prefix = f'\x19Ethereum Signed Message:\n{len(data_str)}' prefix = presign_message_prefix.encode('utf-8').hex() combined_message = f'0x{prefix}{hex_message}' return to_hex(keccak(to_bytes(hexstr=combined_message))) Copy contract = web3.eth.contract(address=owner, abi=abi) magic_value = contract.functions.isValidSignature(hash_message, signature).call() print("Magic Value Returned:", magic_value.hex()) print(magic_value == Web3.to_bytes(hexstr=HexStr('0x1626ba7e'))) sun-brightdesktopmoon --- # CONTRACT LICENSE | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/contract-license#symmio-core-licensing) SYMMIO CORE Licensing ------------------------------------------------------------------------------------------------------------------------------------------------------------- SYMMIO CORE was launched under a Business Source License 1.1 (BUSL 1.1). The license limits use of the SYMMIO contract source code in a commercial or production setting until December 31st, 2027. After this, the license will convert to a GNU General Public License v2.0 or later. This means anyone can fork the code for their own use as long as it is kept open source. Copy Licensor: Symmetry Labs AG. Licensed Work: SYMM Core (v0.8 - v0.89) The Licensed Work is (c) 2023 Symmetry Labs Change Date: 12-31-2027 Change License: GNU General Public License v2.0 or later For information about alternative licensing arrangements for the Software, please visit: https://docs.symm.io/legal-disclaimer/license/additional-license-use-grants Notice License text copyright (c) 2017 MariaDB Corporation Ab, All Rights Reserved. “Business Source License” is a trademark of MariaDB Corporation Ab. ----------------------------------------------------------------------------- Business Source License 1.1 Terms The Licensor hereby grants you the right to copy, modify, create derivative works, redistribute, and make non-production use of the Licensed Work. The Licensor may make an Additional Use Grant, above, permitting limited production use. Effective on the Change Date, or the fourth anniversary of the first publicly available distribution of a specific version of the Licensed Work under this License, whichever comes first, the Licensor hereby grants you rights under the terms of the Change License, and the rights granted in the paragraph above terminate. If your use of the Licensed Work does not comply with the requirements currently in effect as described in this License, you must purchase a commercial license from the Licensor, its affiliated entities, or authorized resellers, or you must refrain from using the Licensed Work. All copies of the original and modified Licensed Work, and derivative works of the Licensed Work, are subject to this License. This License applies separately for each version of the Licensed Work and the Change Date may vary for each version of the Licensed Work released by Licensor. You must conspicuously display this License on each original or modified copy of the Licensed Work. If you receive the Licensed Work in original or modified form from a third party, the terms and conditions set forth in this License apply to your use of that work. Any use of the Licensed Work in violation of this License will automatically terminate your rights under this License for the current and all other versions of the Licensed Work. This License does not grant you any right in any trademark or logo of Licensor or its affiliates (provided that you may use a trademark or logo of Licensor as expressly required by this License). TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON AN "AS IS" BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND TITLE. MariaDB hereby grants you permission to use this License’s text to license your works, and to refer to it using the trademark "Business Source License", as long as you comply with the Covenants of Licensor below. Covenants of Licensor In consideration of the right to use this License’s text and the "Business Source License" name and trademark, Licensor covenants to MariaDB, and to all other recipients of the licensed work to be provided by Licensor: 1. To specify as the Change License the GPL Version 2.0 or any later version, or a license that is compatible with GPL Version 2.0 or a later version, where "compatible" means that software provided under the Change License can be included in a program with software provided under GPL Version 2.0 or a later version. Licensor may specify additional Change Licenses without limitation. 2. To either: (a) specify an additional grant of rights to use that does not impose any additional restriction on the right granted in this License, as the Additional Use Grant; or (b) insert the text "None". 3. To specify a Change Date. 4. Not to modify this License in any other way. ----------------------------------------------------------------------------- Notice The Business Source License (this document, or the "License") is not an Open Source license. However, the Licensed Work will eventually be made available under an Open Source License, as stated in this License. [PreviousFrontend Use Grantschevron-left](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/frontend-license/frontend-use-grants) [NextContract Use Grantschevron-right](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/contract-license/contract-use-grants) Last updated 2 years ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Solver Error Codes | SYMMIO Protocol Gitbook **Code** **Description** **4000** PartyB (Hedger) is unable to Process the Market Order - due to PartyA (Users) Solvency Issue **4001** PartyB (Hedger) is unable to Process the Market Order - due to PartyB (Hedger) Solvency Issue, PartyB (Hedger) MAX OI was reached for this market. **4002** PartyB (Hedger) no longer wants to accept this Quote, because of solvency issues on PartyA (User) side, the Quote is available for any other PartyB (Hedger Pool) to accept it. **4003** PartyB (Hedger) can no longer accept your Quote, because of solvency issues on PartyB (Hedger) side, the Quote is available for any other PartyB (Hedger Pool) to accept it. **4004** PartyB (Hedger) rejected the Close Request: Solvency issue. User might be liquidated already, please contact platform support. **4005** PartyB (Hedger) rejected the Close Request: due to PartyB (Hedger) Solvency issue. please cancel your close request and try again later **4006** PartyB (Hedger) Market Order Placement failed for unknown reasons: Please try again and send a new Market Order quote. **4007** PartyB (Hedger) System experienced an unknown Request Processing Failure, please try again or contact platform support. **4008** PartyB (Hedger) is unable to Process the Market Order - due to PartyB (Hedger) Solvency Issue. please cancel your close request and try again later **4011** Failed due to insolvency **4012** PartyB (Hedger) can't process the requested market order because the order is out of the maximum capacity. **4101** PartyB (Hedger) no longer wants to accept the Quote, for unknown reasons. The Quote is available for any other PartyB (Hedger Pool) to accept it. **4103** The force close event has happened before close request. **4104** PartyB (Hedger) is unable to Process the Open request - due to market movements. The Quote is available for any other PartyB (Hedger Pool) to accept it. **4105** PartyB (Hedger) values for minimum or maximum CVA, MM or Liquidation Fee, price or notional etc. requirements are not met, please send a new quote. **4107** PartyB (Hedger) values for CVA, MM or Liquidation Fee requirements are not met, please send a new quote. **4108** PartyB (Hedger) is unable to Process the action - PartyB (Hedger) MAX OI was reached for this market. **4109** PartyB (Hedger) does not accept this action because of solvency issues on PartyA (User) side. Account Health too low. **4110** PartyB (Hedger) does not accept this action because of solvency issues on PartyA (User) side. **4111** PartyB (Hedger) is unable to Process the Open request - due to PartyB (Hedger) solvency issues. **4112** PartyB (Hedger) is unable to Process the Open request - PartyB (hedger) should rebalance their margin, they will potentially open the position soon. **4113** PartyB (Hedger) is unable to Process the Open request - for technical reasons. The Quote is available for any other PartyB (Hedger Pool) to accept it. **4114** PartyB (Hedger) is unable to Process the Open request - price is too far from last market price. The Quote is available for any other PartyB (Hedger Pool) to accept it. **4116** PartyB (Hedger) is unable to Process the Open request - The max notional capacity has been reached. The Quote is available for any other PartyB (Hedger Pool) to accept it. **4117** PartyB (Hedger) is unable to Process the Open request - hedger cannot accept more open requests at this time. The Quote is available for any other PartyB (Hedger Pool) to accept it. **4118** PartyB (Hedger) request time requirements are not sufficient, please send a new request with more time to process. **4119** PartyB (Hedger) requirements to close are not sufficient, remaining minimum amount is too low, please send a new request. **4120** PartyB (Hedger) System experienced an unknown Request Processing Failure, please try again or contact platform support. **4123** PartyB (Hedger) is unable to Process the Close request, please contact platform support. **4124** PartyB (Hedger) is unable to Process the Close request - price is too far from last market price. **4125** User has been liquidated. **4126** Quote rejected: Our estimation indicates the locked value may drop below acceptable levels upon opening. **4129** User Suspended. **4130** Not enough allocated balance for close request. Please close other positions or top up your account. **4131** Due to the fill price, the locked value has fallen below acceptable levels. The intent has been unlocked. **4132** Invalid max funding rate. **4133** Invalid party\_b\_mm. **4134** Already applied. **4135** Has inner liquidation. **4136** Inner liquidation conditions failed. **4201** PartyB (Hedger) requested decimal or precision values are not sufficient, please send a new order in which price or received value has fewer decimals. **4202** PartyB (Hedger) is unable to process this Request - due to PartyA (Users) Solvency Issue **4203** PartyB (Hedger) System experienced an unknown Request Processing Failure, please try again or contact platform support. **4204** PartyB (Hedger) experienced a Request Processing Failure because the chain is too congested at the moment, please try again or contact platform support. **4205** PartyB (Hedger) System experienced an unknown Request Processing Failure, please try again or contact platform support. **4206** PartyB (Hedger) System experienced an unknown Request Processing Failure, please try again or contact platform support. **4207** PartyB (Hedger) System experienced an unknown Request Processing Failure, please try again or contact platform support. **4208** Max retry for fill close exceeded, cancel your close request. **4210** PartyB (Hedger) system experienced failure in filling limit order - due to partyA (User) solvency issue. **4302** PartyB (Hedger) is unable to process this Request - the requested Market or Symbol is not available. **4303** PartyB (Hedger) is unable to process this Request - due to PartyA (Users) not being Whitelisted or being Blacklisted. **4304** PartyB (Hedger) System experienced an unknown Request Processing Failure, please try again or contact platform support. **4309** Redundant-muon-failure **4311** Redundant-solvency-on-limit-order **4403** Liquidation already handled. **4501** PartyB (Hedger) System experienced an unknown Request Processing Failure, please try again or contact platform support. [PreviousVerifying Account Abstracted Instant Actions (ERC-4337)chevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/verifying-account-abstracted-instant-actions-erc-4337) [NextDocumentation for Investorschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-investors) Last updated 25 days ago sun-brightdesktopmoon sun-brightdesktopmoon --- # SymmioPartyA | SYMMIO Protocol Gitbook The `SymmioPartyA` contract serves as a proxy for users to interact with the Symmio platform via their respective sub-accounts. Each sub-account, represented by an instance of `SymmioPartyA`, can forward calls to the Symmio diamond. Here's a detailed breakdown of the functionalities and features provided by this contract: [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/multiaccount-0.8.4/symmiopartya#constructor) **Constructor** --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Initializes a new `SymmioPartyA` contract with specific roles and addresses. Copy constructor(address admin, address multiAccountAddress, address symmioAddress_) { _grantRole(DEFAULT_ADMIN_ROLE, admin); _grantRole(MULTIACCOUNT_ROLE, multiAccountAddress); symmioAddress = symmioAddress_; } * **Parameters**: * `admin`: The administrator of the contract who is granted the `DEFAULT_ADMIN_ROLE`. * `multiAccountAddress`: The address of the `MultiAccount` contract, granted the `MULTIACCOUNT_ROLE` to allow it to make calls on behalf of the sub-account. * `symmioAddress_`: The initial address of the Symmio platform contract to which all calls will be forwarded. * **Operations**: * Grants `DEFAULT_ADMIN_ROLE` to `admin`. * Grants `MULTIACCOUNT_ROLE` to `multiAccountAddress`. * Sets the initial Symmio platform address (this is the Diamond). ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/multiaccount-0.8.4/symmiopartya#setsymmioaddress) **setSymmioAddress()** Updates the address of the Symmio platform contract. Only an account with `DEFAULT_ADMIN_ROLE` can invoke this function. **Parameters**: * `symmioAddress_`: The new address of the Symmio platform. **Operations**: * Emits a `SetSymmioAddress` event containing the old and new addresses. * Updates the `symmioAddress` state variable. **Events**: [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/multiaccount-0.8.4/symmiopartya#call) **\_call()** ----------------------------------------------------------------------------------------------------------------------------------------------------------------- Forwards calls from the `SymmioPartyA` contract to the Symmio platform. This method is crucial for interacting with the Symmio functionalities through sub-accounts. Only an account with `MULTIACCOUNT_ROLE` can invoke this function, meaning only the `MultiAccount` contract can direct actions. **Parameters**: * `_callData`: The bytecode of the function call to be forwarded to the Symmio platform. **Returns**: * `_success`: A boolean indicating whether the call was successful. * `_resultData`: The data returned from the call if successful, or error information if the call failed. [PreviousMultiAccount (0.8.4)chevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/multiaccount-0.8.4) [NextSymmioPartyBchevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/multiaccount-0.8.4/symmiopartyb) Last updated 11 months ago * [Constructor](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/multiaccount-0.8.4/symmiopartya#constructor) * [setSymmioAddress()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/multiaccount-0.8.4/symmiopartya#setsymmioaddress) * [\_call()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/multiaccount-0.8.4/symmiopartya#call) sun-brightdesktopmoon Copy function setSymmioAddress(address symmioAddress_) external onlyRole(DEFAULT_ADMIN_ROLE) { emit SetSymmioAddress(symmioAddress, symmioAddress_); symmioAddress = symmioAddress_; } Copy event SetSymmioAddress(address oldV3ContractAddress, address newV3ContractAddress); Copy function _call(bytes memory _callData) external onlyRole(MULTIACCOUNT_ROLE) returns (bool _success, bytes memory _resultData) { return symmioAddress.call{ value: 0 }(_callData); } sun-brightdesktopmoon --- # Main Flow (0.8.4) | SYMMIO Protocol Gitbook This section describes the sequential steps required for initiating and managing trading operations in the 0.8.4 codebase. It covers the process from depositing collateral to opening and closing positions. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/main-flow-0.8.4#deposit) Deposit To begin sending and accepting INTENTs, users must first deposit collateral into the Symmio contracts. This collateral is the foundation for all subsequent trading actions. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/main-flow-0.8.4#allocate) Allocate After depositing collateral, funds are not immediately tradable. Users must **allocate** the deposited collateral to a subaccount. * **Purpose of Subaccounts:** Subaccounts isolate trading instances, ensuring that all PartyA and PartyB interactions remain economically sound. All collateral within a subaccount is cross-collateralized across any open positions. * **Isolated Positions:** To create an isolated position, a separate subaccount must be established. This mechanism also paves the way for future enhancements—such as allocating collateral to specific contract instances with custom code developed by PartyA or PartyB. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/main-flow-0.8.4#send-quote-send-intent) Send Quote (Send INTENT) To initiate a trade, the user sends a quote (or INTENT) by specifying trade criteria such as the symbol and price. This is achieved by calling the `sendQuote` function. > **Note:** Sending a quote is the first step in the trading process and signals the start of a potential position. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/main-flow-0.8.4#party-b-sees-the-position-request) Party B Sees the Position Request Once the quote is sent, PartyB receives the position request and can choose to respond as follows: 1. **Lock the Quote:** PartyB calls `lockQuote` to reserve the quote. This prevents other PartyB users from accepting the same quote until it is unlocked. 2. **Open the Position:** After reserving the quote, PartyB finalizes the trade by invoking the `openPosition` function. > **Training Wheel Feature:** Reserving quotes simplifies the response process for MarketMakers. It allows them to reserve a quote, perform necessary hedging operations, and then fulfill the quote. This feature may be subject to removal in future versions. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/main-flow-0.8.4#cancel-quote) Cancel Quote Users can cancel their quote (INTENT) before the position is fully opened: * **Immediate Cancellation:** If the quote is not locked (reserved), it is canceled immediately. * **Conditional Cancellation:** If the quote is locked but not yet fully opened, cancellation depends on the fill status: * **Partially Filled:** The unfilled portion is canceled, while any partially filled amount remains active. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/main-flow-0.8.4#open-position) Open Position Provided that the quote has been successfully locked (reserved) and no issues have arisen, PartyB completes the process by calling `openPosition` to open the position. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/main-flow-0.8.4#close-request) Close Request PartyA (the user) can request to close an open position at any time by calling `requestToClosePosition`. > **Important:** Only PartyA is authorized to request the closure of a position. PartyB does not have this capability unless the PartyA explicitly authorizes. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/main-flow-0.8.4#cancel-close-request) Cancel Close Request If the user wishes to cancel a close request—either before it is completely filled or to modify a limit order—the process is as follows: * **Unfilled Request:** The close request is canceled immediately, reverting the position status from “close pending” back to a regular active position. * **Partially Filled Request:** The portion of the position that has been filled remains closed. The unfilled portion is re-opened and added back to the existing position. [PreviousContracts Documentation 0.8.4chevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4) [NextThe SYMM Diamond (0.8.4)chevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/the-symm-diamond-0.8.4) Last updated 29 days ago * [Deposit](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/main-flow-0.8.4#deposit) * [Allocate](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/main-flow-0.8.4#allocate) * [Send Quote (Send INTENT)](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/main-flow-0.8.4#send-quote-send-intent) * [Party B Sees the Position Request](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/main-flow-0.8.4#party-b-sees-the-position-request) * [Cancel Quote](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/main-flow-0.8.4#cancel-quote) * [Open Position](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/main-flow-0.8.4#open-position) * [Close Request](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/main-flow-0.8.4#close-request) * [Cancel Close Request](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/main-flow-0.8.4#cancel-close-request) sun-brightdesktopmoon sun-brightdesktopmoon --- # Facets | SYMMIO Protocol Gitbook Facets are an essential component of the Diamond architecture, allowing functions to execute logic on the Diamond’s storage. Each facet contract is paired with an associated implementation contract that encapsulates the logic component of the facet. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets#overview) Overview Facets serve as modular units within the Diamond architecture. Their design allows for isolated updates to specific areas of the system without necessitating a full redeployment of the contract. This modularity is key to maintaining system flexibility and ensuring that enhancements can be applied with minimal disruption. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets#functionality-and-implementation) Functionality and Implementation Each facet is responsible for managing a distinct segment of the system’s functionality. The corresponding implementation contract handles the logic, ensuring that: * Facets can adjust the Diamond’s storage in a targeted manner. * Isolated updates are made possible, reducing the risk of widespread system impact during modifications. * The separation of logic and storage responsibilities streamlines both development and troubleshooting. The following sections will delve into the specifics of SYMM’s facet contracts, outlining the functions within each and how they interact with the Diamond’s core architecture. * * * [PreviousThe SYMM Diamond (0.8.4)chevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/the-symm-diamond-0.8.4) [NextAccount Facet (0.8.4)chevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/account-facet-0.8.4) Last updated 29 days ago * [Overview](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets#overview) * [Functionality and Implementation](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets#functionality-and-implementation) sun-brightdesktopmoon sun-brightdesktopmoon --- # BSC | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/bsc#contract-addresses) Contract Addresses ----------------------------------------------------------------------------------------------------------------------- Name Address Diamond 0x76bc5889c0cfcC20960b0D81F541595d81a95122 AccountFacet 0x1A4Fc51fC65A1d3992F93489b641adC01419e05f DiamondCutFacet 0xF91382e6d8359AECA46A81f105994A4171739c7C ControlFacet 0x169953c5682Ae0d89d8aFE0AD20869B3F4ae452f DiamondLoupeFacet 0x7195D6CF49af88a1b35eDa28207e9147ecb2323D LiquidationFacet 0x4d00aD99D906a015559FBc3279251b7A6CD5698F PartyAFacet 0x760C1C617F89dC74C429d0A62D2f1C2959B110f8 PartyBFacet 0x9c8Fe710b6Ef853AbCE27Ae05A3ecb3B00aa2653 ViewFacet 0x2e0D2F6D6f3F4B9f911e6ae286Fd890fA1D82737 FundingRateFacet 0x8D4e3ed16C28eC18fbf32C3B7d07f0a971925c1C BridgeFacet 0x8cAE94D47d92f8ba0E7b0bD0653428421473d43d [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/bsc#affiliate-addresses) Affiliate Addresses ------------------------------------------------------------------------------------------------------------------------- [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/bsc#alpha-thena) Alpha Thena --------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/bsc#multiaccount) MultiAccount `0x650a2D6C263A93cFF5EdD41f836ce832F05A1cF3` ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/bsc#fee-collector) Fee Collector `0xD889bf3Ca766038d54BC1129171fB76D62ea140f` [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/bsc#cloverfield) Cloverfield --------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/bsc#multiaccount-1) MultiAccount `0xcCc8CC82868B94Bc2759c69375fC7Ae769703EB8` ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/bsc#fee-collector-1) Fee Collector `0xcd97db5818B2dA73C9D28c04BBC4477e3f5355f1` [PreviousBasechevron-left](https://docs.symm.io/protocol-architecture/contract-addresses/base) [NextArbitrumchevron-right](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum) Last updated 2 months ago * [Contract Addresses](https://docs.symm.io/protocol-architecture/contract-addresses/bsc#contract-addresses) * [Affiliate Addresses](https://docs.symm.io/protocol-architecture/contract-addresses/bsc#affiliate-addresses) * [Alpha Thena](https://docs.symm.io/protocol-architecture/contract-addresses/bsc#alpha-thena) * [MultiAccount](https://docs.symm.io/protocol-architecture/contract-addresses/bsc#multiaccount) * [Fee Collector](https://docs.symm.io/protocol-architecture/contract-addresses/bsc#fee-collector) * [Cloverfield](https://docs.symm.io/protocol-architecture/contract-addresses/bsc#cloverfield) * [MultiAccount](https://docs.symm.io/protocol-architecture/contract-addresses/bsc#multiaccount-1) * [Fee Collector](https://docs.symm.io/protocol-architecture/contract-addresses/bsc#fee-collector-1) sun-brightdesktopmoon sun-brightdesktopmoon --- # CONTACT US | SYMMIO Protocol Gitbook [\[email protected\]](https://docs.symm.io/cdn-cgi/l/email-protection) [PreviousTRADEMARK & COPYRIGHT NOTICEchevron-left](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/trademark-and-copyright-notice) [NextTERMS OF SERVICEchevron-right](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/terms-of-service) Last updated 10 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Sonic | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/sonic#contract-addresses) Contract Addresses ------------------------------------------------------------------------------------------------------------------------- Name Address Diamond 0x803de354cbd853D9aE3BC58131A5D538DE7a72E3 AccountFacet 0x5b5C7B6494EC52D9316a7f578eF3FbBBAA53BE63 DiamondCutFacet 0x50E88C692B137B8a51b6017026Ef414651e0d5ba ControlFacet 0xe6a62Ca9dA02F43978aD726907ba26558509259D DiamondLoupeFacet 0x01E822AAe6D2cc456804CCd36aA4d3830dbc6e3b LiquidationFacet 0xc258535aaF6ad3cEd5D2E03e2B66C35262488309 PartyAFacet 0x0392e9CF758CD1566dab547fDAF3DDcfEd1d7375 PartyBQuoteActionsFacet 0x0188b538fAf03c695f154a6E324513453faFB8a1 PartyBPositionActionsFacet 0xc4Bae634C692078a97BEb7b0B583D16B13359Fcf PartyBGroupActionsFacet 0x8768Ff7d7E1FF95a583159D573fd1708Dd6C7001 ViewFacet 0x1347A83D1eb2121B15f944B21Ddbe22ebf8Cf8d1 FundingRateFacet 0x5b5C7B6494EC52D9316a7f578eF3FbBBAA53BE63 BridgeFacet 0x6273242a7E88b3De90822b31648C212215caaFE4 **SettlementFacet** 0x1037b57F7496D10d72F81446bA52Fee7D8C8EAD7 **ForceActrionsFacet** 0x44ca93531be2872a1E6e9987BC8f2d62C0864676 [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/sonic#affiliate-addresses) Affiliate Addresses --------------------------------------------------------------------------------------------------------------------------- [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/sonic#spookyswap) SpookySwap --------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/sonic#multiaccount) MultiAccount `0xd90ACA50eE8Cb7C3dD1fEe84A722d574186cdd17` ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/sonic#fee-collector) Fee Collector `0x61662eA0EeecAf693538284d4332ec6F2828f5F4` [PreviousCotichevron-left](https://docs.symm.io/protocol-architecture/contract-addresses/coti) [NextSolver Addresses & Endpointschevron-right](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints) Last updated 2 months ago * [Contract Addresses](https://docs.symm.io/protocol-architecture/contract-addresses/sonic#contract-addresses) * [Affiliate Addresses](https://docs.symm.io/protocol-architecture/contract-addresses/sonic#affiliate-addresses) * [SpookySwap](https://docs.symm.io/protocol-architecture/contract-addresses/sonic#spookyswap) * [MultiAccount](https://docs.symm.io/protocol-architecture/contract-addresses/sonic#multiaccount) * [Fee Collector](https://docs.symm.io/protocol-architecture/contract-addresses/sonic#fee-collector) sun-brightdesktopmoon sun-brightdesktopmoon --- # Arbitrum | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#contract-addresses) Contract Addresses ---------------------------------------------------------------------------------------------------------------------------- Name Address Diamond 0x76bc5889c0cfcC20960b0D81F541595d81a95122 AccountFacet 0x356Ecc2F034ebd5dEF88D0e2F371222e0dda19A1 DiamondCutFacet 0xF39352ec34A007B2726e2c4610A13F7aEA86684E ControlFacet 0x91834F84d768716F94d75eC40FA2775fA84C634D DiamondLoupeFacet 0x5044238ea045585C704dC2C6387D66d29eD56648 LiquidationFacet 0xD8B5F48cD465Eb7d3eFa7BdEeE99caaAEdFE0d57 PartyAFacet 0x87a1F9fF86d6dD411e333a3c0cA09a234C965168 PartyBFacet 0xcCCDA5C17dbdb6F786F432239887d6d51B4B9aD8 ViewFacet 0x67d3BBBf68eb9Ba032aE65552643Fc20461B9054 FundingRateFacet 0x5d51e783487a65C49c091b6B6D4aE36bD612c079 BridgeFacet 0x5485Af25f0E978Ce914b01a92F6f1897d47a5660 [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#affiliate-addresses) Affiliate Addresses ------------------------------------------------------------------------------------------------------------------------------ [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#pear) Pear ------------------------------------------------------------------------------------------------ ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#multiaccount) MultiAccount `0x6273242a7E88b3De90822b31648C212215caaFE4` ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#fee-collector) Fee Collector `0x96AF9f2893F1fd79fa039ECb56c4B47425c8f74B` [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#vibe) Vibe ------------------------------------------------------------------------------------------------ ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#multiaccount-1) MultiAccount `0x3334226b27FCdda639620eE10c4dfca30f084969` ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#fee-collector-1) Fee Collector `0xAF2AbcaBDE3d965354868385B6C657c27267989A` [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#intentx) IntentX ------------------------------------------------------------------------------------------------------ ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#multiaccount-2) MultiAccount `0x141269E29a770644C34e05B127AB621511f20109` ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#fee-collector-2) Fee Collector `0x0532C5008A9214e669c41CE782C0E64095e6fb22` [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#horizon) Horizon ------------------------------------------------------------------------------------------------------ ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#multiaccount-3) MultiAccount `0x263A8220e9351c5d0cC13567Db4d7BF58e7470c6` ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#fee-collector-3) Fee Collector `0x94054634E2F54C753187F204d7803B25FC2375b5` [PreviousBSCchevron-left](https://docs.symm.io/protocol-architecture/contract-addresses/bsc) [NextPolygonchevron-right](https://docs.symm.io/protocol-architecture/contract-addresses/polygon) Last updated 2 months ago * [Contract Addresses](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#contract-addresses) * [Affiliate Addresses](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#affiliate-addresses) * [Pear](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#pear) * [MultiAccount](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#multiaccount) * [Fee Collector](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#fee-collector) * [Vibe](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#vibe) * [MultiAccount](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#multiaccount-1) * [Fee Collector](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#fee-collector-1) * [IntentX](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#intentx) * [MultiAccount](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#multiaccount-2) * [Fee Collector](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#fee-collector-2) * [Horizon](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#horizon) * [MultiAccount](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#multiaccount-3) * [Fee Collector](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum#fee-collector-3) sun-brightdesktopmoon sun-brightdesktopmoon --- # TRADEMARK & COPYRIGHT NOTICE | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/trademark-and-copyright-notice#copyright-notice) Copyright Notice ----------------------------------------------------------------------------------------------------------------------------------------------------------------- The Symmio Entities (collectively referring to Symmio Foundation. & subsidiaries, duly incorporated and registered in the Cayman Islands and its affiliates, subsidiaries, and any related entities) own, operate, and provide access to the website [www.symm.ioarrow-up-right](http://www.symm.io/) (the "Website"), the Symmio platform (the "Platform"), and all associated services (collectively, the "Services"), including but not limited to software applications, features, tools, and any other functionalities made available by the Symmio Entities. All design elements, concepts, and underlying intellectual property related to the Website, Platform, and Services—including copyrights, patents, service marks, trademarks (registered or unregistered), domain names, and other proprietary rights—are the exclusive property of the Symmio Entities and are protected under applicable copyright, patent, trade secret, and other intellectual property laws. The Symmio trademark has been extensively used by the Symmio Entities in the cryptocurrency sector, establishing a strong reputation and goodwill as a well-known brand. The distinctive triangle symbol, an integral part of the Symmio identity, is not only a registered trademark but also an original creation protected under copyright law. Unless explicitly stated otherwise, the Symmio Entities retain all intellectual property rights, title, and interest in any content, materials, ideas, and any other intellectual property made available through the Website, Platform, and Services—including all copies, modifications, extensions, and derivative works. Unauthorized use of any materials from the Website is strictly prohibited. Any new content, updates, or modifications added to the Website will remain the exclusive property of the Symmio Entities. The use of such newly added materials is also prohibited unless explicit written consent is granted by the Symmio Entities. Your right to use the Website, Platform, and Services is strictly limited to the rights expressly granted under these Terms. No licenses or rights to use any trademarks or other intellectual property of the Symmio Entities are granted or implied through the use of the Services. All rights not expressly granted to you remain exclusively reserved by the Symmio Entities. [PreviousTerms of Service & Licensingchevron-left](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing) [NextCONTACT USchevron-right](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/contact-us) Last updated 10 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Polygon | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/polygon#contract-addresses) Contract Addresses --------------------------------------------------------------------------------------------------------------------------- Name Address Diamond **0x976c87Cd3eB2DE462Db249cCA711E4C89154537b** AccountFacet 0xA90b7EDcC470D3e060936eE2b84A8b3A14FA91c8 DiamondCutFacet 0x12FEd7daa1375a96BEe0e0d291cBC18CB82D2Ec6 ControlFacet 0x1f3451d5Ab2810c3739ECF5A16A002bb9f595039 DiamondLoupeFacet 0x50658F52C4d89AE515DaA2cfc503f5E932Fca89D LiquidationFacet 0x599F39e38c09Ed1Ccbb57eE1Cdc7F9A5ecdcc730 PartyAFacet 0x9fa01a45E245015fA685F21763e60C60832Ed2D6 PartyBQuoteActionsFacet 0xAF12970D90fD3d7Bf90EDA281B7a741FE5FE5f8a PartyBGroupActionsFacet 0xD867279E076c43235dAcB06672c20968e620cCA2 ViewFacet 0x650a2D6C263A93cFF5EdD41f836ce832F05A1cF3 FundingRateFacet 0xe0274E79ed451f27dD5cBb4c83A8eEA62c6A6508 BridgeFacet 0xD41B668F3eaC456d145218E53b67EadE1E66a2B3 SettlementFacet 0xD3102Dc287D24B20eC34D8d68a5d617318F6f9Ef [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/polygon#affiliate-addresses) Affiliate Addresses ----------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/polygon#cloverfield) Cloverfield `0xffE2C25404525D2D4351D75177B92F18D9DaF4Af` [PreviousArbitrumchevron-left](https://docs.symm.io/protocol-architecture/contract-addresses/arbitrum) [NextBerachainchevron-right](https://docs.symm.io/protocol-architecture/contract-addresses/berachain) Last updated 2 months ago * [Contract Addresses](https://docs.symm.io/protocol-architecture/contract-addresses/polygon#contract-addresses) * [Affiliate Addresses](https://docs.symm.io/protocol-architecture/contract-addresses/polygon#affiliate-addresses) * [Cloverfield](https://docs.symm.io/protocol-architecture/contract-addresses/polygon#cloverfield) sun-brightdesktopmoon sun-brightdesktopmoon --- # Contract Use Grants | SYMMIO Protocol Gitbook The Licensor hereby grants these projects, with the respective domain addresses the right to copy, modify, create derivative works, redistribute, and make production use of the MultiAccount.sol isolated to this one file. [https://github.com/SYMM-IO/symmio-core/blob/main/contracts/multiAccount/MultiAccount.solarrow-up-right](https://github.com/SYMM-IO/symmio-core/blob/main/contracts/multiAccount/MultiAccount.sol) Thena project by [https://thena.fi arrow-up-right](https://thena.fi/) [PreviousCONTRACT LICENSEchevron-left](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/contract-license) [NextContract Modificationschevron-right](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/contract-license/contract-modifications) Last updated 2 years ago sun-brightdesktopmoon sun-brightdesktopmoon --- # How to contact ? | SYMMIO Protocol Gitbook Via Sherlock Bug Bounty: [https://audits.sherlock.xyz/bug-bounties/5?t=detailsarrow-up-right](https://audits.sherlock.xyz/bug-bounties/5?t=details) Via email: [\[email protected\]](https://docs.symm.io/cdn-cgi/l/email-protection) [PreviousBug bounty / Coveragechevron-left](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/bug-bounty-coverage) [NextAuditschevron-right](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Creating the APIs | SYMMIO Protocol Gitbook As a Solver integrating with SYMMIO, you’ll need to include **REST APIs**, to allow frontends to display data like available symbols, retrieving open interest and notional caps. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis#rest-apis) REST APIs ------------------------------------------------------------------------------------------------------------------------------------------------------ Detailed documentation about REST API endpoint queries and returned data can be found in the following section. It's recommended that solvers follow the same structure in their endpoints to integrate with frontends easily. The full list of endpoints that solvers can integrate is here, however not all are essential for an implementation. Essential endpoints are listed below: ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis#get-contract-symbols-contract-symbols) [**GET Contract Symbols: /contract-symbols**](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-contract-symbols) ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis#get-open-interest-open-interest) [**GET Open Interest: /open-interest**](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-open-interest) ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis#get-notional-cap-by-symbol-notional_cap-symbol_id) [**GET Notional Cap by Symbol: /notional\_cap/{symbol\_id}**](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-notional-cap) ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis#get-price-range-by-symbol-price-range-symbol) [**GET Price Range by Symbol: /price-range/{symbol}**](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-price-range) ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis#get-locked-parameters-for-a-symbol-get_locked_params-symbol-leverage-leverage) [**GET Locked Parameters for a Symbol: /get\_locked\_params/{symbol}?leverage={leverage}**](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-get-locked-params) ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis#get-funding-information-get_funding_info) [**GET Funding Information: /get\_funding\_info**](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-get-funding-info) ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis#get-error-codes-error_codes) [**GET Error Codes: /error\_codes**](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-error-codes) ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis#post-position-information-position_state-less-than-offset-greater-than-less-than-size-greater-than) [**POST Position Information: /position\_state//**](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/post-position-state) [Previous4\. Opening/Closing a Position On-Chainchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/4.-opening-closing-a-position-on-chain) [NextGET Contract Symbolschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-contract-symbols) Last updated 1 month ago * [REST APIs](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis#rest-apis) * [GET Contract Symbols: /contract-symbols](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis#get-contract-symbols-contract-symbols) * [GET Open Interest: /open-interest](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis#get-open-interest-open-interest) * [GET Notional Cap by Symbol: /notional\_cap/{symbol\_id}](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis#get-notional-cap-by-symbol-notional_cap-symbol_id) * [GET Price Range by Symbol: /price-range/{symbol}](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis#get-price-range-by-symbol-price-range-symbol) * [GET Locked Parameters for a Symbol: /get\_locked\_params/{symbol}?leverage={leverage}](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis#get-locked-parameters-for-a-symbol-get_locked_params-symbol-leverage-leverage) * [GET Funding Information: /get\_funding\_info](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis#get-funding-information-get_funding_info) * [GET Error Codes: /error\_codes](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis#get-error-codes-error_codes) * [POST Position Information: /position\_state//](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis#post-position-information-position_state-less-than-offset-greater-than-less-than-size-greater-than) sun-brightdesktopmoon sun-brightdesktopmoon --- # 2. Seeing the Intent | SYMMIO Protocol Gitbook To build a robust hedging service in the SYMMIO ecosystem, it's crucial for hedgers (PartyB) to monitor blockchain events triggered by PartyA's intents. This section shows a basic implementation of an event listener using `ethers.js` or `web3.py`. ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FN8CrEXQcmvR9tESdFikK%252FSolver.png%3Falt%3Dmedia%26token%3D9043157a-e13e-4244-b414-ea8fe057fb6c&width=768&dpr=3&quality=100&sign=4ba84dbb&sv=2) ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/2.-seeing-the-intent#web3eventpoller) Web3EventPoller The `Web3EventPoller` class is a high-level utility designed to: 1. **Connect to the Blockchain**: Establish a connection to the blockchain network using `web3.py`. 2. **Load Contract and ABI**: Use the contract's address and ABI to interact with its events. 3. **Monitor Events**: Listen for specific on-chain events such as `SendQuote` or `ForceCancelQuote`. 4. **Handle Events**: Delegate event handling to predefined handler classes (e.g., `SendQuoteHandler`). 5. **Maintain State**: Use an `EventPoller` instance to manage event polling, handle retries, and ensure no events are missed. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/2.-seeing-the-intent#event-poller-internals) Event Poller Internals `EventPoller`: A utility script that tracks from\_block progress (often persisted in something like Redis) and polls in intervals (poll\_interval). ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/2.-seeing-the-intent#send-quote-handler) Send Quote Handler The `SendQuoteHandler` processes `SendQuote` events from PartyA. It should validate the event data (e.g., whitelist checks, quote status) and construct and stores a structured payload in Redis for further use by the system. **Extract Event Data and Block Information** * Retrieves the event arguments (`args`) and the blockchain block details (`block`). **Fetch Additional Data for the Symbol and Quote** * Fetches detailed information about the symbol and quote using their IDs. * Maps the raw blockchain data into structured fields for easier access. **Check If the Quote Is Already Processed** Checks the status of the quote. If it has already been processed (status 3), the handler exits early. **Validate PartyB Whitelist** Confirms that the current hedger (PartyB) is authorized to act on this quote. If a whitelist exists and the hedger is not included, the handler skips processing. **Constructing the Payload** Creates a structured dictionary containing all relevant event and blockchain data. This includes trade details (e.g., `quoteId`, `price`), contextual metadata (e.g., `blockNumber`), and hedger-specific information (e.g., `partyBmm`). **Generate a Unique Key for Redis** Ensures that each event is uniquely identified to avoid duplication in the Redis store. **Logging the Event** Logs the event processing for debugging and traceability. **Store the Event Data in Redis** Stores the payload in Redis using the unique key. The `setnx` method ensures that the event is only stored if the key does not already exist. [Previous1\. Intent Creationchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/1.-intent-creation) [Next3\. Hedging Off-Chainchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/3.-hedging-off-chain) Last updated 25 days ago * [Web3EventPoller](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/2.-seeing-the-intent#web3eventpoller) * [Event Poller Internals](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/2.-seeing-the-intent#event-poller-internals) * [Send Quote Handler](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/2.-seeing-the-intent#send-quote-handler) sun-brightdesktopmoon Copy from web3 import Web3 from web3.middleware import geth_poa_middleware import logging from settings import RPC, ContractAddress, PollInterval, FromBlock from event_poller import EventPoller from handlers.send_request_handler import SendQuoteHandler class Web3EventPoller: @staticmethod def run(): # 1. Initialize Web3 and contract w3_instance = Web3(Web3.HTTPProvider(RPC)) w3_instance.middleware_onion.inject(geth_poa_middleware, layer=0) contract_abi = [...] # Loaded from a JSON file contract = w3_instance.eth.contract(address=ContractAddress, abi=contract_abi) # 2. Create a poller instance poller = EventPoller( context=..., from_block=FromBlock, poll_interval=PollInterval ) # 3. Register event + handler poller.add_event("SendQuote", SendQuoteHandler().handle) # ... add other events as needed ... # 4. Start the poller poller.start() poller.wait() Copy class EventPoller: def __init__(self, context, from_block=0, poll_interval=10, block_chunk_size=10000): # 1. Initialize context, default block, and interval settings. # 2. Create data structures to track events and their states. # 3. Set up a thread pool executor for concurrent event polling. self.context = context self.tracked_events = {} self.poll_interval = poll_interval self.block_chunk_size = block_chunk_size self.stop_signal = False self.default_from_block = from_block self.futures = {} self.event_from_blocks = {} self.executor = ThreadPoolExecutor() def add_event(self, event_name, callback=None): # 1. Register the event name and callback in `tracked_events`. # 2. Check Redis for the last processed block for the event. # 3. Set `from_block` for the event based on Redis or the default value. self.tracked_events[event_name] = callback stored_from_block = REDIS_SERVER.get("event_poller_from_block_" + event_name) self.event_from_blocks[event_name] = int( stored_from_block) if stored_from_block is not None else self.default_from_block def remove_event(self, event_name): # 1. Remove the event and its block tracking state. # 2. Stop the associated polling thread if it's running. if event_name in self.tracked_events: del self.tracked_events[event_name] del self.event_from_blocks[event_name] self.stop_event_thread(event_name) def _fetch_event(self, event_name, callback, from_block, to_block): # 1. Retrieve the event object from the contract. # 2. Create a filter for logs between `from_block` and `to_block`. # 3. Fetch all logs and update the last processed block in Redis. # 4. Invoke the callback for each log if provided. event = getattr(self.context.contract.events, event_name) event_filter = event.create_filter(fromBlock=from_block, toBlock=to_block) events = event_filter.get_all_entries() REDIS_SERVER.set_permanent("event_poller_from_block_" + event_name, to_block) self.event_from_blocks[event_name] = int(to_block) + 1 if callback: for ev in events: callback(self.context, ev) return events def _run_event(self, event_name, callback): # 1. Poll the blockchain to get the current block number. # 2. Fetch logs for the event in chunks until the current block. # 3. Invoke the callback for each log and sleep for `poll_interval`. while not self.stop_signal: current_block = self.context.provider.eth.block_number from_block = self.event_from_blocks[event_name] while from_block < current_block: end_block = min(from_block + self.block_chunk_size - 1, current_block) self._fetch_event(event_name, callback, from_block, end_block) from_block = end_block + 1 time.sleep(self.poll_interval) def start(self): # 1. Spawn a thread for each registered event using the executor. # 2. Each thread invokes `_run_event` to monitor and process logs. for event_name, callback in self.tracked_events.items(): future = self.executor.submit(self._run_event, event_name, callback) self.futures[event_name] = future def wait(self): # 1. Block until all threads complete their tasks. # 2. Ensures the application does not exit prematurely. for future in self.futures.values(): future.result() def stop(self): # 1. Set `stop_signal` to True to gracefully terminate polling. # 2. Used to shut down the poller when the application exits. self.stop_signal = True def stop_event_thread(self, event_name): # 1. Cancel the thread associated with the specified event. # 2. Remove the thread from the `futures` dictionary. if event_name in self.futures: self.futures[event_name].cancel() del self.futures[event_name] Copy import datetime import logging import simplejson as json from settings import HedgerAddress from share import REDIS_SERVER_EVENTS class SendQuoteHandler: def handle(self, context, args): # 1. Extract event data and block information event_values = args.get('args') block = context.provider.eth.get_block(args.get("blockNumber")) # 2. Fetch additional data for the symbol and quote symbol = context.symbol_fm.map_fields( context.view_provider.contract.functions.getSymbol(event_values.get("symbolId")).call() ) quote = context.quote_fm.map_fields( context.view_provider.contract.functions.getQuote(event_values.get("quoteId")).call() ) # 3. Check if the quote has already been processed quote_status = quote.get("quoteStatus") if quote_status == 3: return # 4. Validate if the hedger is in the whitelist for this quote whitelist = [context.provider.to_checksum_address(addr) for addr in event_values.get("partyBsWhiteList")] if len(whitelist) > 0 and HedgerAddress not in whitelist: return # 5. Construct a payload with relevant event and blockchain data value = { "blockNumber": args.get("blockNumber"), "cva": event_values.get("cva"), "lf": event_values.get("lf"), "partyAmm": event_values.get("partyAmm"), "partyBmm": event_values.get("partyBmm"), "quantity": event_values.get("quantity"), "marketPrice": event_values.get("marketPrice"), "requestedOpenPrice": event_values.get("price"), "quoteStatus": quote.get("quoteStatus"), "quoteId": event_values.get("quoteId"), "symbolId": event_values.get("symbolId"), "symbol": symbol.get("name"), "action": "SendQuote", "partyA": context.provider.to_checksum_address(event_values.get("partyA")), "positionType": event_values.get("positionType"), "orderTypeOpen": event_values.get("orderType"), "maxFundingRate": event_values.get("maxFundingRate"), "deadline": event_values.get("deadline"), "timeStamp": block.get("timestamp"), "timestampsSendQuoteTimeStamp": block.get("timestamp"), "trHash": args.get("transactionHash").hex(), "received_timestamp": datetime.datetime.utcnow().timestamp() // 1000, "input_source": 'py_event_listener', "type": 'quote' } # 6. Generate a unique key for the Redis store key = f"{event_values.get('quoteId')}-{args.get('transactionHash').hex()}-{block.get('timestamp')}" # 7. Log the event for debugging purposes logging.info("SendQuote Received: " + key) # 8. Store the event data in Redis if the key does not already exist REDIS_SERVER_EVENTS.setnx(key, json.dumps(value)) Copy event_values = args.get('args') block = context.provider.eth.get_block(args.get("blockNumber")) Copy symbol = context.symbol_fm.map_fields( context.view_provider.contract.functions.getSymbol(event_values.get("symbolId")).call() ) quote = context.quote_fm.map_fields( context.view_provider.contract.functions.getQuote(event_values.get("quoteId")).call() ) Copy quote_status = quote.get("quoteStatus") if quote_status == 3: return Copy whitelist = [context.provider.to_checksum_address(addr) for addr in event_values.get("partyBsWhiteList")] if len(whitelist) > 0 and HedgerAddress not in whitelist: return Copy value = { "blockNumber": args.get("blockNumber"), ... "type": 'quote' } Copy key = f"{event_values.get('quoteId')}-{args.get('transactionHash').hex()}-{block.get('timestamp')}" Copy logging.info("SendQuote Received: " + key) Copy REDIS_SERVER_EVENTS.setnx(key, json.dumps(value)) sun-brightdesktopmoon --- # Coti | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/coti#contract-addresses) Contract Addresses ------------------------------------------------------------------------------------------------------------------------ Name Address Diamond 0x2Ecc7da3Cc98d341F987C85c3D9FC198570838B5 AccountFacet 0xCF74C49be20351EF069E3F32B6e646d4B2Ba69D9 DiamondCutFacet 0x6b0d9FA54CeC03E83a6b08400228c2AFD291A83d ControlFacet 0x9D4c169703BB0116751A6965952A5E4aDfDFfB05 DiamondLoupeFacet 0x359AE1329F4070f81079B415249fb13664B6cE76 LiquidationFacet 0x8F06459f184553e5d04F07F868720BDaCAB39395 PartyAFacet 0x3adc81CC43d9e1636de9cbac764Afcb1F3ae6cde PartyBQuoteActionsFacet 0x44ca93531be2872a1E6e9987BC8f2d62C0864676 PartyBPositionActionsFacet 0x1347A83D1eb2121B15f944B21Ddbe22ebf8Cf8d1 PartyBGroupActionsFacet 0xc4Bae634C692078a97BEb7b0B583D16B13359Fcf ViewFacet 0x803de354cbd853D9aE3BC58131A5D538DE7a72E3 FundingRateFacet 0x5b5C7B6494EC52D9316a7f578eF3FbBBAA53BE63 BridgeFacet 0x5044238ea045585C704dC2C6387D66d29eD56648 SettlementFacet 0x0392e9CF758CD1566dab547fDAF3DDcfEd1d7375 ForceActrionsFacet 0x01E822AAe6D2cc456804CCd36aA4d3830dbc6e3b [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/coti#affiliate-addresses) Affiliate Addresses -------------------------------------------------------------------------------------------------------------------------- [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/coti#privex) Privex ------------------------------------------------------------------------------------------------ ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/coti#multiaccount) MultiAccount `0xbF318724218cED9A3ff7CfC642c71a0CA1952b0F` ### [hashtag](https://docs.symm.io/protocol-architecture/contract-addresses/coti#fee-collector) Fee Collector `0x80c98e1b606C96eeBEBC1E8e6458C368B155fE16` [PreviousBerachainchevron-left](https://docs.symm.io/protocol-architecture/contract-addresses/berachain) [NextSonicchevron-right](https://docs.symm.io/protocol-architecture/contract-addresses/sonic) Last updated 2 months ago * [Contract Addresses](https://docs.symm.io/protocol-architecture/contract-addresses/coti#contract-addresses) * [Affiliate Addresses](https://docs.symm.io/protocol-architecture/contract-addresses/coti#affiliate-addresses) * [Privex](https://docs.symm.io/protocol-architecture/contract-addresses/coti#privex) * [MultiAccount](https://docs.symm.io/protocol-architecture/contract-addresses/coti#multiaccount) * [Fee Collector](https://docs.symm.io/protocol-architecture/contract-addresses/coti#fee-collector) sun-brightdesktopmoon sun-brightdesktopmoon --- # Control Facet | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/control-facet#changes) Changes: ----------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/control-facet#make-forceclosegapratio-per-symbol) Make `forceCloseGapRatio` per symbol Different symbols with different volatility require different gap ratios for forceClose. **Updated Methods:** Copy // From function setForceCloseGapRatio(uint256 forceCloseGapRatio) external onlyRole(LibAccessibility.SETTER_ROLE) // To function setForceCloseGapRatio(uint256 symbolId, uint256 forceCloseGapRatio) external onlyRole(LibAccessibility.SETTER_ROLE) // From function forceCloseGapRatio() external view returns (uint256) // To function forceCloseGapRatio(uint256 symbolId) external view returns (uint256) ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/control-facet#added-affiliates-into-the-system) Added Affiliates into the System All affiliates, such as intentX, Based, Befi, Core, etc., are now registered in the core contracts. Each affiliate can have a separate `feeCollector`. The new method `sendQuoteWithAffiliate` is introduced, and the old `sendQuote` method is deprecated and will likely be removed in the next version. * The `affiliate` field is added to the quote struct. * `AFFILIATE_MANAGER_ROLE` is introduced, granting control over adding new affiliates and changing their feeCollectors. **Added Methods:** **Updated Methods:** The old `feeCollector` storage is now renamed to `defaultFeeCollectors` and will be used as a fallback when a collector hasn’t been set for an affiliate. Corresponding setters and getters are also added for that. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/control-facet#added-setdeallocatedebouncetime) **Added** `**setDeallocateDebounceTime()**` **Explanation**: This function allows setting the deallocation debounce time. It emits an event `SetDeallocateDebounceTime` indicating the old and new debounce times. [PreviousFacetschevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets) [NextAccount Facetchevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/account-facet) Last updated 1 year ago * [Changes:](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/control-facet#changes) * [Make forceCloseGapRatio per symbol](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/control-facet#make-forceclosegapratio-per-symbol) * [Added Affiliates into the System](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/control-facet#added-affiliates-into-the-system) * [Added setDeallocateDebounceTime()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/control-facet#added-setdeallocatedebouncetime) sun-brightdesktopmoon Copy function registerAffiliate(address affiliate) external onlyRole(LibAccessibility.AFFILIATE_MANAGER_ROLE) function deregisterAffiliate(address affiliate) external onlyRole(LibAccessibility.AFFILIATE_MANAGER_ROLE) function isAffiliate(address affiliate) external view returns (bool) Copy // From function setFeeCollector(address feeCollector) external onlyRole(LibAccessibility.DEFAULT_ADMIN_ROLE) // To function setFeeCollector(address affiliate, address feeCollector) external onlyRole(LibAccessibility.AFFILIATE_MANAGER_ROLE) // From function getFeeCollector() external view returns (address) // To function getFeeCollector(address affiliate) external view returns (address) Copy function setDeallocateDebounceTime(uint256 deallocateDebounceTime) external onlyRole(LibAccessibility.SETTER_ROLE) { emit SetDeallocateDebounceTime(MAStorage.layout().deallocateDebounceTime, deallocateDebounceTime); MAStorage.layout().deallocateDebounceTime = deallocateDebounceTime; } sun-brightdesktopmoon --- # SYMM - V0.8 - 0.81 | SYMMIO Protocol Gitbook [Sherlock Audit - Jun 15, 2023chevron-right](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-v0.8-0.81/sherlock-audit-jun-15-2023) [Smart State - Jul 2, 2023chevron-right](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-v0.8-0.81/smart-state-jul-2-2023) [PreviousAuditschevron-left](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits) [NextSherlock Audit - Jun 15, 2023chevron-right](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-v0.8-0.81/sherlock-audit-jun-15-2023) sun-brightdesktopmoon sun-brightdesktopmoon --- # The SYMM Diamond (0.8.4) | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/the-symm-diamond-0.8.4#the-symm-diamond) The SYMM Diamond ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Symmio's core contracts are implemented using the EIP-2535 Diamond Standard—a modular and upgradeable approach to smart contract development. The 0.8.4 codebase introduces slight modifications; please refer to the updated graphic for the revised depiction of facets and libraries. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/the-symm-diamond-0.8.4#eip-2535-diamond-standard-overview) EIP-2535: Diamond Standard Overview EIP-2535 introduces the Diamond Standard, a methodology for construc ting modular and upgradeable contracts. Central to this standard is the concept of a "Diamond" contract that is composed of multiple "facets," each handling a different set of functionalities. **Key Benefits:** * **Modularity:** Upgrade or modify individual facets independently without impacting the entire contract. * **Function Selectors:** Unique identifiers that route function calls efficiently to the appropriate facet, ensuring organized and conflict-free execution. For further technical details, please refer to the [official EIP-2535 documentationarrow-up-right](https://eips.ethereum.org/EIPS/eip-2535) . * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/the-symm-diamond-0.8.4#symmios-diamond-implementation) Symmio's Diamond Implementation In the Symmio system, the Diamond acts as a facade contract that delegates function calls to its facets via `delegatecall`. Each facet operates as an independent contract and may share internal functions, libraries, and state variables. **Highlights:** * **Centralized Data Storage:** All data manipulated by facets is stored within the Diamond contract. * **Utilization of Libraries:** Libraries define the data structures and methods used to interact with shared state, ensuring consistency across facets. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/the-symm-diamond-0.8.4#storage-libraries) Storage Libraries The SYMM Diamond uses several storage libraries to manage its state. Each storage library defines: * A unique `bytes32` storage slot (derived from a keccak hash of a unique identifier string, e.g., `diamond.standard.storage.quote`). * A **Layout struct** that organizes state variables for consistent access and modification. * A `layout()` function that employs inline assembly to calculate and return a reference to the designated storage slot. **List of Storage Libraries:** * **GlobalAppStorage.sol:** Handles storage for Symmio emergency functions. * **MAStorage.sol:** Contains Master Agreement Storage with variables related to PartyB, such as cooldowns, liquidator shares, and liquidation statuses. * **QuoteStorage.sol:** Defines the Quote, OrderType, QuoteStatus, and PositionType. The Layout struct holds mappings related to quotes. * **MuonStorage.sol:** Specifies the structure for signatures used in verifying symbol prices, user uPnl, and liquidation state. * **AccountStorage.sol:** Manages locked and available balances. * **SymbolStorage.sol:** Defines a Symbol struct containing details about trading symbols, along with a mapping of symbols. * **BridgeStorage.sol:** Manages the bridge feature by storing designated bridge addresses, mapping bridge transactions and tracking transaction IDs. ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252Fe3HdaCvYNJeFsO4iC6CO%252F0.8.4.png%3Falt%3Dmedia%26token%3D54dcbde9-f119-4840-b9bf-3d1b754f282c&width=768&dpr=3&quality=100&sign=dcaf4c8f&sv=2) Facet-Storage Relationships * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/the-symm-diamond-0.8.4#facet-interaction-with-diamond-storage) Facet Interaction with Diamond Storage The Diamond contract itself does not import these storage libraries directly. Instead, when a facet is invoked via `delegatecall`: * It imports and uses the relevant storage library. * The library computes the slot address, allowing the facet to access or modify data in the Diamond’s storage transparently. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/the-symm-diamond-0.8.4#idiamondcut-interface) IDiamondCut Interface The SYMM Diamond implements the `IDiamondCut` interface to manage its function selectors. This interface provides: * **Mapping of Function Selectors:** A relationship between function selectors and their corresponding facet addresses. * **Atomic Updates:** The `diamondCut` function enables adding, replacing, or removing functions from multiple facets in a single transaction. This atomicity prevents data corruption during upgrades. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/the-symm-diamond-0.8.4#finding-facet-contracts) Finding Facet Contracts The `facets()` function provided by the `DiamondLoupeFacet` is essential for inspecting the Diamond's structure. When invoked, it returns an array of facet structs that include: * The address of each facet. * The specific function selectors associated with each facet. For a user-friendly interface to interact with all of the facets within a Diamond contract, consider using the [louper.devarrow-up-right](https://louper.dev/) tool. [PreviousMain Flow (0.8.4)chevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/main-flow-0.8.4) [NextFacetschevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets) Last updated 29 days ago * [The SYMM Diamond](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/the-symm-diamond-0.8.4#the-symm-diamond) * [EIP-2535: Diamond Standard Overview](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/the-symm-diamond-0.8.4#eip-2535-diamond-standard-overview) * [Symmio's Diamond Implementation](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/the-symm-diamond-0.8.4#symmios-diamond-implementation) * [Storage Libraries](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/the-symm-diamond-0.8.4#storage-libraries) * [Facet Interaction with Diamond Storage](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/the-symm-diamond-0.8.4#facet-interaction-with-diamond-storage) * [IDiamondCut Interface](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/the-symm-diamond-0.8.4#idiamondcut-interface) * [Finding Facet Contracts](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/the-symm-diamond-0.8.4#finding-facet-contracts) sun-brightdesktopmoon sun-brightdesktopmoon --- # Helper Contracts | SYMMIO Protocol Gitbook The Symmio protocol includes three key infrastructure contracts—MultiAccount, InstantLayer, and SymmioPartyB—that enable user abstraction, meta-transaction execution, delegated control, and secure interaction with the Symmio Diamond system. [PreviousOracle Integrationchevron-left](https://docs.symm.io/options-protocol-architecture/technical-architecture/oracle-integration) [NextMultiAccount Contractchevron-right](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/multiaccount-contract) Last updated 4 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # SYMM - 0.82 | SYMMIO Protocol Gitbook [Sherlock Audit -Aug 30, 2023chevron-right](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-0.82/sherlock-audit-aug-30-2023) [PreviousSmart State - Jul 2, 2023chevron-left](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-v0.8-0.81/smart-state-jul-2-2023) [NextSherlock Audit -Aug 30, 2023chevron-right](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-0.82/sherlock-audit-aug-30-2023) sun-brightdesktopmoon sun-brightdesktopmoon --- # Solving for Symmio | SYMMIO Protocol Gitbook circle-info ### [hashtag](https://docs.symm.io/building-on-symmio/solving-for-symmio#solver-section-clarifications-and-caveats) Solver Section: Clarifications & Caveats The Solver section of our guide is crafted with a singular goal in mind: to provide a fundamental understanding of the Solver's role in the Symmio system to MarketMakers, Investors and everyone who is interested in becoming a solver himself. However, it's essential to note a few key points about the information it provides. 1. **Educational Use**: The Solver section is educational and not a comprehensive reflection of the entire Symmio protocol. It is structured to provide an introductory grasp of what it means to be a hedger and offers a primer on how one can undertake this role. 2. **Avoid Misconceptions**: Some readers may draw the inference from this section that the Symmio system depends on Solvers hedging themselves via risky off-chain actions, leading to assumed trust dependencies on the Solver side. However, this understanding is incorrect and could potentially lead to erroneous interpretations of the system's operation. 3. **Top-Down Relationship**: To reiterate and clarify, the relationship between a Solver and the Symmio protocol is a top-down one. This means that whatever actions a Solver takes off-chain have no bearing on the on-chain events. Thus, there are no trust assumptions regarding the Solver side of things as they use off-chain systems to hedge themselves or the connection between these offchain systems and Symmio itself. 4. **Independent On-Chain Contracts**: The Symmio contracts function independently of any off-chain actions performed by a Solver. They operate exclusively within the on-chain environment, and are not influenced or impacted by any external actions. 5. **The** Symmio **system is fully isolated:** Symmio is fully isolated by any issues that may or may not arise from using offchain systems, centralized exchanges, trading desks or any other forms of hedging. We strongly recommend you to familiarize yourself with these points for a better understanding of the Solver's role and its interaction with the Symmio protocol. It's important to interpret the Hedger section in light of these clarifications to avoid misrepresentations of the Symmio protocol's actual functioning. ### [hashtag](https://docs.symm.io/building-on-symmio/solving-for-symmio#symmetrial-offers-a-unique-opportunity-for-lps) Symmio offers a unique opportunity for Solvers Symmio, a protocol for on-chain derivatives trading utilizing peer-to-peer bilateral AMFQs or Intents (Automated Request for Quotations), has paved an entirely new way to trade derivatives on-chain, providing significant advantages to early adopter solvers. As the protocol scales, its technological edge and first-mover advantage will become even more valuable, **yielding significant rewards for early adopters in its expansion.** Our Protocol currently offers potential Solvers a unique opportunity to be part of this growth in the early stages. The first Solvers soft committed up to a $20 million open interest range & aims to scale from $20 million to $100 million by onboarding MMs and LPs by incentivizing early Solvers on top of the margins they can earn. Solvers provide liquidity and earn profits by closing the efficiency gap that on-chain derivatives trading still has to this day. **The first Solvers were earning up to 250% APR on their CEFFU-secured stablecoins deposits.** ### [hashtag](https://docs.symm.io/building-on-symmio/solving-for-symmio#undefined) [hashtag](https://docs.symm.io/building-on-symmio/solving-for-symmio#market-potential) Market potential ------------------------------------------------------------------------------------------------------------ **On-chain derivatives present a potential trillion-dollar market.** Currently, the Market anticipation for on-chain derivatives is mimicking the market saturation of Spot on-chain trading prior to uniswap v2 launching. ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252Fmytmbno5upGoNwy1soPj%252FUntitled.png%3Falt%3Dmedia%26token%3D2f048344-4f36-4ee6-aac4-cebf6c96bf57&width=768&dpr=3&quality=100&sign=6e477dff&sv=2) Onchain DEX trading volume vs CEX trading volume in June 2020 around 1.7% right before Uniswap v2 launched in August. ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fsecure.notion-static.com%2F76b8ac1d-c9e6-4542-89ff-d37a799c4c20%2FUntitled.png&width=768&dpr=3&quality=100&sign=cdb8d93f&sv=2) Utitled [hashtag](https://docs.symm.io/building-on-symmio/solving-for-symmio#the-dex-vs.-cex-volume-2-months-before-uniswap-v2s-launch) The DEX vs. CEX volume 2 months before Uniswap v2’s launch. ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Uniswap's V1 version was a proof-of-concept first launched in November 2018 and later improved with the introduction of the V2 version in **August 2020.** Back in June 2020, only 1.69% of the global spot trading volume was done on-chain. ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FlnhsBfg7Woqqzw7hJjFF%252FOnchain%2520DEX%2520vs%2520CEX%2520Derivatives%2520%25201.png%3Falt%3Dmedia%26token%3De0378fc7-8f51-49ce-9cb0-b93de309efe2&width=768&dpr=3&quality=100&sign=312748d&sv=2) **Only 2% of crypto derivatives trading currently occurs on-chain.** Today, a similar market potential exists in the on-chain derivatives trading sector, where **only 2%** of crypto derivatives trading currently occurs on-chain. This presents a substantial opportunity for Symmio to capture a significant market share in crypto and traditional derivatives. With its innovative, AMFQ instant settlement technology, Symmio is uniquely positioned to become the Uniswap v2 equivalent for on-chain derivatives, revolutionizing the industry and offering exceptional growth potential for early investors. #### [hashtag](https://docs.symm.io/building-on-symmio/solving-for-symmio#first-mover-advantage) First mover advantage We offer Solvers the exclusive opportunity to become one of the first liquidity providers on Symmio. By joining Symmio, you will be providing liquidity for a new trading primitive 1. First-mover advantage: As the first liquidity provider on Symmio, you will enjoy a competitive edge over others in the rapidly growing on-chain derivatives market. 2. Technological superiority: Our platform's technological innovations create a tangible lead in the market, distinguishing Symmio from its competitors and offering you a unique advantage as a liquidity provider. 3. Low-risk profile and risk protection: Symmio architecture ensures a low-risk investment opportunity, allowing you to invest your capital and benefit from this groundbreaking platform. At the same time, keep your funds on a trusted custody service (like CEFFU) or other institutional MPC-based trading desks. ​ #### [hashtag](https://docs.symm.io/building-on-symmio/solving-for-symmio#even-more-efficient) Even more efficient. Since quotes in the Symmio system are committed off-chain via frontend applications, Solvers do not need to lock any capital on-chain until they receive a trade request from a user. This allows Solvers to bright platforms and farm with idle capital on various platforms, such as Aave, while waiting for new orders. This increases the efficiency of the platform and yield generation even further. Capital on demand can be withdrawn from Aave and deposited into the platform's on-chain contracts. _**Liquidity is unlocked.**_ #### [hashtag](https://docs.symm.io/building-on-symmio/solving-for-symmio#composability-of-symmetrial) Composability of Symmio On the Symmio (https://cloverfield.exchange) MVP, we integrate Binance liquidity on-chain via our system. This enables on-chain users to trade on Binance Futures liquidity for approximately 200 crypto assets. For providing liquidity on Symmio today, there are two options: **Option II Invest capital into existing Solvers offering services & that use it to provide liquidity** * Investors can inject capital directly into the current running Solver services. (private loan) * The Solver would run all the services and software and manages maintenance. * Solvers could offer a profit split of 70/30, 60/40, 50/50, or 40/60 that can be negotiated based on the size of Liquidity commitments. (for example, at 250% APR generated after 30 days, using a 40/60 split, up to 100% of generated APR would be paid out on stablecoin deposits). **Option II. Become your own Solver on** Symmio To begin Solving services on Symmio, you need to follow these steps: * Set up your trading entity or use an existing one. * Run a [hedger software.](https://docs.symm.io/building-on-symmio/solving-for-symmio/solver-documentation) (maintenance can be complex at this stage.) The trading software can become outdated during upgrades; it must maintain its up time after any potential future updates to the core software. * Obtain an institutional Exchange account. * Have trading capital to deposit on the contract side and Binance to provide incoming trade requests. [PreviousBuilders introductionchevron-left](https://docs.symm.io/building-on-symmio/builders-introduction) [NextSolver documentationchevron-right](https://docs.symm.io/building-on-symmio/solving-for-symmio/solver-documentation) Last updated 1 month ago * [Symmio offers a unique opportunity for Solvers](https://docs.symm.io/building-on-symmio/solving-for-symmio#symmetrial-offers-a-unique-opportunity-for-lps) * [](https://docs.symm.io/building-on-symmio/solving-for-symmio#undefined) * [Market potential](https://docs.symm.io/building-on-symmio/solving-for-symmio#market-potential) * [The DEX vs. CEX volume 2 months before Uniswap v2’s launch.](https://docs.symm.io/building-on-symmio/solving-for-symmio#the-dex-vs.-cex-volume-2-months-before-uniswap-v2s-launch) sun-brightdesktopmoon sun-brightdesktopmoon --- # Sending a Quote (Instant Open) | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/sending-a-quote-instant-open#instant-open-trade) Instant Open Trade --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Instant Opens enable you to open a position immediately by using a market order. This process leverages a prior SIWE login to obtain an access token and then uses that token to send your trade payload to the solver’s instant‑open endpoint. circle-info Instant Trading is only for sending MARKET orders ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/sending-a-quote-instant-open#id-1.-fetch-the-current-price-and-apply-slippage) **1\. Fetch the Current Price and Apply Slippage** Retrieve the asset price from Muon (returned in wei). Use the [uPnL\_A\_WithSymbolPrice](https://docs.symm.io/protocol-architecture/architecture-deep-dive/muon-api#upnl_a_withsymbolprice) method to get this price. Copy // Fetch the asset price from Muon (price returned in wei) async function fetchMuonPrice() { try { const response = await axios.get(MUON_URL); const fetchedPriceWei = response.data.result.data.result.price; if (!fetchedPriceWei) { throw new Error("Muon price not found in response."); } return fetchedPriceWei; // as a string (in wei) } catch (error) { console.error( "Error fetching Muon price:", error.response?.data || error.message ); throw error; } } For LONG positions, you should increase the fetched price by a fixed percentage (e.g., +1%) to account for the hedger’s spread, for SHORT decrease the price by the same amount. This is the `adjustedPrice` that will be sent to the API endpoint. The adjusted price becomes the basis for calculating the notional value. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/sending-a-quote-instant-open#id-2.-fetch-locked-parameters) **2\. Fetch Locked Parameters** Query the solver’s [`get_locked_params`](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/rasa-capital#get-get_locked_params) endpoint to obtain CVA, LF, PartyAmm, and PartyBmm (provided as percentages). These parameters define the collateral requirements for the trade. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/sending-a-quote-instant-open#id-3.-calculate-notional-value) **3\. Calculate Notional Value** For MARKET orders, compute the notional value as: `notionalValue = quantity * adjustedPrice` ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/sending-a-quote-instant-open#id-4.-compute-normalized-locked-values) **4\. Compute Normalized Locked Values:** For each risk parameter (e.g., CVA, LF, PartyAmm, PartyBmm), the normalized locked value is calculated using the formula: **Normalized Locked Value (Wei)** = (Notional Value × lockedParam) / (100 \* leverage) circle-info For `partyBmm`, leverage is not used in the calculation For example: * **CVA:** `(notionalValue * cva) / (100 * leverage)` * **LF:** `(notionalValue * lf) / (100 * leverage)` * **PartyAmm:** `(notionalValue * partyAmm) / (100 * leverage)` * **PartyBmm:** `(notionalValue * partyBmm) / 100)` ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/sending-a-quote-instant-open#id-5.-build-the-trade-payload) **5\. Build the Trade Payload** Create an object containing all the required parameters: * [`**symbolId**`](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#symbolid) **:** The identifier for the asset (e.g., "340" for XRP). * [`**positionType**`](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#positiontype) **:** 0 for LONG (or 1 for SHORT) – note that in instant trading, market orders are used. * [`**orderType**`](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#ordertype) **:** Set to 1 for MARKET orders. * [`**price**`](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/sending-a-quote#price) **:** The adjusted price (after applying slippage). * `**quantity**`**:** The trade quantity (in 18‑decimals). * `**cva**`**,** `**lf**`**,** `**partyAmm**`**,** `**partyBmm**`**:** The normalized locked values calculated above. * [`**maxFundingRate**`](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/partya-facet-0.8.4#sendquotewithaffiliate) **:** Maximum funding rate allowed by Party A (converted to 18 decimals). * `**deadline**`**:** A Unix timestamp indicating when the trade request expires. It's recommended to use a longer dated expiry (>1 day) ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/sending-a-quote-instant-open#id-6.-send-the-instant-open-request) **6\. Send the Instant Open Request:** Use the access token obtained via SIWE login and send the trade payload to the `/instant_open` endpoint of the solver. This is done via an HTTP POST with appropriate headers. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/sending-a-quote-instant-open#sample-script) Sample Script ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Below is a simplified JavaScript example (using ethers and axios) that demonstrates the instant open flow using a LONG XRP order. This includes the login component: [PreviousInstant Login (EOA)chevron-left](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/instant-login-eoa) [NextClosing a Quote (Instant Close)chevron-right](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/closing-a-quote-instant-close) Last updated 11 months ago * [Instant Open Trade](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/sending-a-quote-instant-open#instant-open-trade) * [1\. Fetch the Current Price and Apply Slippage](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/sending-a-quote-instant-open#id-1.-fetch-the-current-price-and-apply-slippage) * [2\. Fetch Locked Parameters](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/sending-a-quote-instant-open#id-2.-fetch-locked-parameters) * [3\. Calculate Notional Value](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/sending-a-quote-instant-open#id-3.-calculate-notional-value) * [4\. Compute Normalized Locked Values:](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/sending-a-quote-instant-open#id-4.-compute-normalized-locked-values) * [5\. Build the Trade Payload](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/sending-a-quote-instant-open#id-5.-build-the-trade-payload) * [6\. Send the Instant Open Request:](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/sending-a-quote-instant-open#id-6.-send-the-instant-open-request) * [Sample Script](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/sending-a-quote-instant-open#sample-script) sun-brightdesktopmoon Copy require("dotenv").config(); const { ethers } = require("ethers"); const axios = require("axios"); const BigNumber = require("bignumber.js"); const PRIVATE_KEY = process.env.PRIVATE_KEY; const activeAccount = process.env.activeAccount; // Your sub-account address const wallet = new ethers.Wallet(PRIVATE_KEY); // -------------------------------------------------------------------- // Trade Configuration // -------------------------------------------------------------------- const ORIGIN = "http://localhost:3000"; const CHAIN_ID = 42161; const LOGIN_URI = `${SOLVER_BASE_URL}/login`; const ISSUED_AT = new Date().toISOString(); const EXPIRATION_DATE = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(); // For locked parameters, append the leverage to the URL: const LEVERAGE = "1"; // Example leverage value const LOCKED_PARAMS_URL = `https://www.perps-streaming.com/v1/42161a/0x141269E29a770644C34e05B127AB621511f20109/get_locked_params/XRPUSDT?leverage=${LEVERAGE}`; const SOLVER_BASE_URL = "https://www.perps-streaming.com/v1/42161a/0x141269E29a770644C34e05B127AB621511f20109"; const DOMAIN = "localhost"; // For XRP, the marketId is "340" const symbolId = 340; // Position type: 0 for long, 1 for short const positionType = 0; // Order type: 0 = limit, 1 = market (instant trading only uses market orders) const orderType = 1; // Trade quantity (6.1 XRP tokens) – ensure this exceeds the minimum notional value (e.g. ~$15) const quantity = "6.1"; // Maximum funding rate as a string (e.g. "200") const maxFundingRate = "200"; // Deadline: current timestamp + 1 hour (in seconds) const deadline = Math.floor(Date.now() / 1000) + 3600; // -------------------------------------------------------------------- // Helper Functions // -------------------------------------------------------------------- function buildSiweMessage({ domain, address, statement, uri, version, chainId, nonce, issuedAt, expirationTime }) { return `${domain} wants you to sign in with your Ethereum account: ${address} ${statement} URI: ${uri} Version: ${version} Chain ID: ${chainId} Nonce: ${nonce} Issued At: ${issuedAt} Expiration Time: ${expirationTime}`; } async function getNonce(address) { const url = `${SOLVER_BASE_URL}/nonce/${address}`; const { data } = await axios.get(url); return data.nonce; } async function fetchMuonPrice() { try { //Replace MUON_URL with your GET endpoint for uPnL_A_WithSymbolPrice const MUON_URL = ""; const response = await axios.get(MUON_URL); const fetchedPriceWei = response.data.result.data.result.price; if (!fetchedPriceWei) { throw new Error("Muon price not found in response."); } return fetchedPriceWei; } catch (error) { console.error( "Error fetching Muon price:", error.response?.data || error.message ); throw error; } } async function fetchLockedParams() { try { const response = await axios.get(LOCKED_PARAMS_URL); if (response.data && response.data.message === "Success") { return response.data; // Contains: cva, lf, leverage, partyAmm, partyBmm } else { throw new Error("Failed to fetch locked parameters."); } } catch (error) { console.error( "Error fetching locked parameters:", error.response?.data || error.message ); throw error; } } // Compute normalized locked value for a given parameter (e.g. CVA, LF, PartyAmm) // For CVA, LF, and PartyAmm, the formula is: (notionalValue * lockedParam) / (100 * leverage) // For PartyBmm, the formula is: (notionalValue * partyBmm) / 100 function calculateNormalizedLockedValue(notional, lockedParam, leverage, applyLeverage = true) { if (applyLeverage) { return notional.multipliedBy(new BigNumber(lockedParam)).dividedBy(100 * leverage); } else { return notional.multipliedBy(new BigNumber(lockedParam)).dividedBy(100); } } // -------------------------------------------------------------------- // openInstantTrade: Executes the instant open trade process // -------------------------------------------------------------------- async function openInstantTrade(token) { try { // 1. Fetch the raw asset price (in wei) from Muon. const fetchedPriceWei = await fetchMuonPrice(); console.log("Fetched price (wei):", fetchedPriceWei); // 2. Apply a fixed +5% slippage. const fetchedPriceBN = new BigNumber(fetchedPriceWei); const adjustedPriceBN = fetchedPriceBN.multipliedBy(1.05); //Because we're going LONG, adjust by increasing to account for hedger spread.. const adjustedPrice = ethers.formatUnits(adjustedPriceBN.toFixed(), 18); console.log("Adjusted price (+5%):", adjustedPrice); // 3. Fetch locked parameters (includes leverage). const lockedParams = await fetchLockedParams(); console.log("Locked parameters:", lockedParams); // 4. Compute the notional value (for MARKET orders: quantity * adjustedPrice) const notional = new BigNumber(adjustedPrice).multipliedBy(new BigNumber(quantity)); console.log("Notional:", notional.toString()); // 5. Compute normalized locked values: const leverage = new BigNumber(lockedParams.leverage); const normalizedCVA = calculateNormalizedLockedValue(notional, lockedParams.cva, leverage, true).toFixed(); const normalizedLF = calculateNormalizedLockedValue(notional, lockedParams.lf, leverage, true).toFixed(); const normalizedPartyAmm = calculateNormalizedLockedValue(notional, lockedParams.partyAmm, leverage, true).toFixed(); const normalizedPartyBmm = calculateNormalizedLockedValue(notional, lockedParams.partyBmm, leverage, false).toFixed(); console.log("Normalized CVA:", normalizedCVA); console.log("Normalized LF:", normalizedLF); console.log("Normalized PartyAmm:", normalizedPartyAmm); console.log("Normalized PartyBmm:", normalizedPartyBmm); // 6. Build the trade payload with normalized values. const tradeParams = { symbolId: symbolId, // For XRP, this is 340 positionType: positionType, // 0 for long (or 1 for short) orderType: orderType, // 1 for market order price: adjustedPrice, // Adjusted price after slippage quantity: quantity, // Quantity in human-readable format (e.g., "6.1") cva: normalizedCVA, lf: normalizedLF, partyAmm: normalizedPartyAmm, partyBmm: normalizedPartyBmm, maxFundingRate: maxFundingRate, deadline: deadline // Unix timestamp for deadline }; console.log("Trade Payload:", tradeParams); // 7. Send the instant open request using the access token. const headers = { "Content-Type": "application/json", Authorization: `Bearer ${token}` }; const response = await axios.post(`${SOLVER_BASE_URL}/instant_open`, tradeParams, { headers }); console.log("Instant open response:", response.data); } catch (error) { console.error("Error in openInstantTrade:", error.response?.data || error.message); } } // -------------------------------------------------------------------- // MAIN FLOW: SIWE Login then Instant Open Trade // -------------------------------------------------------------------- (async function main() { try { console.log(`\n[1/4] Wallet Address: ${wallet.address}`); const nonce = await getNonce(activeAccount); console.log(`[2/4] Got nonce: ${nonce}`); const siweMessage = buildSiweMessage({ domain: DOMAIN, address: wallet.address, statement: `msg: ${activeAccount}`, uri: LOGIN_URI, version: "1", chainId: CHAIN_ID, nonce, issuedAt: ISSUED_AT, expirationTime: EXPIRATION_DATE }); console.log("\n[3/4] SIWE message to sign:\n", siweMessage); const signature = await wallet.signMessage(siweMessage); console.log("\nSignature:", signature); const loginBody = { account_address: activeAccount, expiration_time: EXPIRATION_DATE, issued_at: ISSUED_AT, signature, nonce }; const loginHeaders = { "Content-Type": "application/json", Origin: ORIGIN, Referer: ORIGIN }; console.log("\n[4/4] Sending login request..."); const loginResponse = await axios.post(`${SOLVER_BASE_URL}/login`, loginBody, { headers: loginHeaders }); console.log("Login response:", loginResponse.data); const token = loginResponse.data.access_token; if (!token) { throw new Error("No access token received from login."); } await openInstantTrade(token); } catch (err) { console.error("Error in SIWE login flow:", err.response?.data || err.message); } })(); sun-brightdesktopmoon --- # Rasa Instant Trading Implementation | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#implementing-instant-actions) Implementing Instant Actions -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#for-frontends) For Frontends: To enable instant actions on the frontend, users must delegate specific functions to solvers so they can perform actions on the user's behalf without requiring signatures for each request. Front-ends should ensure that the following functions are delegated to the respective solver addresses through the `delegateAccess()` method on the MultiAccount contract: * `sendQuote`: **0x7f2755b2** * `sendQuoteWithAffiliate`: **0x40f1310c** * `requestToClosePosition`: **0x501e891f** * `requestToCancelQuote`: **0xa8ffc7ab** * `requestToCancelCloseRequest`: **0xa63b9363** * `allocate`: **0x90ca796b** The delegation should be initiated by calling delegateAccesses() on the [MultiAccount](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount) contract, specifying the user’s sub-account, the target (solver) address, and the function selectors that need to be delegated. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#for-solvers) For Solvers: ----------------------------------------------------------------------------------------------------------------------------------------------------------------- [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#overview) Overview ---------------------------------------------------------------------------------------------------------------------------------------------------------- This document outlines how to implement Instant Trading for Solvers. Instant trading involves creating sessions for users allowing solvers to open and close positions on traders' behalf without requiring signatures for each action. Users must first delegate certain functions to the solver to manage positions on behalf of them (`sendQuote`, `sendQuoteWithAffiliate`, `requestToClosePosition`) The frontend then prompts to authenticate the user for instant actions and generates a message to sign. This message includes the following details: * Wallet Address (`address`): The multiaccount address to be used with instant trading. * Nonce (`nonce`): The nonce related to the request. * Domain (`domain`): The domain of the application. * URI (`uri`): The specific endpoint the request is associated with (e.g., the login endpoint). * Issued At (`issuedAt`): The timestamp when the message was created. * Expiration Time (`expirationTime`): The time after which the signature is no longer valid. Once the message is signed, the frontend sends this signed message along with other necessary data (such as the nonce, expiration time, and wallet address) to the solver API via a request (e.g., to the `/login` endpoint). The solver should issue an access token which the frontend stores and includes it in the headers of future requests until the token expires. Solvers should validate the stored access token before proceeding with any API request. The expiration time can be set by the frontend and should be checked before every API call. This section covers the API endpoints and request/response structures needed for instant trading. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#authentication-and-session-management) Authentication and Session Management Before executing any trading actions, solvers must authenticate the user and manage sessions via the following endpoints. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#nonce-retrieval) Nonce Retrieval **Endpoint**: `GET /nonce/{activeAddress}` * Description: Retrieve a nonce for signing the login message. **Parameters**: * `activeAddress` (string): The user's active multiaccount wallet address. **Response:** ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#user-login) User Login **Endpoint**: `POST /login` * **Description**: Authenticates the user and retrieves an access token. The nonce is obtained in the previous API call. The access token is saved to the browser locally, meaning the user won't have to log in again after closing and reopening the browser. **Request Body:** **Response:** ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#get-pending-instant-open-requests) Get Pending Instant Open Requests **Endpoint**: `GET /instant_open/{account_address}` Description: This endpoint retrieves a statement for all pending instant open requests for a given account. **Parameters**: * `account_address` (string): The user's multi-account wallet address. **Response**: A list of pending instant open requests for the given account. Each object in the list contains details of the requested positions. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#response-schema) Response Schema: [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#instant-actions) Instant Actions ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ These endpoints allow solvers to execute instant open and close actions on the user's behalf. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#instant-open-position) Instant Open Position **Endpoint**: `POST /instant_open` Opens a position instantly on behalf of the user. The user’s account balance is checked, including allocated balance, unrealized PnL, and locked amounts (cva, lf, partyAmm). If the user has too many pending instant RFQs, or if their available balance does not cover the new RFQ's requirements, the request should be rejected. A temporary quote ID is generated, and the necessary request data is emitted and stored in Redis. The request is registered as a pending instant open action (stored in the InstantRFQs table). **Response:** Upon successful registration, the details of the newly created instant RFQ are returned, including position type, symbol ID, quote ID, and other relevant data. **Request Body:** **Headers:** **Response:** This response includes the temporary `temp_quote_id` which allows the system to track the quote before it is confirmed on-chain. Once confirmed, the real `quote_id` will be resolved and stored. How Temporary Quote IDs Work: * A temporary quote ID is generated as a negative decremental integer when the instant open request is made. * The temporary quote ID is used to track the status of the position until the actual on-chain `quote_id` is confirmed. * Once the on-chain transaction is confirmed, the real `quote_id` replaces the temporary one. * The position state endpoint will provide the real `quote_id` after the resolution, allowing the user to track the final status. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#instant-close-position) Instant Close Position **Endpoint**: `POST /instant_close` * Description: Closes an open position instantly on behalf of the user. The API checks the validity of the request based on the user's access, the state of the position, and available balance The close is always processed as a MARKET order. **Request Body:** **Headers:** **Response:** ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#get-instant-close-requests) Get Instant Close Requests **Endpoint:** `GET /instant_close/{account_address}` Description: Retrieves all pending instant close requests for the provided user's account (`account_address`). The system returns a list of pending close requests for both instant close requests and any regular close requests that are still being processed. **Headers:** **Response:** ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#cancel-instant-action) Cancel Instant Action **Endpoints**: * `DELETE /instant_close/{quoteId}` * `DELETE /instant_open/{quoteId}` **Description**: Cancel an open or close request. **Parameters**: * `quoteId` (integer): The temporary ID of the instant quote to be canceled. **Headers**: **Response:** [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#contract-calls-for-instant-trading) Contract Calls for Instant Trading -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- In order to implement instant actions it’s necessary for the user to call `delegateAccess()` on the MultiAccount contract for the respective sub-account to the partyB address, which performs actions on behalf of the user. This transaction should include the function signatures which partyB needs access to for instant trading. To execute functions on behalf of partyA, the partyB should use the `_call()` function on the MultiAccount contract and pass the partyA address as a parameter with the `_callDatas`. After this step the user should then sign the message from the solver. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#instant-open) Instant Open For Instant Opens, `delegateAccess()` should be called from the trader’s wallet with the following parameters: * `account` (address): The User’s sub-account * `target` (address) : The address of the PartyB * `selector` (bytes4\[\]): `0x7f2755b2` (Function selector for sendQuote) AND `0x40f1310c` (Function selector for sendQuoteWithAffiliate) * `state` (bool): true ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#instant-close) Instant Close For Instant Close, delegateAccess() should be called from the trader’s wallet with the following parameters: * `account`(address): The User’s sub-account * `target`(address) : The address of the PartyB * `selector`(bytes4\[\]): 0x501e891f (Function selector for requestToClosePosition) * `state` (bool): true [PreviousInstant Trading (Solvers)chevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-solvers) [NextInstant Trading Condition Checkschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/instant-trading-condition-checks) Last updated 1 month ago * [Implementing Instant Actions](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#implementing-instant-actions) * [For Frontends:](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#for-frontends) * [For Solvers:](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#for-solvers) * [Overview](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#overview) * [Authentication and Session Management](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#authentication-and-session-management) * [Nonce Retrieval](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#nonce-retrieval) * [User Login](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#user-login) * [Get Pending Instant Open Requests](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#get-pending-instant-open-requests) * [Response Schema:](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#response-schema) * [Instant Actions](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#instant-actions) * [Instant Open Position](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#instant-open-position) * [Instant Close Position](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#instant-close-position) * [Get Instant Close Requests](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#get-instant-close-requests) * [Cancel Instant Action](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#cancel-instant-action) * [Contract Calls for Instant Trading](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#contract-calls-for-instant-trading) * [Instant Open](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#instant-open) * [Instant Close](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading/rasa-instant-trading-implementation#instant-close) sun-brightdesktopmoon Copy { "nonce": "string" } Copy { "account_address": "string", "expiration_time": "ISO8601 datetime string", "issued_at": "ISO8601 datetime string", "signature": "string", "nonce": "string" } Copy { "access_token": "string" } Copy [\ {\ "position_type": 0 // 0 for long, 1 for short,\ "temp_quote_id": "string",\ "symbol_id": "string",\ "requested_open_price": "string",\ "quantity": "string",\ "party_a_address": "string",\ "cva": "string",\ "partyAmm": "string",\ "partyBmm": "string",\ "lf": "string",\ "order_type": 0 // 0 for limit, one for market\ }\ ] Copy { "symbolId": "string", "positionType": 0, // 0 for long, 1 for short "orderType": 0, // 0 for limit, 1 for market "price": "string", "quantity": "string", "cva": "string", "lf": "string", "partyAmm": "string", "partyBmm": "string", "maxFundingRate": "string", "deadline": 1625234523 // Unix timestamp } Copy headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, Copy [\ {\ "position_type": 0 // 0 for long, 1 for short,\ "temp_quote_id": "string",\ "symbol_id": "string",\ "requested_open_price": "string",\ "quantity": "string",\ "party_a_address": "string",\ "cva": "string",\ "partyAmm": "string",\ "partyBmm": "string",\ "lf": "string",\ "order_type": 0 // 0 for limit, one for market\ }\ ] Copy { "quote_id": number, "quantity_to_close": "string", "close_price": "string" } Copy headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, Copy { "successful": "boolean", "message": "string" } Copy { "Authorization": `Bearer ${token}` // Access token obtained during login } Copy [\ {\ "quote_id": number, \ "quantity_to_close": "string", \ "close_price": "string" },\ {\ "quote_id": number,\ "quantity_to_close": "string",\ "close_price": "string"\ }\ ] Copy headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, Copy { "successful": "boolean", "message": "string" } sun-brightdesktopmoon --- # Sherlock Audit - Oct 3, 2024 | SYMMIO Protocol Gitbook [![Logo](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2Faudits.sherlock.xyz%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=87b6773d&sv=2)SYMMIO v0.8.4 Update Contest Contest - 26,000 USDCaudits.sherlock.xyzchevron-right](https://audits.sherlock.xyz/contests/577?filter=questions) circle-info Sherlock is an audit marketplace and smart contract coverage protocol built on the Ethereum blockchain. Sherlock works to protect Decentralized Finance (DeFi) users from smart contract exploits with security reviews from top auditors backed by smart contract coverage on the audited contracts. You can find a brief overview of the Sherlock ecosystem below. [https://docs.sherlock.xyz/arrow-up-right](https://docs.sherlock.xyz/) View findings:[https://github.com/sherlock-audit/2024-09-symmio-v0-8-4-update-contest-judging/issuesarrow-up-right](https://github.com/sherlock-audit/2024-09-symmio-v0-8-4-update-contest-judging/issues) Audit report: [https://audits.sherlock.xyz/contests/577?filter=questionsarrow-up-right](https://audits.sherlock.xyz/contests/577?filter=questions) [PreviousSYMM - 0.84chevron-left](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-0.84) [NextVaultschevron-right](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/vaults) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Account Facet | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/account-facet#changes) Changes: ----------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/account-facet#added-internaltransfer-method) Added `InternalTransfer` Method This method allows a user to send their deposits to another user’s allocated balance. The receiver address cannot be a partyB and must not be in a liquidated state. This enables users to transfer funds between accounts without waiting for `deallocateCooldown`. `internalTransfer()` uses the balance of the sender's account, not allocatedBalance, so you'll have to call `deallocate()` first if funds are already allocated. Copy function internalTransfer(address user, uint256 amount) internal { AccountStorage.Layout storage accountLayout = AccountStorage.layout(); require( accountLayout.allocatedBalances[user] + amount <= GlobalAppStorage.layout().balanceLimitPerUser, "AccountFacet: Allocated balance limit reached" ); require(accountLayout.balances[msg.sender] >= amount, "AccountFacet: Insufficient balance"); accountLayout.balances[msg.sender] -= amount; accountLayout.allocatedBalances[user] += amount; } Symmio can pause internal transfers when needed. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/account-facet#deallocate) `**deallocate()**` **Before:** Copy require( accountLayout.allocatedBalances[msg.sender] >= amount, "AccountFacet: Insufficient allocated Balance" ); **After:** **Explanation**: Added a new condition to enforce a debounce time between deallocation requests to prevent too frequent deallocations. #### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/account-facet#summary-of-changes) Summary of Changes * **Added a debounce time check** to the `deallocate` function to ensure that deallocation requests are not made too frequently. This is done by checking that the current block timestamp is greater than or equal to the sum of the user's `withdrawCooldown` and the global `deallocateDebounceTime`. * **Maintained the existing check** to ensure the user has sufficient allocated balance for the deallocation request. This change helps to prevent abuse of the deallocation process by enforcing a time window between consecutive deallocations. [PreviousControl Facetchevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/control-facet) [NextPartyA Facetchevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/partya-facet) Last updated 1 year ago * [Changes:](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/account-facet#changes) * [Added InternalTransfer Method](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/account-facet#added-internaltransfer-method) * [deallocate()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/account-facet#deallocate) sun-brightdesktopmoon Copy require( block.timestamp >= accountLayout.withdrawCooldown[msg.sender] + MAStorage.layout().deallocateDebounceTime, "AccountFacet: Too many deallocate in a short window" ); require( accountLayout.allocatedBalances[msg.sender] >= amount, "AccountFacet: Insufficient allocated Balance" ); sun-brightdesktopmoon --- # Smart State - Jul 2, 2023 | SYMMIO Protocol Gitbook Unexpected error with integration github-files: Integration is not authenticated with GitHub Smart State audited SYMMIO, through a collaboration (3rd Party Frontend and Hedger), who provided the audit as a grant. ### [hashtag](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-v0.8-0.81/smart-state-jul-2-2023#about-smart-state) **About Smart State** Established in 2019, Smart State has always been at the forefront of innovation. While many firms in the industry limit themselves to a standard checklist approach for smart contract audits and security reviews, Smart State believes in a more holistic approach. ### [hashtag](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-v0.8-0.81/smart-state-jul-2-2023#more-on-their-website-https-smartstate.tech-about.html) more on their website: [https://smartstate.tech/about.htmlarrow-up-right](https://smartstate.tech/about.html) [PreviousSherlock Audit - Jun 15, 2023chevron-left](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-v0.8-0.81/sherlock-audit-jun-15-2023) [NextSYMM - 0.82chevron-right](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-0.82) Last updated 1 year ago * [About Smart State](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-v0.8-0.81/smart-state-jul-2-2023#about-smart-state) * [more on their website: https://smartstate.tech/about.html](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-v0.8-0.81/smart-state-jul-2-2023#more-on-their-website-https-smartstate.tech-about.html) sun-brightdesktopmoon sun-brightdesktopmoon --- # Solver Implementation Guide (High Level Overview) | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-implementation-guide-high-level-overview#overview) Overview ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- This document provides a quick guide on setting up a Solver with the SYMMIO platform. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-implementation-guide-high-level-overview#prerequisites) Prerequisites **Read Symmio's Smart Contracts:** Understanding the smart contracts is essential. Start by reading through the contracts to familiarize yourself with their functions and events. Smart contract documentation (0.8.4) can be found [herearrow-up-right](https://docs.symm.io/protocol-architecture/technical-documentation/contracts-documentation-0.8.2) . [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-implementation-guide-high-level-overview#steps-to-set-up-a-solver-with-symm) Steps to Set Up a Solver with SYMM -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FiSxKDrB7WWodpiwXRwaO%252FSYMMIO%2520Hedger%2520Architecture.png%3Falt%3Dmedia%26token%3Db75102e8-d9ac-4655-b783-79e8e3b231db&width=768&dpr=3&quality=100&sign=379db80&sv=2) Recommended Architecture for Solvers ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-implementation-guide-high-level-overview#smart-contracts-and-event-handling) Smart Contracts and Event Handling To become familiar with the infrastructure it's recommended to develop a bot to read and handle events from the smart contracts. This bot should listen for specific events and then take appropriate actions depending on the function. Symmio's smart contracts rely on data verification from the Muon network to ensure the validity of asset prices and unrealized profit and loss for parties. This process involves invoking methods on the Muon app before any action is executed on the contract. You can read more about Muon queries [here](https://docs.symm.io/protocol-architecture/architecture-deep-dive/muon-api) . To accept quotes, you need an address that is whitelisted to act as `partyB` on the contract side. Please contact our developers to get whitelisted. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-implementation-guide-high-level-overview#setting-up-a-mock-frontend) Setting Up a Mock Frontend After getting familiar with the smart contracts and developing your event-handling bot, the next step is to set up a mock frontend. 1. **Obtain a Mock Frontend:** * Contact Symmio's development team to get access to a mock frontend. This frontend will allow you to send intents and simulate various user actions. 2. **Send Intents:** * Use the mock frontend to send intents to your bot. You can use these intents to test how your bot handles different events and actions. 3. **Write a Script to Accept Intents:** * Develop a script that will process and accept the intents sent from the mock frontend. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-implementation-guide-high-level-overview#building-the-position-manager-internal-solving-strategy) Building the Position Manager / Internal Solving Strategy This involves creating an internal strategy for solving positions based on market conditions and your hedging needs. Hedging strategies are private and may vary. Develop your unique strategy based on your risk management and market analysis. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-implementation-guide-high-level-overview#building-the-broker-order-pusher) Building the Broker Order Pusher When a quote is seen that adheres to the solving strategy, it's standard procedure to call `lockQuote()` on the contract side, then open a position elsewhere (Binance, etc.) to hedge the position before calling `openPosition()` on the contract. This process can also be done in parallel with Instant Execution, where a user delegates the access of their account to the solver to enable faster trading. To ensure these transactions succeed it's vital to create a module for reliable RPC calls, or use a service like Gelato Relayer. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-implementation-guide-high-level-overview#build-the-on-chain-balance-manager) Build the On-Chain Balance Manager One of the services that Solver should run is a position manager to keep tabs on solvency to prevent being liquidated across positions. Create a balance manager to track and manage the health of your positions on-chain which can adjust the collateral balances within each trade. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-implementation-guide-high-level-overview#setting-up-endpoints-websockets) Setting up Endpoints/Websockets To ensure effective communication with frontends and users, you'll need to set up various APIs and Websockets. **REST APIs** Set up APIs to provide essential data such as: * **Available Markets**: Lists the markets that the Solver is offering. * **Total Open Interest**: Provides data on the total open interest across different markets. * **Error Codes**: Provides a list of potential error codes and their meanings. * **User Position Data**: Returns data related to a user's position with the Solver. **Websockets** Configure Websockets to provide real-time updates: * **Funding Rate**: Reflects the current funding rate charged on each symbol. * **User Position State**: Notifies users about the state of their position. For an exhaustive list and detailed examples of endpoints and Websockets, please refer to this [documentation](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints/rasa-capital) . ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-implementation-guide-high-level-overview#build-a-position-monitor-and-validator) Build a Position Monitor & Validator Finally set up monitoring and developer alerts to maintain uptime and reliability. [PreviousBuilding a Solver on SYMMIOchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio) [Next1\. Intent Creationchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/1.-intent-creation) Last updated 25 days ago * [Overview](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-implementation-guide-high-level-overview#overview) * [Prerequisites](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-implementation-guide-high-level-overview#prerequisites) * [Steps to Set Up a Solver with SYMM](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-implementation-guide-high-level-overview#steps-to-set-up-a-solver-with-symm) * [Smart Contracts and Event Handling](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-implementation-guide-high-level-overview#smart-contracts-and-event-handling) * [Setting Up a Mock Frontend](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-implementation-guide-high-level-overview#setting-up-a-mock-frontend) * [Building the Position Manager / Internal Solving Strategy](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-implementation-guide-high-level-overview#building-the-position-manager-internal-solving-strategy) * [Building the Broker Order Pusher](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-implementation-guide-high-level-overview#building-the-broker-order-pusher) * [Build the On-Chain Balance Manager](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-implementation-guide-high-level-overview#build-the-on-chain-balance-manager) * [Setting up Endpoints/Websockets](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-implementation-guide-high-level-overview#setting-up-endpoints-websockets) * [Build a Position Monitor & Validator](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/solver-implementation-guide-high-level-overview#build-a-position-monitor-and-validator) sun-brightdesktopmoon sun-brightdesktopmoon --- # PartyB Facet | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/partyb-facet#changes) Changes: ---------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/partyb-facet#acceptcancelrequest) `**acceptCancelRequest()**` **Before:** Copy // send trading Fee back to partyA accountLayout.allocatedBalances[quote.partyA] += LibQuote.getTradingFee(quoteId); **After:** Copy // send trading Fee back to partyA uint256 fee = LibQuote.getTradingFee(quoteId); accountLayout.allocatedBalances[quote.partyA] += fee; emit SharedEvents.BalanceChangePartyA(quote.partyA, fee, SharedEvents.BalanceChangeType.PLATFORM_FEE_IN); **Explanation**: Added emission of `BalanceChangePartyA` event when returning the trading fee to Party A upon quote cancellation. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/partyb-facet#openposition) `**openPosition()**` **Before:** Copy accountLayout.balances[GlobalAppStorage.layout().feeCollector] += (filledAmount * quote.requestedOpenPrice * quote.tradingFee) / 1e36; ... accountLayout.balances[GlobalAppStorage.layout().feeCollector] += (filledAmount * quote.marketPrice * quote.tradingFee) / 1e36; ... accountLayout.pendingLockedBalances[quote.partyA].subQuote(quote); ... accountLayout.allocatedBalances[newQuote.partyA] += LibQuote.getTradingFee(newQuote.id); ... accountLayout.pendingLockedBalances[quote.partyA].sub(filledLockedValues); ... newQuote.lockedValues = quote.lockedValues.sub(filledLockedValues); **After:** **Explanation**: Added emission of `BalanceChangePartyA` in all places where the allocated balance of the user changes. Also, platform fees are now paid to fee collectors of each affiliate separately. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/partyb-facet#emergencycloseposition) `**emergencyClosePosition()**` **Before:** **After:** **Explanation**: From time to time, Binance delists some of its pairs. In the current version, we had to put partyBs in emergency mode to let them close their positions without user requests. In the next version, if a symbol becomes invalid, partyB can emergency close all its positions. [PreviousPartyA Facetchevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/partya-facet) [NextView Facetchevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/view-facet) Last updated 1 year ago * [Changes:](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/partyb-facet#changes) * [acceptCancelRequest()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/partyb-facet#acceptcancelrequest) * [openPosition()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/partyb-facet#openposition) * [emergencyClosePosition()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/partyb-facet#emergencycloseposition) sun-brightdesktopmoon Copy accountLayout.balances[GlobalAppStorage.layout().affiliateFeeCollector[quote.affiliate]] += (filledAmount * quote.requestedOpenPrice * quote.tradingFee) / 1e36; ... accountLayout.balances[GlobalAppStorage.layout().affiliateFeeCollector[quote.affiliate]] += (filledAmount * quote.marketPrice * quote.tradingFee) / 1e36; ... uint256 fee = LibQuote.getTradingFee(newQuote.id); accountLayout.allocatedBalances[newQuote.partyA] += fee; emit SharedEvents.BalanceChangePartyA(newQuote.partyA, fee, SharedEvents.BalanceChangeType.PLATFORM_FEE_IN); ... accountLayout.pendingLockedBalances[quote.partyA].sub(filledLockedValues); emit SharedEvents.BalanceChangePartyA(quote.partyA, filledLockedValues.totalForPartyA(), SharedEvents.BalanceChangeType.LOCK_OUT); ... newQuote.lockedValues = quote.lockedValues.sub(filledLockedValues); emit SharedEvents.BalanceChangePartyA(newQuote.partyA, filledLockedValues.totalForPartyA(), SharedEvents.BalanceChangeType.LOCK_OUT); Copy function emergencyClosePosition(uint256 quoteId, PairUpnlAndPriceSig memory upnlSig) internal { AccountStorage.Layout storage accountLayout = AccountStorage.layout(); Quote storage quote = QuoteStorage.layout().quotes[quoteId]; require(quote.quoteStatus == QuoteStatus.OPENED || quote.quoteStatus == QuoteStatus.CLOSE_PENDING, "PartyBFacet: Invalid state"); LibMuon.verifyPairUpnlAndPrice(upnlSig, quote.partyB, quote.partyA, quote.symbolId); uint256 filledAmount = LibQuote.quoteOpenAmount(quote); quote.quantityToClose = filledAmount; quote.requestedClosePrice = upnlSig.price; LibSolvency.isSolventAfterClosePosition(quoteId, filledAmount, upnlSig.price, upnlSig); accountLayout.partyBNonces[quote.partyB][quote.partyA] += 1; accountLayout.partyANonces[quote.partyA] += 1; LibQuote.closeQuote(quote, filledAmount, upnlSig.price); } Copy function emergencyClosePosition(uint256 quoteId, PairUpnlAndPriceSig memory upnlSig) internal { AccountStorage.Layout storage accountLayout = AccountStorage.layout(); Quote storage quote = QuoteStorage.layout().quotes[quoteId]; Symbol memory symbol = SymbolStorage.layout().symbols[quote.symbolId]; require( GlobalAppStorage.layout().emergencyMode || GlobalAppStorage.layout().partyBEmergencyStatus[quote.partyB] || !symbol.isValid, "PartyBFacet: Operation not allowed. Either emergency mode must be active, party B must be in emergency status, or the symbol must be delisted" ); require(quote.quoteStatus == QuoteStatus.OPENED || quote.quoteStatus == QuoteStatus.CLOSE_PENDING, "PartyBFacet: Invalid state"); LibMuon.verifyPairUpnlAndPrice(upnlSig, quote.partyB, quote.partyA, quote.symbolId); uint256 filledAmount = LibQuote.quoteOpenAmount(quote); quote.quantityToClose = filledAmount; quote.requestedClosePrice = upnlSig.price; LibSolvency.isSolventAfterClosePosition(quoteId, filledAmount, upnlSig.price, upnlSig); accountLayout.partyBNonces[quote.partyB][quote.partyA] += 1; accountLayout.partyANonces[quote.partyA] += 1; LibQuote.closeQuote(quote, filledAmount, upnlSig.price); } sun-brightdesktopmoon --- # Technical Architecture | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture#diamond-pattern-implementation) Diamond Pattern Implementation ------------------------------------------------------------------------------------------------------------------------------------------------------- The protocol leverages the **EIP-2535 Diamond Pattern** to achieve modularity, upgradeability, and well-organized shared storage management. #### [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture#core-components) Core Components 1. **Diamond Contract** Acts as the main entry point, delegating function calls to the appropriate facets. 2. **Facets** Modular contracts that implement specific areas of functionality. 3. **Shared Storage** Structured storage layout that is accessible across all facets, ensuring consistency and upgrade safety. [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture#storage-architecture) Storage Architecture ----------------------------------------------------------------------------------------------------------------------------------- **Storage Contract** **Purpose** **Key Data Structures** **AppStorage** Global configuration System version, collateral whitelist, limits, timeouts, Party B configurations **AccountStorage** User balances and accounts Scheduled releases, withdrawal records, nonces **SymbolStorage** Trading instruments Symbol definitions, oracle references, instrument configurations **TradeStorage** Active positions Open intents, close intents, active trades **StateControlStorage** System state management Pause states, emergency flags, suspended addresses **AccessControlStorage** Permission management User roles, access rights [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture#facet-organization) Facet Organization ------------------------------------------------------------------------------------------------------------------------------- **1\. Account Management** * **Account Facet** Manages user deposits, withdrawals, balances, and collateral allocation. 1. **Trading Operations** * **Party A Open Facet** & **Party A Close Facet** Handle Party A’s position opening and closing intents. * **Party B Open Facet** & **Party B Close Facet** Manage Party B’s intent locking, unlocking, and filling intents. * **Trade Facet** Manage trade execution and cancelation. [PreviousCore Financial Conceptschevron-left](https://docs.symm.io/options-protocol-architecture/core-financial-concepts) [NextBalance Operations (Deposit, Withdraw, Transfers)chevron-right](https://docs.symm.io/options-protocol-architecture/technical-architecture/balance-operations-deposit-withdraw-transfers) Last updated 4 months ago * [Diamond Pattern Implementation](https://docs.symm.io/options-protocol-architecture/technical-architecture#diamond-pattern-implementation) * [Storage Architecture](https://docs.symm.io/options-protocol-architecture/technical-architecture#storage-architecture) * [Facet Organization](https://docs.symm.io/options-protocol-architecture/technical-architecture#facet-organization) sun-brightdesktopmoon sun-brightdesktopmoon --- # Frontend Modifications | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/frontend-license/frontend-modifications#licensing) Licensing[​arrow-up-right](https://docs.uniswap.org/contracts/v3/guides/governance/liscense-modifications#licensing) - Please note that the SYMM FRONTEND (CLOVERFIELD) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- is under BUSL license until the Change Date, currently 31st of December 2025 Exceptions to the license may be specified by SYMMIO Governance or SYMMIO team via [Additional Use Grants](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/frontend-license/frontend-use-grants) , which can, for example, allow CLOVERFIELD to be deployed on new chains or be delivered to partners to host new Frontends. The process to request a DAO vote for exceptions to the license or move up the Change Date will be released soon. Modifications of the Change Date should be specified at [Frontend Modifications](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/frontend-license/frontend-modifications) and Additional Use Grants should be specified at [Frontend Use Grants](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/frontend-license/frontend-use-grants) [PreviousFRONTEND LICENSEchevron-left](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/frontend-license) [NextFrontend Use Grantschevron-right](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/frontend-license/frontend-use-grants) Last updated 2 years ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Frontend Use Grants | SYMMIO Protocol Gitbook The Licensor hereby grants these projects, with the respective domain addresses the right to copy, modify, create derivative works, redistribute, and make production use of the Licensed Work. * ALPHA by [https://thena.fi arrow-up-right](https://thena.fi/) * PEAR by [https://www.pear.garden/arrow-up-right](https://www.pear.garden/) * BASED MARKETS by [https://trade.based.marketsarrow-up-right](https://www.based.markets/) * DAO Maker Wallet by [https://daomaker.com/arrow-up-right](https://daomaker.com/) * Ramses & Cleo by [https://www.ramses.exchange/arrow-up-right](https://www.ramses.exchange/) * Chronos by [https://chronos.exchange/arrow-up-right](https://chronos.exchange/) * IntentX by [https://app.intentx.ioarrow-up-right](https://app.intentx.io/) * Magma by [Magma Financearrow-up-right](https://twitter.com/magma_fi) * Ape Terminal by Ape Better Technologies * ZkZero by Stabl-Labs * Retro Finance by Stabl-Labs * SwapBased Finance by [https://swapbased.financearrow-up-right](https://swapbased.finance/) [PreviousFrontend Modificationschevron-left](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/frontend-license/frontend-modifications) [NextCONTRACT LICENSEchevron-right](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/contract-license) Last updated 2 years ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Rasa Solver TP/SL Implementation | SYMMIO Protocol Gitbook Rasa’s conditional orders handler lets you set take-profit and stop-losses to an existing position. Instead of polling and closing positions manually, you send a conditional order to Rasa and it will automatically request the close when your trigger price is hit. This version of the API: * Uses the **instant trading login flow** (no more manual JSON signing) * Requires **MultiAccount delegation** so Rasa can request closes on your behalf * Supports **multiple conditional orders per quote** (e.g. one TP and one SL) **Base URL** Copy https://conditional-orders-handler.rasa.capital/api/v4/ Before sending TP/SL orders, you must have: 1. **MultiAccount delegation set up** In your MultiAccount, you must delegate at least the following functions to the [Rasa PartyB address](https://docs.symm.io/protocol-architecture/solver-addresses-and-endpoints) : * `requestToClosePosition(``**0x501e891f**``)` * `requestToCancelCloseRequest(``**0xa63b9363**``)` This lets Rasa submit/modify close requests on your sub-account when the TP/SL triggers. 1. **Instant trading login (Bearer token)** You must log in to the Rasa hedger using the **instant trading** flow (SIWE) and obtain an `access_token`. * See: [_Instant Trading / Login with Hedger_](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading) . * That token will be sent as `Authorization: Bearer ` when you call the conditional orders API. 2. **An open SYMMIO position (quote)** * You need a valid `quote_id` from an existing open position. * You must know: * `account_address` (PartyA sub-account) * `symbol_id` * `multi_account_address` * Rasa PartyB address for the chain (goes in `hedger_whitelist`). [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/rasa-solver-tp-sl-implementation#post-api-v4) POST api/v4/ ----------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/rasa-solver-tp-sl-implementation#request-payload) Request Payload Example payload for **one TP and one SL** on the same quote: * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/rasa-solver-tp-sl-implementation#request-fields) Request Fields: * `**account_address:**` PartyA sub-account address for this position (the MultiAccount child that owns the quote). * `**quote_id:**` The SYMMIO quote ID you want to attach TP/SL to (must be OPEN). * `**symbol_id:**` The SYMMIO symbol ID (e.g. XRP = `4` in your example). * `**multi_account_address:**` The MultiAccount contract address deployed by a frontend builder. * `**hedger_whitelist**` Array of PartyB addresses allowed to execute these conditional orders. For Rasa on Base, this is their PartyB address: * `**conditional_orders**` Array of TP/SL instructions for this quote. You can send one or multiple (e.g. one TP + one SL). #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/rasa-solver-tp-sl-implementation#conditional_orders-object) `conditional_orders[]` object Each object describes a single TP or SL: * `**quantity**` **(string) —** How much of the position should be closed when this order triggers. * `**price**` **(string)** – This is the **minimum price you’re willing to accept when closing**, after slippage. * For **LONGS**, a common pattern is: e.g. for 10% slippage: `price = conditional_price * 0.9` * For **SHORTS**, the direction is inverted: e.g. for 10% slippage: `price = conditional_price * 1.1` The solver will only close the trade if it can get at least this price (for longs) or at most this price (for shorts). * `**conditional_price**` **(string)** – The price level at which this TP/SL should attempt to close. * `**conditional_price_type**` **(string) —** How the trigger price is interpreted: * `"last_close"` – use the last close price feed for that symbol. * `"market`" — uses the market price for that symbol * `**order_type**` **(number) —** Order type used when closing: `1` for market orders, `2` for limit. * `**position_type**` **(number) —** The direction of the position: `0` – Long, `1` – Short. This is important because TP and SL logic, as well as slippage direction, depend on whether the position is long or short. * `**conditional_order_type**` **(string)** * `"take_profit"` – close when price moves **in your favor** to lock in gains. * `"stop_loss"` – close when price moves **against you** to cap losses. * `**leverage**` **(number)** The leverage used for the position. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/rasa-solver-tp-sl-implementation#authentication-and-headers) Authentication & Headers Before calling the conditional-orders API, you must **log in** to Rasa using the [instant-trading login](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/building-an-application-with-symmio/instant-trading/instant-login-eoa) flow and obtain an `access_token`. When sending the request: ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/rasa-solver-tp-sl-implementation#flow-summary) Flow Summary 1. **Delegate permissions** via MultiAccount: Allow Rasa’s PartyB address to call `requestToClosePosition` and `requestToCancelCloseRequest` for your sub-account. 2. **Login to Rasa** via the instant-trading flow and get a Bearer token. 3. **Build your conditional orders payload** 4. **POST the payload** with the `Authorization: Bearer ` header. 5. When the market reaches your `conditional_price` and execution is possible above/below your `price` threshold. * * * [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/rasa-solver-tp-sl-implementation#get-api-v4-quote_id) GET /api/v4/{quote\_id}/ ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- You can query which TP/SL (or other conditional) orders are currently registered for a quote. **Endpoint** **Path params** * `quote_id` – the SYMMIO quote ID you want to inspect. **Example response** * * * [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/rasa-solver-tp-sl-implementation#delete-api-v4-quote_id-conditional_order_type) DELETE /api/v4/{quote\_id}/{conditional\_order\_type} -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- You can remove an existing TP, SL, or other conditional order for a quote. **Endpoint** **Path params** * `quote_id` – the quote ID of the conditional order you want to cancel. * `conditional_order_type` – one of: * `take_profit` * `stop_loss` This will cancel **that specific type** of conditional order for the quote. For example: * Cancel only the stop loss for quote `179921`: * Cancel the take profit: [PreviousConditional Orderschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders) [NextPerpsHub TP/SL Implementationchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/perpshub-tp-sl-implementation) Last updated 1 month ago * [POST api/v4/](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/rasa-solver-tp-sl-implementation#post-api-v4) * [Request Payload](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/rasa-solver-tp-sl-implementation#request-payload) * [Request Fields:](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/rasa-solver-tp-sl-implementation#request-fields) * [Authentication & Headers](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/rasa-solver-tp-sl-implementation#authentication-and-headers) * [Flow Summary](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/rasa-solver-tp-sl-implementation#flow-summary) * [GET /api/v4/{quote\_id}/](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/rasa-solver-tp-sl-implementation#get-api-v4-quote_id) * [DELETE /api/v4/{quote\_id}/{conditional\_order\_type}](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/rasa-solver-tp-sl-implementation#delete-api-v4-quote_id-conditional_order_type) sun-brightdesktopmoon Copy { "account_address": "0xB6492A3963DDa0910329787478df3Bb02C7b0DA3", "quote_id": 179921, "conditional_orders": [\ {\ "quantity": "7.2",\ "price": "1.9683",\ "conditional_price": "2.1870",\ "conditional_price_type": "last_close",\ "order_type": 1,\ "position_type": 0,\ "conditional_order_type": "take_profit",\ "leverage": 1\ },\ {\ "quantity": "7.2",\ "price": "1.7808",\ "conditional_price": "1.9787",\ "conditional_price_type": "last_close",\ "order_type": 1,\ "position_type": 0,\ "conditional_order_type": "stop_loss",\ "leverage": 1\ }\ ], "symbol_id": 4, "multi_account_address": "0x95605c64356572eb5C076Cb9c027c88b527A2059", "hedger_whitelist": [\ "0x9206D9d8F7F1B212A4183827D20De32AF3A23c59"\ ] } Copy "hedger_whitelist": ["0x9206D9d8F7F1B212A4183827D20De32AF3A23c59"] Copy price = conditional_price * (1 - slippage) Copy price = conditional_price * (1 + slippage) Copy POST https://conditional-orders-handler.rasa.capital/api/v4/ Content-Type: application/json Accept: application/json App-Name: Cloverfield # App Name Authorization: Bearer Copy GET https://conditional-orders-handler.rasa.capital/api/v4/{quote_id}/ Authorization: Bearer Accept: application/json Copy [\ {\ "quote_id": 179967,\ "party_a_address": "0xB6492A3963DDa0910329787478df3Bb02C7b0DA3",\ "symbol_id": 4,\ "conditional_order_type": "take_profit",\ "quantity": 7.2,\ "price": 2.2513,\ "conditional_order_price": 2.0466,\ "order_type": 1,\ "state": "new",\ "action_price_type": "last_close",\ "position_type": 1\ }\ ] Copy DELETE https://conditional-orders-handler.rasa.capital/api/v4/{quote_id}/{conditional_order_type} Authorization: Bearer Accept: application/json Copy DELETE https://conditional-orders-handler.rasa.capital/api/v4/179921/stop_loss Authorization: Bearer Copy DELETE https://conditional-orders-handler.rasa.capital/api/v4/179921/take_profit Authorization: Bearer sun-brightdesktopmoon --- # Vaults | SYMMIO Protocol Gitbook Audit: [https://audits.sherlock.xyz/contests/144arrow-up-right](https://audits.sherlock.xyz/contests/144) [PreviousSherlock Audit - Oct 3, 2024chevron-left](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-0.84/sherlock-audit-oct-3-2024) [NextSherlock Audit - Jan 2, 2024chevron-right](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/vaults/sherlock-audit-jan-2-2024) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # SymmioPartyB Contract | SYMMIO Protocol Gitbook The `SymmioPartyB` contract is the core **execution proxy** for Party B actors. It provides **secure routing**, **multi-call support**, and **fine-grained permissioning** for interactions with the Symmio core contracts. This contract allows Party B to batch trade operations, authorize token flows, and interface with both internal and whitelisted external contracts. [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/symmiopartyb-contract#core-functions) **Core Functions** ------------------------------------------------------------------------------------------------------------------------------------------------------------------ ### [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/symmiopartyb-contract#symmio-call-dispatcher) 🔹 **Symmio Call Dispatcher** Copy function _call(bytes[] calldata callDatas) external; Forwards multiple encoded calls to the Symmio core (e.g., opening or closing trades). Enforces selector-level permissions: * `restrictedSelectors[sel] == true`: requires `MANAGER_ROLE` * otherwise: `TRUSTED_ROLE` or `InstantLayer` delegate is sufficient Reverts if any call fails. ### [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/symmiopartyb-contract#multicast-executor) 🔹 **Multicast Executor** Copy function _multicastCall( address[] calldata dests, bytes[] calldata datas ) external; Sends parallel external calls to approved targets. All destination contracts must be whitelisted. Requires `TRUSTED_ROLE`. ### [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/symmiopartyb-contract#token-management) 🔹 **Token Management** Sets Symmio token allowances. Callable by `TRUSTED_ROLE`. Withdraws tokens to the caller. Restricted to `MANAGER_ROLE`. ### [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/symmiopartyb-contract#configuration-functions) 🔹 **Configuration Functions** Marks a core selector as restricted to `MANAGER_ROLE`. Controls which external contracts can be called via `_multicastCall`. Updates the ERC-1271 signer address used for off-chain validation. ### [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/symmiopartyb-contract#signature-verification) 🔹 **Signature Verification** Returns `0x1626ba7e` if signature is valid; otherwise `0xffffffff`. ### [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/symmiopartyb-contract#emergency-controls) 🔹 **Emergency Controls** Enables or disables contract functions under emergency conditions. Controlled via `PAUSER_ROLE` / `UNPAUSER_ROLE`. Once the cooldown period has elapsed, the withdrawal can be finalized: [PreviousInstantLayer Contractchevron-left](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/instantlayer-contract) [NextContract Addresseschevron-right](https://docs.symm.io/options-protocol-architecture/contract-addresses) Last updated 4 months ago * [Core Functions](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/symmiopartyb-contract#core-functions) * [🔹 Symmio Call Dispatcher](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/symmiopartyb-contract#symmio-call-dispatcher) * [🔹 Multicast Executor](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/symmiopartyb-contract#multicast-executor) * [🔹 Token Management](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/symmiopartyb-contract#token-management) * [🔹 Configuration Functions](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/symmiopartyb-contract#configuration-functions) * [🔹 Signature Verification](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/symmiopartyb-contract#signature-verification) * [🔹 Emergency Controls](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/symmiopartyb-contract#emergency-controls) sun-brightdesktopmoon Copy function _approve(address token, uint256 amount) external; Copy function withdrawERC20(address token, uint256 amount) external; Copy function setRestrictedSelector(bytes4 sel, bool state) external; Copy function setMulticastWhitelist(address addr, bool state) external; Copy function setSigner(address newSigner) external; Copy function isValidSignature( bytes32 hash, bytes calldata sig ) external view returns (bytes4); Copy function pause() external; function unpause() external; Copy function completeWithdraw(uint256 id) sun-brightdesktopmoon --- # Contract Modifications | SYMMIO Protocol Gitbook ### [hashtag](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/contract-license/contract-modifications#licensing) Licensing[​arrow-up-right](https://docs.uniswap.org/contracts/v3/guides/governance/liscense-modifications#licensing) Please note that the SYMM Core is under BUSL license until the Change Date, currently 12-31-2027. Exceptions to the license may be specified by SYMM Governance via [Additional Use Grants](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/contract-license/contract-use-grants) , which can, for example, allow the CORE to be deployed on new chains or be released in partnership with new Frontends. The process to request a DAO vote for exceptions to the license or move up the Change Date will be released soon. Modifications of the Change Date should be specified at [Contract Modifications](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/contract-license/contract-modifications) , and Additional Use Grants should be specified at [Contract Use Grants](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/contract-license/contract-use-grants) . [PreviousContract Use Grantschevron-left](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/contract-license/contract-use-grants) [NextBrand - Assets Logoschevron-right](https://docs.symm.io/legal-and-brand-and-security/brand-assets-logos) Last updated 2 years ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Sherlock Audit - Jun 17, 2024 | SYMMIO Protocol Gitbook [![Logo](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2Faudits.sherlock.xyz%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=87b6773d&sv=2)SYMMIO v0.83 Update Contest Contest - 27,500 USDCaudits.sherlock.xyzchevron-right](https://audits.sherlock.xyz/contests/427) circle-info Sherlock is an audit marketplace and smart contract coverage protocol built on the Ethereum blockchain. Sherlock works to protect Decentralized Finance (DeFi) users from smart contract exploits with security reviews from top auditors backed by smart contract coverage on the audited contracts. You can find a brief overview of the Sherlock ecosystem below. [https://docs.sherlock.xyz/arrow-up-right](https://docs.sherlock.xyz/) View findings: [https://github.com/sherlock-audit/2024-06-symmetrical-update-2-judging/issuesarrow-up-right](https://github.com/sherlock-audit/2024-06-symmetrical-update-2-judging/issues) Audit report: [https://audits.sherlock.xyz/contests/427/reportarrow-up-right](https://audits.sherlock.xyz/contests/427/report) [PreviousSYMM - 0.83chevron-left](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-0.83) [NextSYMM - 0.84chevron-right](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-0.84) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # SYMM - 0.83 | SYMMIO Protocol Gitbook [Sherlock Audit - Jun 17, 2024chevron-right](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-0.83/sherlock-audit-jun-17-2024) [PreviousSherlock Audit -Aug 30, 2023chevron-left](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-0.82/sherlock-audit-aug-30-2023) [NextSherlock Audit - Jun 17, 2024chevron-right](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-0.83/sherlock-audit-jun-17-2024) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Sherlock Audit - Mar 7, 2025 | SYMMIO Protocol Gitbook [![Logo](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2Faudits.sherlock.xyz%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=87b6773d&sv=2)Symmio, Staking and Vesting Contest - 17,500 USDCaudits.sherlock.xyzchevron-right](https://audits.sherlock.xyz/contests/838) circle-info Sherlock is an audit marketplace and smart contract coverage protocol built on the Ethereum blockchain. Sherlock works to protect Decentralized Finance (DeFi) users from smart contract exploits with security reviews from top auditors backed by smart contract coverage on the audited contracts. You can find a brief overview of the Sherlock ecosystem below. [https://docs.sherlock.xyz/arrow-up-right](https://docs.sherlock.xyz/) View findings: [https://github.com/sherlock-audit/2025-03-symm-io-stacking-judging/issuesarrow-up-right](https://github.com/sherlock-audit/2025-03-symm-io-stacking-judging/issues) Audit report: [https://audits.sherlock.xyz/contests/838/reportarrow-up-right](https://audits.sherlock.xyz/contests/838/report) [PreviousStaking and Vestingchevron-left](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/staking-and-vesting) [NextTerms of Service & Licensingchevron-right](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing) Last updated 7 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Frontend Builder Introduction | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/frontend-builder-introduction#introduction) Introduction ------------------------------------------------------------------------------------------------------------------------------------------- At its core, Symmio is designed with a critical perspective on regulatory restrictions and a thorough commitment to censorship resistance of our core aMFQ technology. Consequently, we do not host any front end. Instead, we focus on providing the crucial technical infrastructure required for executing aMFQ peer-to-peer (p2p) symmetrical trades. Notably, while we provide the technology necessary for these transactions, we do not employ it to establish markets or extend market offerings to users. Traders should use one of our [3rd party frontend applications to trade SYMMIO markets.arrow-up-right](https://symm.io/frontends) ### [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/frontend-builder-introduction#business-to-business-b2b) Business-to-Business (B2B) Symmio adopted a strict business-to-business (B2B) approach in our operations for various reasons. Our infrastructure is exclusively offered to developers and exchanges, enabling them to tap into the potential of decentralized finance without dealing with the complexities of backend development. We recommend exploring our [Profit Sharing Model](https://docs.symm.io/building-on-symmio/trading-fees/perps-settlement-costs) for parties interested in launching a Symmio front end and creating their infinite array of markets using the Symmio Tech Stack. ### [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/frontend-builder-introduction#simply-integrate-with-us) Simply integrate with us Symmio offers a comprehensive perpetual exchange infrastructure that can be effortlessly integrated into your existing or newly built exchange. The complete functionality found on [https://cloverfield.exchange/trade/BTCUSDTarrow-up-right](https://cloverfield.exchange/trade/BTCUSDT) (Symmio demo frontend) can be easily incorporated into your platform through forking our complete code base by getting a [Frontend Use Grants](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/frontend-license/frontend-use-grants) or using our [SDK - SYMM client](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/sdk-symm-client) , streamlining the process for seamless integration. For further information on deploying a frontend application, refer to the [Documentation for Frontend Builders](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders) Symmio effectively circumvents liquidity fragmentation often associated with forking projects and concepts, such as vAMM-based perps (e.g., GMX, Gains) or OrderBook-based (e.g., DyDx). By providing access to an extensive pool of institutionally-backed liquidity providers, known as "Hedgers" in Symmio, the user experience is significantly enhanced through Liquidity aggregation instead of fragmentation. Please do not hesitate to contact us for further information or support. [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/frontend-builder-introduction#disclaimer) Disclaimer --------------------------------------------------------------------------------------------------------------------------------------- circle-info #### [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/frontend-builder-introduction#decentralized-frontends) Decentralized Frontend Applications In our quest of making the system more decentralized and censorship-resistant. Symmio itself doesn't offer any trading or promote the trading of any derivatives; Symmio only provides the infrastructure for symmetrical peer-to-peer matchmaking; 3rd party providers can use that to build a fully functional on-chain derivatives exchange. Frontend Builders (Dealers and Market Makers) offer services directly via 3rd party services. To see their offering, make deposits, request trades, etc. Users thus have to use one of the frontends provided by third parties.​ [#https://symm.io/frontendsarrow-up-right](https://symm.io/frontends) #### [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/frontend-builder-introduction#which-frontend-do-i-pick) Which Frontend do I pick? Deciding which Frontend to use is a personal decision based on various factors, including UI, UX, features, tools, and the Frontend Operator's liquidity on the platform or offering of products and assets.​ #### [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/frontend-builder-introduction#list-disclaimer) List Disclaimer Frontend Operators provide descriptions. The list of Frontend Operators is provided for informational purposes only. Neither is the list conclusive nor has Symmetry Labs AG conducted any due diligence on these operators. Accordingly, Symmetry Labs AG does not make any statement regarding technical functionality and the trustworthiness of the Frontend Operators listed below. #### [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/frontend-builder-introduction#decentralized-frontends-1) [PreviousExchanges (Frontend Builders)chevron-left](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders) [NextSDK - SYMM clientchevron-right](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/sdk-symm-client) Last updated 2 months ago * [Introduction](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/frontend-builder-introduction#introduction) * [Business-to-Business (B2B)](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/frontend-builder-introduction#business-to-business-b2b) * [Simply integrate with us](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/frontend-builder-introduction#simply-integrate-with-us) * [Disclaimer](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/frontend-builder-introduction#disclaimer) sun-brightdesktopmoon sun-brightdesktopmoon --- # SYMM - 0.84 | SYMMIO Protocol Gitbook [Sherlock Audit - Oct 3, 2024chevron-right](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-0.84/sherlock-audit-oct-3-2024) [PreviousSherlock Audit - Jun 17, 2024chevron-left](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-0.83/sherlock-audit-jun-17-2024) [NextSherlock Audit - Oct 3, 2024chevron-right](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-0.84/sherlock-audit-oct-3-2024) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # GET Price Range | SYMMIO Protocol Gitbook ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-price-range#price-range) /price-range Copy /price-range/{symbol} **Example Query:** Copy https://base-hedger82.rasa.capital/price-range/BTCUSDT **Example Response:** Copy { "min_price": "1113.60", "max_price": "754960.6666666666666666666668176588" } #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-price-range#data-source) **Data Source** The `min_price` and `max_price` are configured by the hedger but **must align with the price range** of the external exchange where the hedger is actively hedging (e.g., Binance, Bybit). `**min_price**`: The minimum acceptable order price for the symbol (in quote currency, e.g., USDT). Derived from the external exchange’s current price floor or liquidity constraints. * Example: `"1113.60"` → Orders below this price are rejected. `**max_price**`: The maximum acceptable order price for the symbol. Reflects the hedging platform’s upper price limit. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-price-range#price-range-implementation-rasa) Price Range Implementation (Rasa) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-price-range#router) Router * Reads the exchange’s order-book or recent trades (via the Binance API or a cached copy). * Computes a safe **min\_price** (floor) and **max\_price** (ceiling) for new orders. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-price-range#steps-to-implement-your-own-version) Steps to Implement Your Own Version **Define the Response Schema** **Build Your Condition-Checks Utility** * Implement `BinanceConditionChecks.get_price_bounds(symbol, from_stats)` to return a tuple `(_, _, min_price, max_price)`. **Add the FastAPI Route** * In `common_router`, register the `GET /price-range/{symbol}` endpoint as shown above. * Import `symbol_enum` for the path parameter (a class containing all Symbol names), and `SymbolPriceRangeInputSchema` for the response. [PreviousGET Notional Capchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-notional-cap) [NextGET Error Codeschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-error-codes) Last updated 9 months ago * [/price-range](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-price-range#price-range) * [Price Range Implementation (Rasa)](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-price-range#price-range-implementation-rasa) * [Router](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-price-range#router) sun-brightdesktopmoon Copy @common_router.get( '/price-range/{symbol}', responses={status.HTTP_200_OK: {"model": SymbolPriceRangeInputSchema}}, response_model=SymbolPriceRangeInputSchema ) async def get_symbol_price_range(symbol: symbol_enum): # 1. Compute safe order-price bounds from the exchange _, _, min_price, max_price = BinanceConditionChecks.get_price_bounds(symbol, from_stats=True) # 2. Return JSON matching SymbolPriceRangeInputSchema return { "min_price": min_price, "max_price": max_price } Copy class SymbolPriceRangeInputSchema(BaseModel): min_price: Decimal max_price: Decimal sun-brightdesktopmoon --- # Funding Rate Facet (0.8.4) | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/funding-rate-facet-0.8.4#funding-rate-facet) Funding Rate Facet ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- The **Funding Rate Facet** is responsible for applying periodic funding rate adjustments to open positions. Funding rates reflect the cost or gain from holding a position over time and are applied in discrete epochs defined on a per‑symbol basis. This facet adjusts the open price of a quote and updates the available balances for both Party A and Party B accordingly. > **Key Concepts:** > > * **Epoch Duration:** Each symbol defines a funding epoch (epochDuration), which is the total period between funding rate applications. > > * **Window Time:** A designated time window (windowTime) within each epoch during which the funding rate can be applied. > > * **Price Adjustments:** The open price is adjusted by a factor derived from the funding rate. For long positions, a positive rate increases the price (and vice versa for short positions), while a negative rate applies the opposite adjustment. > > * **Event Logging:** The adjustment process emits a `ChargeFundingRate` event, capturing the key parameters involved in the funding rate charge. > * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/funding-rate-facet-0.8.4#overview) Overview The primary function in this facet is **chargeFundingRate()**. It is called with an array of quote IDs and corresponding funding rates. For each quote, the function: 1. Verifies the UPnL data using a Muon signature. 2. Retrieves funding epoch parameters (`epochDuration` and `windowTime`) from the symbol settings. 3. Determines the appropriate funding payment timestamp based on the current block timestamp. 4. Adjusts the open price of the quote by calculating a price difference based on the funding rate. 5. Updates the available balances for Party A and Party B. 6. Increments nonce counters to maintain state consistency. After processing, the function emits a `ChargeFundingRate` event. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/funding-rate-facet-0.8.4#chargefundingrate) chargeFundingRate() The `chargeFundingRate` function adjusts the open price of one or more quotes for a given Party A, based on an array of funding rates. It ensures that adjustments occur only within a designated time window (derived from the epoch duration and window time settings) and that the resulting balance changes do not render either party insolvent. **Function Signature:** **Parameters:** * **partyA:** The address of Party A whose quotes will be adjusted. * **quoteIds:** An array of quote IDs to be processed. * **rates:** An array of funding rates (as signed integers) corresponding to each quote. * **upnlSig:** A structure containing UPnL signature data for both parties; used for verification. **Example Usage:** **Internal Logic:** * **UPnL Verification:** The function starts by verifying the provided UPnL data using `LibMuonFundingRate.verifyPairUpnl`. * **Funding Epoch Calculation:** For each quote, it retrieves: * `epochDuration` from the symbol storage mapping `SymbolStorage.layout().symbols[quote.symbolId].fundingRateEpochDuration` * `windowTime` from the symbol storage mapping `SymbolStorage.layout().symbols[quote.symbolId].fundingRateWindowTime` It then computes the `latestEpochTimestamp` as: * **Price Adjustment:** A price difference is calculated: The open price is then adjusted (increased or decreased) based on the position type and the sign of the funding rate. The funding rate charge is embedded into the openedPrice of the quote. * **Balance Updates:** The available balances for Party A and Party B are updated based on the price difference and the open amount of the quote. * **Final Checks:** The function ensures that both parties remain solvent, then increments nonce counters in AccountStorage. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/funding-rate-facet-0.8.4#epoch-timestamps-and-window-time) Epoch Timestamps and Window Time For each quote, the function calculates the funding epoch details: * **Epoch Duration:** Determines how often funding adjustments are applied. Retrieved from the symbol configuration. * **Window Time:** Specifies the time window within an epoch when adjustments are allowed. * **Latest Epoch Timestamp:** Calculated as: * **Paid Timestamp:** Depending on the current block time relative to the window, the function determines whether to use the latest epoch timestamp or the next epoch timestamp as the effective payment timestamp. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/funding-rate-facet-0.8.4#price-adjustments-and-balance-updates) Price Adjustments and Balance Updates Once the appropriate funding payment timestamp is determined, the function: **Calculates Price Difference:** For a positive funding rate: * Long positions: `quote.openedPrice` is increased. * Short positions: `quote.openedPrice` is decreased. For a negative funding rate, the adjustments are reversed. **Updates Balances:** The function deducts or credits the calculated monetary impact from Party A's and Party B's available balances. **Nonce Updates:** Nonce counters for Party A and Party B are incremented to prevent replay attacks. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/funding-rate-facet-0.8.4#funding-events) Funding Events **Event Emitted:** After processing, the function emits the `ChargeFundingRate` event, defined as follows: * **partyB:** The address of the caller (typically Party B). * **partyA:** The address of Party A whose quotes are adjusted. * **quoteIds:** The array of quote IDs for which funding rates were charged. * **rates:** The corresponding array of funding rates applied. This event provides a transparent log of all funding rate adjustments applied through the `chargeFundingRate` function. **Contract-Level Code Snippet:** [PreviousForce Actions Facet (0.8.4)chevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/force-actions-facet-0.8.4) [NextLiquidations Facet (0.8.4)chevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/liquidations-facet-0.8.4) Last updated 11 months ago * [Funding Rate Facet](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/funding-rate-facet-0.8.4#funding-rate-facet) * [Overview](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/funding-rate-facet-0.8.4#overview) * [chargeFundingRate()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/funding-rate-facet-0.8.4#chargefundingrate) * [Epoch Timestamps and Window Time](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/funding-rate-facet-0.8.4#epoch-timestamps-and-window-time) * [Price Adjustments and Balance Updates](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/funding-rate-facet-0.8.4#price-adjustments-and-balance-updates) * [Funding Events](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.4/facets/funding-rate-facet-0.8.4#funding-events) sun-brightdesktopmoon Copy function chargeFundingRate( address partyA, uint256[] memory quoteIds, int256[] memory rates, PairUpnlSig memory upnlSig ) external whenNotPartyBActionsPaused notLiquidatedPartyA(partyA); Copy // Example: Adjust funding rates for multiple quotes for Party A address partyA = 0x...; uint256[] memory quotes = new uint256[](2); quotes[0] = 101; quotes[1] = 102; int256[] memory fundingRates = new int256[](2); fundingRates[0] = 50000000000000000; // 0.05 (in 1e18 precision) fundingRates[1] = -30000000000000000; // -0.03 (in 1e18 precision) PairUpnlSig memory upnlSig = /* obtain verified signature data */; fundingRateFacet.chargeFundingRate(partyA, quotes, fundingRates, upnlSig); Copy uint256 latestEpochTimestamp = (block.timestamp / epochDuration) * epochDuration; Copy uint256 priceDiff = (quote.openedPrice * uint256(rates[i])) / 1e18; Copy uint256 latestEpochTimestamp = (block.timestamp / epochDuration) * epochDuration; Copy require(block.timestamp >= nextEpochTimestamp - windowTime, "ChargeFundingFacet: Current timestamp is out of window"); require(nextEpochTimestamp > quote.lastFundingPaymentTimestamp, "ChargeFundingFacet: Funding already paid for this window"); Copy event ChargeFundingRate(address partyB, address partyA, uint256[] quoteIds, int256[] rates); Copy contract FundingRateFacet is Accessibility, Pausable, IFundingRateFacet { function chargeFundingRate( address partyA, uint256[] memory quoteIds, int256[] memory rates, PairUpnlSig memory upnlSig ) external whenNotPartyBActionsPaused notLiquidatedPartyA(partyA) { FundingRateFacetImpl.chargeFundingRate(partyA, quoteIds, rates, upnlSig); emit ChargeFundingRate(msg.sender, partyA, quoteIds, rates); } } sun-brightdesktopmoon --- # MuonStorage | SYMMIO Protocol Gitbook The `MuonStorage` contract is designed to help facilitate the verification of data related to trading. It outlines the structure of various signatures and configurations. [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/symm-app-muon/muonstorage#structs) **Structs** ------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/symm-app-muon/muonstorage#schnorrsign) **SchnorrSign** Represents a Schnorr signature, which is used for cryptographic verification of transactions and data. It includes: Copy struct SchnorrSign { uint256 signature; address owner; address nonce; } * `signature`: The actual signature. * `owner`: The address of the owner who generated the signature. * `nonce`: An additional parameter used to ensure the uniqueness of the signature, preventing replay attacks. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/symm-app-muon/muonstorage#publickey) **PublicKey** Represents a public key used in cryptographic operations. Copy struct PublicKey { uint256 x; uint8 parity; } * `x`: The x-coordinate of the public key on the elliptic curve. * `parity`: Indicates the parity of the y-coordinate of the public key, which helps in recovering the full public key from the x-coordinate alone. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/symm-app-muon/muonstorage#singleupnlsig) **SingleUpnlSig** Stores the signature for a single unrealized profit and loss (uPnl) computation. * `reqId`: A unique identifier for the request. * `timestamp`: The timestamp when the signature was generated. * `upnl`: The unrealized profit or loss. * `gatewaySignature`: Additional security layer provided by a gateway signature. * `sigs`: Embedded Schnorr signature for verification. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/symm-app-muon/muonstorage#singleupnlandpricesig) **SingleUpnlAndPriceSig** Extends `SingleUpnlSig` by adding price information, used for verifying computations involving both uPnl and asset prices. * `price`: The price of the asset. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/symm-app-muon/muonstorage#pairupnlsig) **PairUpnlSig** Contains signatures for calculations involving two parties (PartyA and PartyB). * `upnlPartyA` and `upnlPartyB`: uPnl values for both parties. * Includes all other fields from `SingleUpnlSig`. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/symm-app-muon/muonstorage#pairupnlandpricesig) **PairUpnlAndPriceSig:** Combines features of `PairUpnlSig` and `SingleUpnlAndPriceSig` for scenarios where both uPnl calculations and price verifications are necessary for two parties. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/symm-app-muon/muonstorage#liquidationsig) **LiquidationSig:** Signature struct specifically designed for use in liquidation scenarios. * `liquidationId`: Identifier for the specific liquidation event. * `totalUnrealizedLoss`: Represents the total unrealized loss leading to liquidation. * `symbolIds` and `prices`: Lists of symbol identifiers and their corresponding prices involved in the liquidation. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/symm-app-muon/muonstorage#quotepricesig) **QuotePriceSig:** Utilized for verifying the prices of multiple quotes in a single operation. * `quoteIds`: List of quote identifiers. * `prices`: Corresponding prices for the quotes. [PreviousLibMuonchevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/symm-app-muon/libmuon) [NextContracts Documentation 0.8.3chevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3) Last updated 1 year ago * [Structs](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/symm-app-muon/muonstorage#structs) * [SchnorrSign](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/symm-app-muon/muonstorage#schnorrsign) * [PublicKey](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/symm-app-muon/muonstorage#publickey) * [SingleUpnlSig](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/symm-app-muon/muonstorage#singleupnlsig) * [SingleUpnlAndPriceSig](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/symm-app-muon/muonstorage#singleupnlandpricesig) * [PairUpnlSig](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/symm-app-muon/muonstorage#pairupnlsig) * [PairUpnlAndPriceSig:](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/symm-app-muon/muonstorage#pairupnlandpricesig) * [LiquidationSig:](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/symm-app-muon/muonstorage#liquidationsig) * [QuotePriceSig:](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/symm-app-muon/muonstorage#quotepricesig) sun-brightdesktopmoon Copy struct SingleUpnlSig { bytes reqId; uint256 timestamp; int256 upnl; bytes gatewaySignature; SchnorrSign sigs; } Copy struct SingleUpnlAndPriceSig { bytes reqId; uint256 timestamp; int256 upnl; uint256 price; bytes gatewaySignature; SchnorrSign sigs; } Copy struct PairUpnlSig { bytes reqId; uint256 timestamp; int256 upnlPartyA; int256 upnlPartyB; bytes gatewaySignature; SchnorrSign sigs; } Copy struct PairUpnlAndPriceSig { bytes reqId; uint256 timestamp; int256 upnlPartyA; int256 upnlPartyB; uint256 price; bytes gatewaySignature; SchnorrSign sigs; } Copy struct LiquidationSig { bytes reqId; uint256 timestamp; bytes liquidationId; int256 upnl; int256 totalUnrealizedLoss; uint256[] symbolIds; uint256[] prices; bytes gatewaySignature; SchnorrSign sigs; } Copy struct QuotePriceSig { bytes reqId; uint256 timestamp; uint256[] quoteIds; uint256[] prices; bytes gatewaySignature; SchnorrSign sigs; } sun-brightdesktopmoon --- # Sherlock Audit - Jun 15, 2023 | SYMMIO Protocol Gitbook [![Logo](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2Faudits.sherlock.xyz%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=87b6773d&sv=2)Symmetrical Contest - 91,000 USDCaudits.sherlock.xyzchevron-right](https://audits.sherlock.xyz/contests/85) circle-info Sherlock is an audit marketplace and smart contract coverage protocol built on the Ethereum blockchain. Sherlock works to protect Decentralized Finance (DeFi) users from smart contract exploits with security reviews from top auditors backed by smart contract coverage on the audited contracts. You can find a brief overview of the Sherlock ecosystem below. [https://docs.sherlock.xyz/arrow-up-right](https://docs.sherlock.xyz/) View findings: [https://github.com/sherlock-audit/2023-06-symmetrical-judging/issuesarrow-up-right](https://github.com/sherlock-audit/2023-06-symmetrical-judging/issues) Audit report: [https://audits.sherlock.xyz/contests/85/reportarrow-up-right](https://audits.sherlock.xyz/contests/85/report) [PreviousSYMM - V0.8 - 0.81chevron-left](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-v0.8-0.81) [NextSmart State - Jul 2, 2023chevron-right](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/symm-v0.8-0.81/smart-state-jul-2-2023) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # PartyB | SYMMIO Protocol Gitbook The `SymmioPartyB` contract acts as a management contract for solvers or "Party B" . This contract allows for controlled interaction with the Symmio platform and external addresses for managing roles and permissions. [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partyb#constructor) **Constructor** --------------------------------------------------------------------------------------------------------------------------------------------------------------- Sets up initial state, disabling initializers to ensure proper contract upgrades. Copy /// @custom:oz-upgrades-unsafe-allow constructor constructor() { _disableInitializers(); } * **Operations**: Calls `_disableInitializers()` to prepare the contract for the upgrade-safe initialization pattern. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partyb#initialize) **initialize()** Properly initializes the contract with roles and the address of the Symmio platform. Copy function initialize(address admin, address symmioAddress_) public initializer { __Pausable_init(); __AccessControl_init(); _grantRole(DEFAULT_ADMIN_ROLE, admin); _grantRole(TRUSTED_ROLE, admin); _grantRole(MANAGER_ROLE, admin); symmioAddress = symmioAddress_; } **Parameters**: * `admin`: The administrator's address that will receive initial roles. * `symmioAddress_`: The address of the Symmio platform this contract will interact with. **Operations**: * Initializes the contract as pausable and with access control features. * Grants `DEFAULT_ADMIN_ROLE`, `TRUSTED_ROLE`, `MANAGER_ROLE`, `PAUSER_ROLE`, and `UNPAUSER_ROLE` to the admin. * Sets the initial Symmio address. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partyb#setsymmioaddress) **setSymmioAddress()** Updates the address of the Symmio platform to which calls are forwarded. **Access Control**: Only accessible by users with `DEFAULT_ADMIN_ROLE`. **Parameters**: * `addr`: New address for the Symmio platform. **Operations**: Updates `symmioAddress` and emits the `SetSymmioAddress` event. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partyb#setrestrictedselector) **setRestrictedSelector()** Manages access control by setting restrictions on specific function selectors. **Access Control**: Requires `DEFAULT_ADMIN_ROLE`. **Parameters**: * `selector`: The function selector to restrict or unrestrict. * `state`: Boolean value indicating whether the selector is restricted. **Operations**: Updates the `restrictedSelectors` mapping and emits the `SetRestrictedSelector` event. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partyb#setmulticastwhitelist) **setMulticastWhitelist()** Manages a whitelist of addresses allowed to be called through multicasting. This allows functions on multiple contracts to be called at the same time. * **Access Control**: Requires `MANAGER_ROLE`. * **Parameters**: * `addr`: The address to whitelist or remove from whitelist. * `state`: Boolean indicating whether to add (true) or remove (false) from the whitelist. * **Operations**: Updates the `multicastWhitelist` mapping and emits the `SetMulticastWhitelist` event. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partyb#approve) **\_approve()** Approves a token amount to the Symmio address. Only accessible by users with `TRUSTED_ROLE` and when the contract is not paused. **Parameters**: * `token`: ERC20 token address. * `amount`: Amount of tokens to approve. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partyb#executecall) **\_executeCall()** Executes a call to a specified address with provided call data. * **Parameters**: * `destAddress`: Destination address for the call. * `callData`: The data to be sent in the call. This function ensures that the destination address is not zero and that the call data is at least 4 bytes (minimum size for a function selector). Depending on the function selector extracted from the call data: * If the function is restricted (as per `restrictedSelectors`), the caller must have a `MANAGER_ROLE`. * Otherwise, either the `MANAGER_ROLE` or `TRUSTED_ROLE` is required. If the destination address is not the Symmio platform, it checks whether the address is whitelisted for calls. The call is made using the low-level `call` function, and successful execution is required; otherwise, it reverts. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partyb#call) **\_call()** Executes multiple calls to the Symmio address. Iterates over `_callDatas` and executes each using `_executeCall`. **Parameters**: * `_callDatas`: An array of call data bytes to be executed. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partyb#multicastcall) **\_multicastCall()** Enables the solver to interact with multiple contracts in a single transaction. It checks that the arrays of destination addresses and call data have the same length to ensure each address has corresponding call data then iterates through each address and associated call data, executing each via the `_executeCall` function. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partyb#withdrawerc20) **withdrawERC20()** Allows withdrawal of ERC20 tokens to the caller's address. Requires `MANAGER_ROLE` and transfers specified amount of tokens to the caller. * **Parameters**: * `token`: The ERC20 token address. * `amount`: The amount of tokens to withdraw. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partyb#pause-and-unpause) **pause() and unpause()** Controls the pausing and unpausing of the contract. Requires `PAUSER_ROLE` for pausing and `UNPAUSER_ROLE` for unpausing. [PreviousPartyAchevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partya) [NextSYMM App (Muon)chevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/symm-app-muon) Last updated 11 months ago * [Constructor](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partyb#constructor) * [initialize()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partyb#initialize) * [setSymmioAddress()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partyb#setsymmioaddress) * [setRestrictedSelector()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partyb#setrestrictedselector) * [setMulticastWhitelist()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partyb#setmulticastwhitelist) * [\_approve()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partyb#approve) * [\_executeCall()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partyb#executecall) * [\_call()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partyb#call) * [\_multicastCall()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partyb#multicastcall) * [withdrawERC20()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partyb#withdrawerc20) * [pause() and unpause()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.2/multiaccount/partyb#pause-and-unpause) sun-brightdesktopmoon Copy function setSymmioAddress(address addr) external onlyRole(DEFAULT_ADMIN_ROLE) { emit SetSymmioAddress(symmioAddress, addr); symmioAddress = addr; } Copy function setRestrictedSelector(bytes4 selector, bool state) external onlyRole(DEFAULT_ADMIN_ROLE) { restrictedSelectors[selector] = state; emit SetRestrictedSelector(selector, state); } Copy function setMulticastWhitelist(address addr, bool state) external onlyRole(MANAGER_ROLE) { require(addr != address(this), "SymmioPartyB: Invalid address"); multicastWhitelist[addr] = state; emit SetMulticastWhitelist(addr, state); } Copy function _approve(address token, uint256 amount) external onlyRole(TRUSTED_ROLE) whenNotPaused { require(IERC20Upgradeable(token).approve(symmioAddress, amount), "SymmioPartyB: Not approved"); } Copy function _executeCall(address destAddress, bytes memory callData) internal { require(destAddress != address(0), "SymmioPartyB: Invalid address"); require(callData.length >= 4, "SymmioPartyB: Invalid call data"); if (destAddress == symmioAddress) { bytes4 functionSelector; assembly { functionSelector := mload(add(callData, 0x20)) } if (restrictedSelectors[functionSelector]) { _checkRole(MANAGER_ROLE, msg.sender); } else { require(hasRole(MANAGER_ROLE, msg.sender) || hasRole(TRUSTED_ROLE, msg.sender), "SymmioPartyB: Invalid access"); } } else { require(multicastWhitelist[destAddress], "SymmioPartyB: Destination address is not whitelisted"); _checkRole(TRUSTED_ROLE, msg.sender); } (bool success, ) = destAddress.call{ value: 0 }(callData); require(success, "SymmioPartyB: Execution reverted"); } Copy function _call(bytes[] calldata _callDatas) external whenNotPaused { for (uint8 i; i < _callDatas.length; i++) _executeCall(symmioAddress, _callDatas[i]); } Copy function _multicastCall(address[] calldata destAddresses, bytes[] calldata _callDatas) external whenNotPaused { require(destAddresses.length == _callDatas.length, "SymmioPartyB: Array length mismatch"); for (uint8 i; i < _callDatas.length; i++) _executeCall(destAddresses[i], _callDatas[i]); } Copy function withdrawERC20(address token, uint256 amount) external onlyRole(MANAGER_ROLE) { require(IERC20Upgradeable(token).transfer(msg.sender, amount), "SymmioPartyB: Not transferred"); } Copy function pause() external onlyRole(PAUSER_ROLE) { _pause(); } function unpause() external onlyRole(UNPAUSER_ROLE) { _unpause(); } sun-brightdesktopmoon --- # InstantLayer Contract | SYMMIO Protocol Gitbook `InstantLayer` is Symmio’s **meta-transaction router**, built to allow **Party A and Party B** participants to submit pre-signed operations for **gas-free execution**. It securely bridges off-chain intent signing with on-chain execution through EIP-712 signatures and structured batching. The contract also supports **workflow templates**, where predefined sequences of operations can be reused with dynamic inputs. **Key Features** * **EIP-712 meta-tx support** with salt-based replay protection * **Nonce ordering** for increased signature safety * **Result chaining** between template steps * **Standalone batch execution** for unrelated ops * **Operator & admin roles** for access control * **Instant-mode toggling** for Party A automation [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/instantlayer-contract#core-functions) **Core Functions** ------------------------------------------------------------------------------------------------------------------------------------------------------------------ ### [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/instantlayer-contract#registration) 🔹 **Registration** Copy function registerPartyB(address partyB) external; function unregisterPartyB(address partyB) external; Manages execution privileges for Party B actors. Assigns or revokes `OPERATOR_ROLE`. Copy function registerMultiAccount(address multi) external; function unregisterMultiAccount(address multi) external; Whitelists or removes a `MultiAccount` contract. ### [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/instantlayer-contract#template-management) 🔹 **Template Management** Creates a reusable operation sequence (workflow template). Assigns a sequential `templateId`. Enables or disables existing templates without removing them. ### [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/instantlayer-contract#execution) 🔹 **Execution** Executes a template-based workflow. Verifies all signatures and steps. Allows result chaining between operations. Fully reverts on failure. Executes unrelated, independently signed operations in a batch. All must succeed. ### [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/instantlayer-contract#signature-utilities) 🔹 **Signature Utilities** Returns the EIP-712 domain-separated hash that off-chain signers must sign. Exposes the domain separator used in signature generation. [PreviousMultiAccount Contractchevron-left](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/multiaccount-contract) [NextSymmioPartyB Contractchevron-right](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/symmiopartyb-contract) Last updated 4 months ago * [Core Functions](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/instantlayer-contract#core-functions) * [🔹 Registration](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/instantlayer-contract#registration) * [🔹 Template Management](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/instantlayer-contract#template-management) * [🔹 Execution](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/instantlayer-contract#execution) * [🔹 Signature Utilities](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts/instantlayer-contract#signature-utilities) sun-brightdesktopmoon Copy function addTemplate(string calldata name, Operation[] calldata ops) external; Copy function setTemplateActive(uint256 templateId, bool active) external; Copy function executeTemplate( uint256 templateId, SignedOperation[] calldata signedOps ) external; Copy function executeBatch(SignedOperation[] calldata signedOps) external; Copy function getOperationHash(SignedOperation calldata op) public view returns (bytes32); Copy function domainSeparator() public view returns (bytes32); sun-brightdesktopmoon --- # Sherlock Audit - Jan 2, 2024 | SYMMIO Protocol Gitbook [![Logo](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2Faudits.sherlock.xyz%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=87b6773d&sv=2)SYMM IO Contest - 13,500 USDCaudits.sherlock.xyzchevron-right](https://audits.sherlock.xyz/contests/144) circle-info Sherlock is an audit marketplace and smart contract coverage protocol built on the Ethereum blockchain. Sherlock works to protect Decentralized Finance (DeFi) users from smart contract exploits with security reviews from top auditors backed by smart contract coverage on the audited contracts. You can find a brief overview of the Sherlock ecosystem below. [https://docs.sherlock.xyz/arrow-up-right](https://docs.sherlock.xyz/) View findings: [arrow-up-right](https://github.com/sherlock-audit/2023-12-symm-io-judging/issues) [https://github.com/sherlock-audit/2023-12-symm-io-judging/issuesarrow-up-right](https://github.com/sherlock-audit/2023-12-symm-io-judging/issues) Audit report: [https://audits.sherlock.xyz/contests/144?filter=questionsarrow-up-right](https://audits.sherlock.xyz/contests/144?filter=questions) [PreviousVaultschevron-left](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/vaults) [NextStaking and Vestingchevron-right](https://docs.symm.io/legal-and-brand-and-security/security-audits-bugbounty/audits/staking-and-vesting) Last updated 1 year ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Bridge Facet | SYMMIO Protocol Gitbook The Bridge feature allows users to bypass the full cooldown period when withdrawing their money. Certain addresses can be designated as "bridges" within the system. The method `transferToBridge` enables users to quickly transfer the amount they wish to withdraw. The trusted bridge will then send that amount to the user's wallet outside of SYMMIO. After the cooldown period is complete, the bridge can withdraw that amount from SYMMIO. The bridge is responsible for ensuring user compliance with system regulations. If SYMMIO detects any wrongdoing by the user, the bridge transaction will be suspended, and the bridge may become unable to fully withdraw the funds after SYMMIO restores the transaction. [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/bridge-facet#added-methods) Added Methods --------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/bridge-facet#transfertobridge) `transferToBridge()` **Description:** Transfers a specified amount to a designated bridge address. Copy function transferToBridge( uint256 amount, address bridgeAddress ) external whenNotAccountingPaused notSuspended(msg.sender) **Parameters:** * `amount` - The amount to transfer to the bridge. * `bridgeAddress` - The address of the bridge. **Returns:** None. **Events Emitted:** `TransferToBridge(address indexed sender, uint256 amount, address indexed bridgeAddress, uint256 transactionId)` ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/bridge-facet#withdrawreceivedbridgevalue) `withdrawReceivedBridgeValue()` **Description:** Withdraws the received bridge value associated with a specific transaction ID. **Parameters:** * `transactionId` - The ID of the transaction whose received value is to be withdrawn. **Returns:** None. **Events Emitted:** `WithdrawReceivedBridgeValue(uint256 indexed transactionId)` ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/bridge-facet#withdrawreceivedbridgevalues) `withdrawReceivedBridgeValues()` **Description:** Withdraws the received bridge values associated with multiple transaction IDs. **Parameters:** * `transactionIds` - An array of transaction IDs whose received values are to be withdrawn. **Returns:** None. **Events Emitted:** `WithdrawReceivedBridgeValues(uint256[] transactionIds)` ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/bridge-facet#suspendbridgetransaction) `suspendBridgeTransaction()` **Description:** Suspends a specific bridge transaction. **Parameters:** * `transactionId` - The transaction ID of the bridge transaction to be suspended. **Returns:** None. **Events Emitted:** * `SuspendBridgeTransaction(uint256 indexed transactionId)` ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/bridge-facet#restorebridgetransaction) `restoreBridgeTransaction()` **Description:** Restores a previously suspended bridge transaction and updates the valid transaction amount. **Parameters:** * `transactionId` - The transaction ID of the bridge transaction to be restored. * `validAmount` - The validated amount to be associated with the restored transaction. **Returns:** None. **Events Emitted:** * `RestoreBridgeTransaction(uint256 indexed transactionId, uint256 validAmount)` [PreviousView Facetchevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/view-facet) [NextLiquidation Facet (Implementation)chevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/liquidation-facet-implementation) Last updated 1 year ago * [Added Methods](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/bridge-facet#added-methods) * [transferToBridge()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/bridge-facet#transfertobridge) * [withdrawReceivedBridgeValue()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/bridge-facet#withdrawreceivedbridgevalue) * [withdrawReceivedBridgeValues()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/bridge-facet#withdrawreceivedbridgevalues) * [suspendBridgeTransaction()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/bridge-facet#suspendbridgetransaction) * [restoreBridgeTransaction()](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/facets/bridge-facet#restorebridgetransaction) sun-brightdesktopmoon Copy function withdrawReceivedBridgeValue( uint256 transactionId ) external whenNotAccountingPaused notSuspended(msg.sender) Copy function withdrawReceivedBridgeValues( uint256[] memory transactionIds ) external whenNotAccountingPaused notSuspended(msg.sender) Copy function suspendBridgeTransaction( uint256 transactionId ) external onlyRole(LibAccessibility.SUSPENDER_ROLE) Copy function restoreBridgeTransaction( uint256 transactionId, uint256 validAmount ) external onlyRole(LibAccessibility.DISPUTE_ROLE) sun-brightdesktopmoon --- # Fetching Gas Prices Script | SYMMIO Protocol Gitbook This script handles the process of fetching gas prices for hedger transactions from different sources, checks for errors, and ensures the gas price does not exceed a specified upper bound. **Full Script:** Copy def __get_gas_from_metaswap(self, priority, gas_upper_bound): gas_provider = f'https://gas-api.metaswap.codefi.network/networks/{self.chain_id}/suggestedGasFees' resp = None try: resp = requests.get(gas_provider, timeout=RequestTimeout) resp_json = resp.json() max_fee_per_gas = Decimal(resp_json[priority]['suggestedMaxFeePerGas']) max_priority_fee_per_gas = Decimal(resp_json[priority]['suggestedMaxPriorityFeePerGas']) apm.span_label(max_fee_per_gas=max_fee_per_gas, max_priority_fee_per_gas=max_priority_fee_per_gas, gas_price_provider=gas_provider) if max_fee_per_gas > gas_upper_bound: raise OutOfRangeTransactionFee(f'gas price exceeded. {gas_upper_bound=} but it is {max_fee_per_gas}') gas_params = { 'maxFeePerGas': Web3.to_wei(max_fee_per_gas, 'GWei'), 'maxPriorityFeePerGas': Web3.to_wei(max_priority_fee_per_gas, 'GWei') } return gas_params except (RequestException, JSONDecodeError, KeyError): if not DevEnv: logging.exception(f'Failed to get gas info from metaswap {resp.status_code=}') raise FailedToGetGasPrice("Failed to get gas info from metaswap") # fixme: do it by asyncio way def __get_gas_from_rpc(self, priority, gas_upper_bound): gas_price = None for provider in self.providers: provider_url = str(provider.provider.endpoint_uri) # noqa try: gas_price = provider.eth.gas_price apm.span_label(gas_price_from_provider=str(gas_price / 1e9), gas_price_provider=provider_url) except (ConnectionError, ReadTimeout, ValueError) as e: logging.error(f'Failed to get gas price from {provider_url}, {e=}') continue break if gas_price is None: raise FailedToGetGasPrice("Non of RCP could provide gas price!") if gas_price / 1e9 > gas_upper_bound: raise OutOfRangeTransactionFee(f'gas price exceeded. {gas_upper_bound=} but it is {gas_price / 1e9}') return dict(gasPrice=int(gas_price * TxPriorityMultiplier.get(priority, 1))) def _get_gas_price(self, gas_upper_bound, priority) -> dict: gas_params = {} if self.chain_id == 97: # Test BNB Network gas_params['gasPrice'] = Web3.to_wei(10.1, 'GWei') elif DevEnv or self.chain_id in ChainIdsWithGasFromRPC: gas_params = self.__get_gas_from_rpc(priority, gas_upper_bound) else: try: gas_params = self.__get_gas_from_metaswap(priority, gas_upper_bound) except FailedToGetGasPrice: gas_params = self.__get_gas_from_rpc(priority, gas_upper_bound) apm.span_label(**gas_params) return gas_params [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#get_gas_from_metaswap) \_\_get\_gas\_from\_metaswap ------------------------------------------------------------------------------------------------------------------------------------------------------------------ Function Definition and Parameters: This function is designed to retrieve gas price information from the Metamask Gas API. It takes two parameters: * `priority`: The priority level of the transaction, which will determine the gas fee structure to use (low, medium, high). * `gas_upper_bound`: The maximum allowable gas price for the transaction. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#gas-provider-url) **Gas Provider URL:** Constructs the URL to fetch gas price information from the Metamask Gas API for the specific blockchain network identified by `self.chain_id`. **Initialize Response:** Initializes the variable `resp` to `None`. This will later be used to store the response from the API request. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#fetching-and-processing-data) **Fetching and Processing Data:** Attempts to send a GET request to the `gas_provider` URL with a specified timeout (`RequestTimeout`). The response from this request is stored in `resp`,then converts the response from the API into JSON format, which allows for easy access to the data fields within the response. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#extract-gas-fees) **Extract Gas Fees:** Extracts the suggested maximum fee per gas unit (suggestedMaxFeePerGas) and the suggested maximum priority fee per gas unit (Decimal) from the JSON response, converting these values to Decimal. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#log-span-label) **Log Span Label:** Logs the extracted gas fee information using apm.span\_label for monitoring purposes. This includes the maximum fee per gas, the maximum priority fee per gas, and the URL of the gas price provider. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#check-upper-bound) **Check Upper Bound:** Checks if the `max_fee_per_gas` exceeds the specified `gas_upper_bound`. If it does, raises an `OutOfRangeTransactionFee` exception with a descriptive message. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#prepare-gas-parameters) **Prepare Gas Parameters:** If the gas fee is within the acceptable range, this prepares a dictionary gas\_params containing the gas fee values converted to Wei (a smaller unit of Ether) using Web3.to\_wei, then returns the gas\_params dictionary. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#exception-handling) **Exception Handling:** Handles potential exceptions that might occur during the process: * `RequestException`: General exception for request issues. * `JSONDecodeError`: Issue decoding the JSON response. * `KeyError`: If the expected keys are not present in the JSON response. If an exception occurs, logs the error (unless in development environment DevEnv) and raises a FailedToGetGasPrice exception with an appropriate message. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#get_gas_from_rpc) \_\_get\_gas\_from\_rpc -------------------------------------------------------------------------------------------------------------------------------------------------------- **Function Definition and Parameters:** This function is a private method to get gas prices from an RPC provider. It takes priority and gas\_upper\_bound as parameters. Initialize Gas Price: Initializes the gas price variable to None. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#loop-through-providers) Loop Through Providers: Iterates through available RPC providers to fetch the gas price. If it fails for a provider, logs the error and continues to the next one. Also logs the gas fees and provider URL for tracing purposes with `apm.span_label` ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#check-gas-price) Check Gas Price: If a gas price was retrieved, the function checks whether this price divided by 1e9 (to convert from wei to GWei) exceeds the `gas_upper_bound`. If it does, it raises an exception for exceeding the specified gas price limit. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#return-gas-parameters) Return Gas Parameters: Finally, the function returns a dictionary with a single key-value pair. The key is gasPrice, and the value is the fetched gas\_price adjusted by a priority multiplier. This multiplier adjusts the gas price based on the transaction priority, allowing for some dynamic control over how much to pay per transaction. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#get_gas_price) \_\_get\_gas\_price ------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#function-definition-and-parameters) Function Definition and Parameters: This function fetches the gas price based on the specified gas\_upper\_bound and priority. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#initialize-gas-parameters) Initialize Gas Parameters: Initializes an empty dictionary `gas_params` to store the gas price parameters. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#conditional-check-for-test-bnb-network) Conditional Check for Test BNB Network Checks if the `chain_id` is 97, which corresponds to the Test BNB Network. If true, it sets the gasPrice to 10.1 GWei (converted to Wei) directly in the gas\_params dictionary. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#conditional-check-for-development-environment-or-specific-chains) **Conditional Check for Development Environment or Specific Chains** If the code is running in a development environment (DevEnv) or if the `chain_id` is in the `ChainIdsWithGasFromRPC` list, it fetches the gas price from RPC providers by calling the `__get_gas_from_rpc` method with the specified priority and `gas_upper_bound`. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#attempt-to-get-gas-price-from-metamask-swap-api) **Attempt to Get Gas Price from Metamask Swap API** If the previous conditions are not met, it attempts to fetch the gas price from MetaSwap using the `__get_gas_from_metaswap` method. If this attempt fails and raises a `FailedToGetGasPrice` exception, it falls back to fetching the gas price from RPC providers using the `__get_gas_from_rpc` method. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#logging-the-gas-parameters) **Logging the Gas Parameters** Logs the gas price parameters using for monitoring purposes. The \*\*gas\_params syntax unpacks the dictionary so that each key-value pair in gas\_params is passed as a separate keyword argument. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#returning-the-gas-parameters) Returning the Gas Parameters Returns the gas\_params dictionary to the caller. **Summary:** The `_get_gas_price` function is designed to determine and return the appropriate gas price parameters for a transaction. It first checks if the network is the Test BNB Network, in which case it directly sets the gas price. If the environment is a development environment or the chain ID is in a specific list, it fetches the gas price from RPC providers. Otherwise, it tries to fetch the gas price from MetaSwap and falls back to RPC providers if that fails. [PreviousHow to Add a Market as a Solverchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/how-to-add-a-market-as-a-solver) [NextVerifying Account Abstracted Instant Actions (ERC-4337)chevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/verifying-account-abstracted-instant-actions-erc-4337) Last updated 1 year ago * [\_\_get\_gas\_from\_metaswap](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#get_gas_from_metaswap) * [Gas Provider URL:](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#gas-provider-url) * [Fetching and Processing Data:](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#fetching-and-processing-data) * [Extract Gas Fees:](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#extract-gas-fees) * [Log Span Label:](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#log-span-label) * [Check Upper Bound:](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#check-upper-bound) * [Prepare Gas Parameters:](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#prepare-gas-parameters) * [Exception Handling:](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#exception-handling) * [\_\_get\_gas\_from\_rpc](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#get_gas_from_rpc) * [Loop Through Providers:](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#loop-through-providers) * [Check Gas Price:](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#check-gas-price) * [Return Gas Parameters:](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#return-gas-parameters) * [\_\_get\_gas\_price](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#get_gas_price) * [Function Definition and Parameters:](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#function-definition-and-parameters) * [Initialize Gas Parameters:](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#initialize-gas-parameters) * [Conditional Check for Test BNB Network](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#conditional-check-for-test-bnb-network) * [Conditional Check for Development Environment or Specific Chains](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#conditional-check-for-development-environment-or-specific-chains) * [Attempt to Get Gas Price from Metamask Swap API](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#attempt-to-get-gas-price-from-metamask-swap-api) * [Logging the Gas Parameters](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#logging-the-gas-parameters) * [Returning the Gas Parameters](https://docs.symm.io/protocol-architecture/documentation-for-solvers/fetching-gas-prices-script#returning-the-gas-parameters) sun-brightdesktopmoon Copy def __get_gas_from_metaswap(self, priority, gas_upper_bound): Copy gas_provider = f'https://gas-api.metaswap.codefi.network/networks/{self.chain_id}/suggestedGasFees' Copy try: resp = requests.get(gas_provider, timeout=RequestTimeout) resp_json = resp.json() Copy max_fee_per_gas = Decimal(resp_json[priority]['suggestedMaxFeePerGas']) max_priority_fee_per_gas = Decimal(resp_json[priority]['suggestedMaxPriorityFeePerGas']) Copy apm.span_label(max_fee_per_gas=max_fee_per_gas, max_priority_fee_per_gas=max_priority_fee_per_gas, gas_price_provider=gas_provider) Copy if max_fee_per_gas > gas_upper_bound: raise OutOfRangeTransactionFee(f'gas price exceeded. {gas_upper_bound=} but it is {max_fee_per_gas}') Copy gas_params = { 'maxFeePerGas': Web3.to_wei(max_fee_per_gas, 'GWei'), 'maxPriorityFeePerGas': Web3.to_wei(max_priority_fee_per_gas, 'GWei') } return gas_params Copy except (RequestException, JSONDecodeError, KeyError): if not DevEnv: logging.exception(f'Failed to get gas info from metaswap {resp.status_code=}') raise FailedToGetGasPrice("Failed to get gas info from metaswap") Copy def __get_gas_from_rpc(self, priority, gas_upper_bound): Copy gas_price = None Copy for provider in self.providers: provider_url = str(provider.provider.endpoint_uri) # noqa try: gas_price = provider.eth.gas_price apm.span_label(gas_price_from_provider=str(gas_price / 1e9), gas_price_provider=provider_url) except (ConnectionError, ReadTimeout, ValueError) as e: logging.error(f'Failed to get gas price from {provider_url}, {e=}') continue break Copy if gas_price is None: raise FailedToGetGasPrice("None of RCP could provide gas price!") if gas_price / 1e9 > gas_upper_bound: raise OutOfRangeTransactionFee(f'gas price exceeded. {gas_upper_bound=} but it is {gas_price / 1e9}') Copy return dict(gasPrice=int(gas_price * TxPriorityMultiplier.get(priority, 1))) Copy def _get_gas_price(self, gas_upper_bound, priority) -> dict: Copy gas_params = {} Copy if self.chain_id == 97: # Test BNB Network gas_params['gasPrice'] = Web3.to_wei(10.1, 'GWei') Copy elif DevEnv or self.chain_id in ChainIdsWithGasFromRPC: gas_params = self.__get_gas_from_rpc(priority, gas_upper_bound) Copy else: try: gas_params = self.__get_gas_from_metaswap(priority, gas_upper_bound) except FailedToGetGasPrice: gas_params = self.__get_gas_from_rpc(priority, gas_upper_bound) Copy apm.span_label(**gas_params) Copy apm.span_label(**gas_params) sun-brightdesktopmoon --- # PerpsHub TP/SL Implementation | SYMMIO Protocol Gitbook ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/perpshub-tp-sl-implementation#overview) Overview The stop-loss/take-profit (SL/TP) system allows users to automatically close positions when the market price reaches specified trigger levels. The system continuously monitors mark prices and executes closes when conditions are met. **Base URL Pattern:** `/v1/:symmId/:multiaccount` All endpoints require the following path parameters: * `symmId`: Network/chain identifier (e.g., '56a', '5000a', '42161a', '8453a', etc.) * `multiaccount`: Ethereum address of the multi-account contract * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/perpshub-tp-sl-implementation#endpoints) Endpoints #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/perpshub-tp-sl-implementation#id-1.-create-stop-loss-take-profit) 1\. Create Stop Loss / Take Profit Create or update a stop-loss and/or take-profit order for a specific position. **Endpoint:** * `POST /v1/:symmId/:multiaccount/stop_loss` * `POST /v1/:symmId/:multiaccount/stop-loss` (kebab-case alternative) **Authentication:** Required (Bearer token) **Request Body:** Copy { userAddress: string // Ethereum address of the user (0x...) accountAddress: string // Ethereum address of the account/partyA (0x...) positionSide: 0 | 1 // 0 = LONG, 1 = SHORT symbolId: number // Numeric symbol identifier requestedPrice: string // Requested open price (decimal string) quoteId: number // Quote ID (positive for filled trades, negative for pending instant opens) tpPrice: string // Take profit trigger price (decimal string, can be empty) slPrice: string // Stop loss trigger price (decimal string, can be empty) timestamp: number // Request timestamp in milliseconds } **Validation Rules:** * At least one of `tpPrice` or `slPrice` must be provided (non-empty) * `tpPrice` and `slPrice` cannot be equal * For LONG positions: * `tpPrice` must be ABOVE the current/estimated mark price * `slPrice` must be BELOW the current/estimated mark price * For SHORT positions: * `tpPrice` must be BELOW the current/estimated mark price * `slPrice` must be ABOVE the current/estimated mark price **Success Response (200 OK):** **Error Responses:** **400 Bad Request:** **404 Not Found:** **Notes:** * If a stop-loss already exists for the trade in PENDING status, the request will be rejected * The system validates prices against the current mark price (for opened positions) or estimated fill price (for pending instant opens) * Prices are validated with slippage considerations **Example:** * * * #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/perpshub-tp-sl-implementation#id-2.-list-stop-losses-take-profits) 2\. List Stop Losses / Take Profits Retrieve stop-loss/take-profit orders for multiple quote IDs. **Endpoint:** * `POST /v1/:symmId/:multiaccount/list_sl` * `POST /v1/:symmId/:multiaccount/list-sl-tp` (kebab-case alternative) **Authentication:** Not required **Request Body:** **Success Response (200 OK):** **Response Fields:** * `symmId`: Network identifier * `quoteId`: Quote/trade identifier * `userAddress`: User's address * `affiliate`: Affiliate/multiaccount address * `partyA`: Account address (partyA) * `tpPrice`: Take profit trigger price (null if not set) * `slPrice`: Stop loss trigger price (null if not set) * `timestamp`: Creation timestamp * `status`: Order status (`"pending"`, `"processing"`, `"executed"`, `"cancelled"`) * `positionSide`: 0 = LONG, 1 = SHORT * `lastCheckedAt`: Last time the order was checked by the system * `symbolName`: Trading symbol (e.g., "BTCUSDT") **Error Response (400 Bad Request):** **Example:** * * * #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/perpshub-tp-sl-implementation#id-3.-cancel-stop-loss-take-profit) 3\. Cancel Stop Loss / Take Profit Cancel the stop-loss and/or take-profit for a specific quote. **Endpoint:** * `POST /v1/:symmId/:multiaccount/cancel_sl` * `POST /v1/:symmId/:multiaccount/cancel-sl-tp` (kebab-case alternative) **Authentication:** Required (Bearer token) **Request Body:** **Validation Rules:** * At least one of `cancelSl` or `cancelTp` must be `true` * The stop-loss order must exist for the given quote * The stop-loss order must be in `PENDING` status (cannot cancel processing/executed orders) **Success Response (200 OK):** When canceling both: When canceling only stop loss: When canceling only take profit: **Error Responses:** **400 Bad Request:** **404 Not Found:** **Notes:** * If both `cancelSl` and `cancelTp` are true (or if canceling the only remaining one), the entire stop-loss document is removed * If only one is canceled and the other remains, the document is updated with the remaining value * Partial cancellation is supported: you can cancel just SL or just TP while keeping the other active **Example:** Cancel both SL and TP: Cancel only stop loss: * * * #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/perpshub-tp-sl-implementation#stop-loss-states) Stop Loss States Status Description `PENDING` Order is active and being monitored `PROCESSING` Trigger conditions met, execution in progress `EXECUTED` Order successfully executed `CANCELLED` Order cancelled by user ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/perpshub-tp-sl-implementation#authentication) Authentication Endpoints marked as requiring authentication must include a Bearer token in the Authorization header: To obtain an access token, use the login endpoints: * `POST /v1/:symmId/:multiaccount/login` (for EVM wallets) * `POST /v1/:symmId/:multiaccount/tac-login` (for TON wallets) * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/perpshub-tp-sl-implementation#common-error-codes) Common Error Codes HTTP Status Error Message Description 400 Invalid symmId The symmId path parameter is not valid 400 Validation error Request body validation failed 401 Invalid or missing credentials Authentication token is missing or invalid 404 Trade not found The specified quote ID does not exist 404 Stop loss not found No stop-loss order exists for the quote 500 Internal server error Unexpected server error [PreviousRasa Solver TP/SL Implementationchevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/rasa-solver-tp-sl-implementation) [NextInstant Tradingchevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/instant-trading) Last updated 1 month ago * [Overview](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/perpshub-tp-sl-implementation#overview) * [Endpoints](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/perpshub-tp-sl-implementation#endpoints) * [Authentication](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/perpshub-tp-sl-implementation#authentication) * [Common Error Codes](https://docs.symm.io/protocol-architecture/documentation-for-solvers/conditional-orders/perpshub-tp-sl-implementation#common-error-codes) sun-brightdesktopmoon Copy { "success": true, "statusMessage": "Stoploss created", "data": { "success": true, "statusMessage": "Stoploss created" } } Copy { "error": "Stoploss request must have either TP or SL" } Copy { "error": "Stoploss request cannot have TP and SL equal" } Copy { "error": "Take profit price is invalid" } Copy { "error": "Stop loss price is invalid" } Copy { "error": "Stop loss already exists for this trade" } Copy { "error": "Unsupported symbol" } Copy { "error": "Trade not found" } Copy curl -X POST \ https://api.example.com/v1/42161a/0x1234...5678/stop-loss \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "userAddress": "0xabcd...ef01", "accountAddress": "0x1234...5678", "positionSide": 0, "symbolId": 123, "requestedPrice": "50000.5", "quoteId": 12345, "tpPrice": "55000", "slPrice": "48000", "timestamp": 1234567890000 }' Copy { quoteIds: number[] // Array of quote IDs (minimum 1 item) } Copy { "success": true, "statusMessage": "Stoplosses listed", "data": { "statusMessage": "Stoplosses listed", "success": true, "data": { "12345": { "symmId": "42161a", "quoteId": 12345, "userAddress": "0xabcd...ef01", "affiliate": "0x1234...5678", "partyA": "0x9876...5432", "tpPrice": "55000", "slPrice": "48000", "timestamp": 1234567890000, "status": "pending", "positionSide": 0, "lastCheckedAt": 1234567890000, "symbolName": "BTCUSDT" }, "67890": { "symmId": "42161a", "quoteId": 67890, "userAddress": "0xabcd...ef01", "affiliate": "0x1234...5678", "partyA": "0x9876...5432", "tpPrice": null, "slPrice": "3200", "timestamp": 1234567891000, "status": "pending", "positionSide": 0, "lastCheckedAt": 1234567891000, "symbolName": "ETHUSDT" } } } } Copy { "error": "Error message" } Copy curl -X POST \ https://api.example.com/v1/42161a/0x1234...5678/list-sl-tp \ -H "Content-Type: application/json" \ -d '{ "quoteIds": [12345, 67890, 11111] }' Copy { quoteId: number // Quote ID to cancel cancelSl?: boolean // Whether to cancel stop loss (optional, default: false) cancelTp?: boolean // Whether to cancel take profit (optional, default: false) } Copy { "success": true, "statusMessage": "Stop loss and take profit cancelled", "data": { "success": true, "statusMessage": "Stop loss and take profit cancelled" } } Copy { "success": true, "statusMessage": "Stop loss cancelled", "data": { "success": true, "statusMessage": "Stop loss cancelled" } } Copy { "success": true, "statusMessage": "Take profit cancelled", "data": { "success": true, "statusMessage": "Take profit cancelled" } } Copy { "error": "Must cancel at least one of SL or TP" } Copy { "error": "Can only cancel pending stop loss orders" } Copy { "error": "Error while cancelling stop loss" } Copy { "error": "Stop loss not found for this quote" } Copy curl -X POST \ https://api.example.com/v1/42161a/0x1234...5678/cancel-sl-tp \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "quoteId": 12345, "cancelSl": true, "cancelTp": true }' Copy curl -X POST \ https://api.example.com/v1/42161a/0x1234...5678/cancel-sl-tp \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "quoteId": 12345, "cancelSl": true, "cancelTp": false }' Copy Authorization: Bearer YOUR_ACCESS_TOKEN sun-brightdesktopmoon --- # New Events | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#new-events) New Events ------------------------------------------------------------------------------------------------------------------------------------------------ [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#balancechange) `BalanceChange` -------------------------------------------------------------------------------------------------------------------------------------------------------- To facilitate the tracking of user balances for partyB or anyone monitoring the Symmio contracts, we have added an event called `BalanceChanged` that is emitted every time a user's allocated balance changes. The reason for the change can be accessed through the type field of this event. Copy enum BalanceChangeType { ALLOCATE, DEALLOCATE, PLATFORM_FEE_IN, PLATFORM_FEE_OUT, REALIZED_PNL_IN, REALIZED_PNL_OUT, CVA_IN, CVA_OUT, LF_IN, LF_OUT } event BalanceChangePartyA(address indexed partyA, uint256 amount, BalanceChangeType _type); event BalanceChangePartyB(address indexed partyB, address indexed partyA, uint256 amount, BalanceChangeType _type); [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#expirequote) **ExpireQuote** ------------------------------------------------------------------------------------------------------------------------------------------------------ To enhance clarity, the single `ExpireQuote` event has been split into two separate events: `ExpireQuoteOpen` and `ExpireQuoteClose`. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#expirequoteopen) `**ExpireQuoteOpen**` **Explanation**: Emitted when an open request expires, providing the quote status and quote ID. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#expirequoteclose) `**ExpireQuoteClose**` **Explanation**: Emitted when a close request expires, including the quote status, quote ID, and close ID. [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#affiliate-events) **Affiliate Events** ---------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#registeraffiliate) `**RegisterAffiliate**` **Explanation**: Emitted when an affiliate is registered. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#deregisteraffiliate) `**DeregisterAffiliate**` **Explanation**: Emitted when an affiliate is deregistered. [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#bridge-events) **Bridge Events** ---------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#addbridge) `**AddBridge**` **Explanation**: Emitted when a bridge is added. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#removebridge) `**RemoveBridge**` **Explanation**: Emitted when a bridge is removed. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#transfertobridge) `**TransferToBridge**` **Explanation**: Emitted when a transfer to a bridge is initiated. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#withdrawreceivedbridgevalue) `**WithdrawReceivedBridgeValue**` **Explanation**: Emitted when the received bridge value is withdrawn. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#suspendbridgetransaction) `**SuspendBridgeTransaction**` **Explanation**: Emitted when a bridge transaction is suspended. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#restorebridgetransaction) `**RestoreBridgeTransaction**` **Explanation**: Emitted when a bridge transaction is restored. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#withdrawreceivedbridgevalues) `**WithdrawReceivedBridgeValues**` **Explanation**: Emitted when multiple received bridge values are withdrawn. ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#setinvalidbridgedamountspool) `**SetInvalidBridgedAmountsPool**` **Explanation**: Emitted when the invalid bridged amounts pool is updated. [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#internal-transfer-events) **Internal Transfer Events** -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#internaltransfer) `**InternalTransfer**` **Explanation**: Emitted when an internal transfer is made. [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#deferred-liquidation-events) **Deferred Liquidation Events** -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#deferredliquidatepartya) `**DeferredLiquidatePartyA**` **Explanation**: Emitted when a deferred liquidation for Party A occurs. [PreviousModified Eventschevron-left](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/modified-events) [NextMuonStoragechevron-right](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/muonstorage) Last updated 1 year ago * [New Events](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#new-events) * [BalanceChange](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#balancechange) * [ExpireQuote](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#expirequote) * [ExpireQuoteOpen](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#expirequoteopen) * [ExpireQuoteClose](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#expirequoteclose) * [Affiliate Events](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#affiliate-events) * [RegisterAffiliate](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#registeraffiliate) * [DeregisterAffiliate](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#deregisteraffiliate) * [Bridge Events](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#bridge-events) * [AddBridge](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#addbridge) * [RemoveBridge](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#removebridge) * [TransferToBridge](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#transfertobridge) * [WithdrawReceivedBridgeValue](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#withdrawreceivedbridgevalue) * [SuspendBridgeTransaction](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#suspendbridgetransaction) * [RestoreBridgeTransaction](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#restorebridgetransaction) * [WithdrawReceivedBridgeValues](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#withdrawreceivedbridgevalues) * [SetInvalidBridgedAmountsPool](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#setinvalidbridgedamountspool) * [Internal Transfer Events](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#internal-transfer-events) * [InternalTransfer](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#internaltransfer) * [Deferred Liquidation Events](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#deferred-liquidation-events) * [DeferredLiquidatePartyA](https://docs.symm.io/protocol-architecture/architecture-deep-dive/contracts-documentation-0.8.3/new-events#deferredliquidatepartya) sun-brightdesktopmoon Copy event ExpireQuoteOpen(QuoteStatus quoteStatus, uint256 quoteId); Copy event ExpireQuoteClose(QuoteStatus quoteStatus, uint256 quoteId, uint256 closeId); Copy event RegisterAffiliate(address affiliate); Copy event DeregisterAffiliate(address affiliate); Copy event AddBridge(address bridge); Copy eevent RemoveBridge(address bridge); Copy event TransferToBridge(address user, uint256 amount, address bridgeAddress, uint256 transactionId); Copy sevent WithdrawReceivedBridgeValue(uint256 transactionId); Copy event SuspendBridgeTransaction(uint256 transactionId); Copy event RestoreBridgeTransaction(uint256 transactionId, uint256 validAmount); Copy event WithdrawReceivedBridgeValues(uint256[] transactionIds); Copy event SetInvalidBridgedAmountsPool(address oldInvalidBridgedAmountsPool, address newInvalidBridgedAmountsPool); Copy event InternalTransfer(address sender, address user, uint256 userNewAllocatedBalance, uint256 amount); Copy event DeferredLiquidatePartyA( address liquidator, address partyA, uint256 allocatedBalance, int256 upnl, int256 totalUnrealizedLoss, bytes liquidationId, uint256 liquidationBlockNumber, uint256 liquidationTimestamp, uint256 liquidationAllocatedBalance ); sun-brightdesktopmoon --- # FRONTEND LICENSE | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/frontend-license#symmio-frontend-licensing) SYMMIO Frontend Licensing --------------------------------------------------------------------------------------------------------------------------------------------------------------------- Cloverfield was launched under a Business Source License 1.1 (BUSL 1.1). The license limits use of the Cloverfield source code in a commercial or production setting until December 1st, 2025. After this, the license will convert to a MIT. This means anyone can fork the code for their own use. The Symmetry Labs team is creating a documents that outlines the forking process. Copy Licensor: Symmetry Labs AG. Licensed Work: SYMMIO Frontend (CLOVERFIELD) The Licensed Work is (c) 2023 Symmetry Labs Change Date: 12-31-2025 Change License: MIT License For information about alternative licensing arrangements for the Software, please visit: Additional Use Grant: Any uses listed and defined at https://docs.symm.io/legal-disclaimer/frontend-license/frontend-use-grants Change Date: 31st of December 2025 or a date https://docs.symm.io/legal-disclaimer/frontend-license/frontend-modifications Change License: MIT LICENSE Notice License text copyright (c) 2017 MariaDB Corporation Ab, All Rights Reserved. “Business Source License” is a trademark of MariaDB Corporation Ab. Terms The Licensor hereby grants you the right to copy, modify, create derivative works, redistribute, and make non-production use of the Licensed Work. The Licensor may make an Additional Use Grant, above, permitting limited production use. Effective on the Change Date, or the fourth anniversary of the first publicly available distribution of a specific version of the Licensed Work under this License, whichever comes first, the Licensor hereby grants you rights under the terms of the Change License, and the rights granted in the paragraph above terminate. If your use of the Licensed Work does not comply with the requirements currently in effect as described in this License, you must purchase a commercial license from the Licensor, its affiliated entities, or authorized resellers, or you must refrain from using the Licensed Work. All copies of the original and modified Licensed Work, and derivative works of the Licensed Work, are subject to this License. This License applies separately for each version of the Licensed Work and the Change Date may vary for each version of the Licensed Work released by Licensor. You must conspicuously display this License on each original or modified copy of the Licensed Work. If you receive the Licensed Work in original or modified form from a third party, the terms and conditions set forth in this License apply to your use of that work. Any use of the Licensed Work in violation of this License will automatically terminate your rights under this License for the current and all other versions of the Licensed Work. This License does not grant you any right in any trademark or logo of Licensor or its affiliates (provided that you may use a trademark or logo of Licensor as expressly required by this License). TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON AN "AS IS" BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND TITLE. MariaDB hereby grants you permission to use this License’s text to license your works, and to refer to it using the trademark "Business Source License", as long as you comply with the Covenants of Licensor below. Covenants of Licensor In consideration of the right to use this License’s text and the "Business Source License" name and trademark, Licensor covenants to MariaDB, and to all other recipients of the licensed work to be provided by Licensor: To specify as the Change License the MIT License, or a license that is compatible with MIT Licnse, where "compatible" means that software provided under the Change License can be included in a program with software provided under MIT License. Licensor may specify additional Change Licenses without limitation. To either: (a) specify an additional grant of rights to use that does not impose any additional restriction on the right granted in this License, as the Additional Use Grant; or (b) insert the text "None". To specify a Change Date. Not to modify this License in any other way. Notice The Business Source License (this document, or the "License") is not an Open Source license. However, the Licensed Work will eventually be made available under an MIT Open Source License, as stated in this License. [PreviousTERMS OF SERVICEchevron-left](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/terms-of-service) [NextFrontend Modificationschevron-right](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/frontend-license/frontend-modifications) Last updated 7 months ago sun-brightdesktopmoon sun-brightdesktopmoon --- # Collateral & Margin System | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/collateral-and-margin-system#collateral-management) **Collateral Management** ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- Symmio supports two distinct margin systems to manage risk and ensure solvency across counterparties: ### [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/collateral-and-margin-system#id-1.-isolated-margin) **1\. Isolated Margin** * Used exclusively for **Party A option purchases**. * Party A’s funds are deposited into an individual **isolated balance**, managed per user. * **Party B** is responsible for maintaining sufficient collateral in their own isolated balance to cover the **total unrealized PnL** of all open positions with all Party As. * The required collateral is determined by the **loss coverage ratio**, which defines what percentage of unrealized losses must be backed by actual funds. * Solvency checks for Party B are performed **only** against their isolated balance, aggregated across all counterparties (not per Party A). * If Party B’s available balance falls below the required threshold, liquidation is triggered. * The **Scheduled Release Balance System** governs how and when deposited funds become available, introducing timed delays for security. ### [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/collateral-and-margin-system#id-2.-cross-margin) **2\. Cross Margin** * Available for **both buying and selling** by **Party A**. * Each Party A and Party B maintains a **dedicated cross balance per counterparty pair**. * This model is used for: * **Party A’s maintenance margin** (when selling options). * **Party B’s loss coverage** (when Party A is the buyer). * Funds can be allocated from the isolated balance into a cross balance specific to a trading counterparty. * Solvency and liquidation are **pair-specific**—they apply only to the trades and margin balances between a particular Party A and Party B. * Party A must maintain enough maintenance margin in their cross balance with Party B to support short positions. * Party B must allocate sufficient funds in the cross balance with Party A to cover the required unrealized PnL. * A dedicated **reserve balance** is introduced for Party B: * Acts as a fail-safe collateral source in critical situations. * Can be used to top up a cross balance and **prevent liquidation** if the account is at risk. [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/collateral-and-margin-system#scheduled-release-balance-system) Scheduled Release Balance System ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- The Scheduled Release System is a smart contract-based balance management system that provides secure fund handling with time-delayed releases and multi-counterparty support. The system supports both isolated and cross-margin trading models with sophisticated locking mechanisms. This system : * Controls fund release and transfers between parties * Implements security delays to prevent immediate fund availability * Mitigates risks associated with rapid fund movements * Provides different functionality for isolated vs. cross margin systems **Balance Types** 1. **Isolated Balance**: User's main balance pool which used in isolated solvency checks 2. **Cross Balance**: Per-counterparty balance for cross-margin operations and solvency checks 3. **Scheduled Balance**: Time-locked funds awaiting first release 4. **Transitioning Balance**: Funds in second phase of release process **Margin Types** * **Isolated Margin**: Uses scheduled release mechanism with time delays * **Cross Margin**: Direct balance operations without delays ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FyEQ1IQS1XuVucsOeebmL%252Fimage.png%3Falt%3Dmedia%26token%3Dec7cac01-7214-4eba-ba95-783e636eafd1&width=768&dpr=3&quality=100&sign=d5974a7e&sv=2) ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FKXLd5K1jLhho08PjbJYi%252Fimage.png%3Falt%3Dmedia%26token%3D50c41579-9c00-4311-bb8f-7c38758370fa&width=768&dpr=3&quality=100&sign=8c5c3815&sv=2) ### [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/collateral-and-margin-system#isolated-balance-functions) **Isolated Balance Functions** `instantIsolatedAdd()` * Immediately adds funds to party's isolated balance `isolatedSub()` * Subtracts funds from isolated balance `isolatedLock()` / `isolatedUnlock()` * Lock/unlock portions of isolated balance ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252Fz2dGHhEczIfTvHs0v1yB%252Fimage.png%3Falt%3Dmedia%26token%3De083ef91-baee-4a26-8420-0b26811dbe08&width=768&dpr=3&quality=100&sign=d546e9aa&sv=2) ### [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/collateral-and-margin-system#cross-balance-functions) **Cross Balance Functions** `allocateBalance()` * Transfer funds from isolated to cross balance for specific counterparty `deallocateBalance()` * Transfer funds from cross balance to isolated balance `crossLock()` / `crossUnlock()` * Lock/unlock portions of cross balance ### [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/collateral-and-margin-system#scheduled-release-functions) **Scheduled Release Functions** `scheduledAdd()` * Add funds with time-delayed release. This delay is because of security issues. ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FjV3RQq0B8BoohewJRNAx%252Fimage.png%3Falt%3Dmedia%26token%3D911d3690-23c5-4f5e-a410-e1f3c646676f&width=768&dpr=3&quality=100&sign=620ce0c&sv=2) `subForCounterParty()` * Subtract funds from balances for counterparty not just the isolated balance. ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FSwpjI0xx5EiDI9aV2Tsk%252Fimage.png%3Falt%3Dmedia%26token%3D3c48c991-6e03-41af-9402-656942bb168e&width=768&dpr=3&quality=100&sign=b3f361d3&sv=2) ### [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/collateral-and-margin-system#release-mechanism) **Release Mechanism** **Time Intervals** The system uses two release intervals: 1. **Release Interval 1**: Scheduled Balance → Transitioning Balance 2. **Release Interval 2**: Transitioning Balance → Isolated Balance **Sync Function** The `sync()` function must be called to progress funds through the release intervals. This function: * Checks elapsed time for each balance bucket * Moves funds from Scheduled to Transitioning when interval 1 expires * Moves funds from Transitioning to Isolated when interval 2 expires [PreviousBalance Operations (Deposit, Withdraw, Transfers)chevron-left](https://docs.symm.io/options-protocol-architecture/technical-architecture/balance-operations-deposit-withdraw-transfers) [NextIntent-Based Trading Systemchevron-right](https://docs.symm.io/options-protocol-architecture/technical-architecture/intent-based-trading-system) Last updated 4 months ago * [Collateral Management](https://docs.symm.io/options-protocol-architecture/technical-architecture/collateral-and-margin-system#collateral-management) * [1\. Isolated Margin](https://docs.symm.io/options-protocol-architecture/technical-architecture/collateral-and-margin-system#id-1.-isolated-margin) * [2\. Cross Margin](https://docs.symm.io/options-protocol-architecture/technical-architecture/collateral-and-margin-system#id-2.-cross-margin) * [Scheduled Release Balance System](https://docs.symm.io/options-protocol-architecture/technical-architecture/collateral-and-margin-system#scheduled-release-balance-system) * [Isolated Balance Functions](https://docs.symm.io/options-protocol-architecture/technical-architecture/collateral-and-margin-system#isolated-balance-functions) * [Cross Balance Functions](https://docs.symm.io/options-protocol-architecture/technical-architecture/collateral-and-margin-system#cross-balance-functions) * [Scheduled Release Functions](https://docs.symm.io/options-protocol-architecture/technical-architecture/collateral-and-margin-system#scheduled-release-functions) * [Release Mechanism](https://docs.symm.io/options-protocol-architecture/technical-architecture/collateral-and-margin-system#release-mechanism) sun-brightdesktopmoon sun-brightdesktopmoon --- # User Interaction Scenarios | SYMMIO Protocol Gitbook Below are typical user flows. Each scenario assumes the user has a Web3 wallet connected and has retrieved a valid JWT via the SIWE login flow. [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-withdrawal-for-frontend-builders/user-interaction-scenarios#scenario-1-normal-flow-and-successful-instant-withdrawal) Scenario 1: Normal Flow and Successful Instant Withdrawal ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1. **Login via wallet (SIWE flow)** 1. UI calls `POST /v1/auth/nonce` with `{ address }`. 2. UI immediately calls `GET /v1/auth/sign-in-message` with the same address, domain, and URI; displays the returned message for signing. 3. User signs; UI sends `POST /v1/auth/login` with `{ message, signature }`. 4. UI receives `access_token` and sets `Authorization: Bearer ` on subsequent requests. 2. **Fetch Fee Options** 1. User enters their wallet account address and desired amount in UI. 2. UI calls `POST /v1/fee-options?account=&amount=`. 3. Backend validates, computes instant and fallback options, and locks them for `POLICY_VALID_TIME` (e.g., 30 s). 4. UI displays the returned array of one or more `FeeOption` items. 3. **Bridge Funds** 1. UI invokes on-chain call `symmio_contract.bridge(amount)` (or `_call(deallocate, bridge)` if bridging from a multi-account). 2. Once on-chain transaction is mined, UI displays the `bridgeId` and instructs user to select a fee policy. 4. **Select Fee Policy** 1. UI calls `POST /v1/bridges/{account}/{start}/{size}` to fetch the user’s bridges in `no_policy` state, e.g.: Copy { "bridge_state": "pending", "bridge_type": "no_policy" } 2. For each bridge: 1. UI calls `GET /v1/pending-fee-policy/{account}` and displays locked fee policies. 2. User chooses one of the displayed `FeeOption`. 3. _(Optional)_ To specify a different receiver: 1. UI calls Copy GET /v1/get-select-receiver-message?receiver=&bridgeId= 2. UI has user sign the returned EIP-712 payload and includes: Copy "receiver": { "address": "", "signature": "" } 4. UI calls `POST /v1/select-fee-policy` with: Copy { "symmioBridgeId": , "cooldown": , "feeAmount": , "receiver": { … } // optional } 5. Backend validates, records in DB, calls `selectFeePolicyForBridge` on-chain, and schedules withdrawal at `execution_time = now + cooldown`. 6. Backend returns: Copy { "bridge_id": , "fee": , "execution_time": } 5. **Automated Withdrawal** After `cooldown` seconds, the backend bot automatically calls `processWithdrawal(bridgeId)` on-chain. * * * [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-withdrawal-for-frontend-builders/user-interaction-scenarios#scenario-2-fee-options-expire-and-retry) Scenario 2: Fee Options Expire and Retry --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1. Login via wallet (as in Scenario 1). 2. **Initial Fee Options** UI calls `POST /v1/fee-options` but user waits beyond `POLICY_VALID_TIME` (e.g., 30 s). 3. Bridge funds and obtain `bridgeId`. 4. Lock expires (options TTL passed). 5. UI retrieves no-policy bridges via `POST /v1/bridges/{account}/{start}/{size}`. 6. **Retry Fee Options** UI calls `POST /v1/fee-options?account=&amount=` again; backend regenerates options and locks for another 30 s. 7. **Select & Withdraw** User picks a new option, signs payload, calls `POST /v1/select-fee-policy`, and flow continues as in Scenario 1. * * * [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-withdrawal-for-frontend-builders/user-interaction-scenarios#scenario-3-no-policy-selected-withdrawal-pending) Scenario 3: No Policy Selected (Withdrawal Pending) ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-withdrawal-for-frontend-builders/user-interaction-scenarios#id-1.-login-and-bridge-funds) **1\. Login & Bridge Funds** * The user logs in and initiates a bridge transaction through the frontend. * The backend captures the bridge event and records it with `bridge_type = no_policy` and `status = RECEIVED`. * The funds are deducted from the user’s Symmio balance and reserved in the bridge contract — **no payout occurs yet.** #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-withdrawal-for-frontend-builders/user-interaction-scenarios#id-2.-user-does-not-select-a-policy) **2\. User Does Not Select a Policy** * If the user leaves or closes the UI before selecting a fee policy: * No withdrawal is scheduled. * The bridge transaction remains **pending** indefinitely. * The user’s reserved funds **cannot be used elsewhere**, but **can still be withdrawn later** once a policy is chosen. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-withdrawal-for-frontend-builders/user-interaction-scenarios#id-3.-user-returns-later-to-complete-the-withdrawal) **3\. User Returns Later to Complete the Withdrawal** * When the user logs back in, the UI must: * Retrieve all pending bridges with `POST /v1/bridges/{account}/{start}/{size}` and look for entries where `bridge_type = no_policy`. * For each pending bridge, request a **new set of fee options** using `POST /v1/fee-options?account=&amount=`. circle-info Previously shown fee options may have expired past their `POLICY_VALID_TIME,`in which case a new set of fee options must be fetched. #### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-withdrawal-for-frontend-builders/user-interaction-scenarios#id-4.-selecting-a-policy-and-processing-the-withdrawal) **4\. Selecting a Policy and Processing the Withdrawal** * Once the user selects a fee option: 1. The frontend calls `POST /v1/select-fee-policy` with the chosen policy . 2. The backend calls `selectFeePolicyForBridge` on-chain. 3. After the configured cooldown period (usually 0), the backend or bot executes `processWithdrawal(bridgeId)` to finalize the payout to the user. * The transaction is then marked as **completed**, and the user receives the bridged funds. * * * [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-withdrawal-for-frontend-builders/user-interaction-scenarios#scenario-4a-bot-inactive-then-reactivated) Scenario 4a: Bot Inactive, Then Reactivated -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1. **Bot Down During Bridge** – User bridges on-chain while event poller is offline → no record created. 2. **Bot Reactivation & Catch-Up** – Bot scans missed events, creates `BridgeTransactions` with `no_policy`. 3. **User Resumes Normal Flow** – UI requests fee options and follows Scenario 1 steps to select and execute withdrawal. * * * [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-withdrawal-for-frontend-builders/user-interaction-scenarios#scenario-4b-bot-inactive-after-policy-selected-manual-withdrawal) Scenario 4b: Bot Inactive after Policy Selected, Manual Withdrawal ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 1. Follow Scenario 1 through fee-policy selection. 2. Bot goes down before scheduled withdrawal executes. 3. **Manual Withdrawal** 1. UI displays “Withdraw After Cooldown” button next to bridges where `execution_time` has passed but state is still `pending`. 2. When clicked, UI calls `processWithdrawal(bridgeId)` on-chain. 3. Tokens arrive in user’s wallet. * * * [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-withdrawal-for-frontend-builders/user-interaction-scenarios#scenario-5-reset-locked-fee-options) Scenario 5: Reset Locked Fee Options ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1. Login via wallet. 2. UI calls `POST /v1/fee-options?account=&amount=`, receives options. 3. UI calls `POST /v1/unlock/{account}` to clear locks. 4. UI calls `POST /v1/fee-options?account=&amount=` again to fetch fresh options. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-withdrawal-for-frontend-builders/user-interaction-scenarios#id-4.-additional-ui-actions-and-buttons) 4\. Additional UI Actions and Buttons 1. **Get Max Instant Value Button** * **Endpoint:** `GET /v1/max-instant-value/{account}` * **Purpose:** Show the maximum amount the user can withdraw instantly; guide the user to not bridge more than this. 2. **Refresh Fee Options Button** * **Combined Actions:** 1. `POST /v1/unlock/{account}` 2. `POST /v1/fee-options?account=&amount=` * **Purpose:** Clear existing lock and fetch fresh fee/cooldown options in one click. 3. **Manual Process Withdrawal Button** * **Action:** Calls the contract’s `processWithdrawal(bridgeId)` method directly. * **Purpose:** Allow users to trigger on-chain withdrawal if scheduled withdrawal failed or bot is down. * **When to Show:** After fetching user’s bridge list, display “Withdraw Now” next to any entry where `execution_time` has passed but state is still `pending`. * * * ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-withdrawal-for-frontend-builders/user-interaction-scenarios#id-5.-error-codes) 5\. Error Codes All endpoints return structured error codes via the shared `ErrorInfoContainer`: Code Identifier Message 1 `unhandled_error` Internal server error 2 `could_not_get_excepted_response` Could not get expected response 3 `model_validation_error` Model validation error 4 `not_found_error` Not found 5 `already_has_pending` Already has pending withdrawal options—try again in ? seconds 6 `not_enough_balance` Not enough user balance 7 `invalid_bridge_transaction` Invalid bridge transaction 8 `invalid_bridge_policy_option` Invalid Bridge Policy Option—please check and select options again 9 `already_has_withdrawal_option_or_executed` You already selected an option for this bridge or it has executed 10 `low_amount_to_bridge` Requested amount for bridge is very low 11 `unauthorized_access` Unauthorized 12 `invalid_signature` Invalid Signature 13 `signature_mismatch` Signature mismatch 14 `expired_nonce` Nonce expired or not found 15 `not_authenticated` Not authenticated 16 `contract_validation_failed` Contract validation failed 17 `rpc_connection_failed` RPC endpoint connection failed 18 `nonce_mismatch` Nonce mismatch 19 `user_creation_in_progress` User creation in progress for this address. Please retry in a moment. [PreviousAPI Endpointschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-withdrawal-for-frontend-builders/api-endpoints) [NextDocumentation for Solverschevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers) Last updated 3 months ago * [Scenario 1: Normal Flow and Successful Instant Withdrawal](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-withdrawal-for-frontend-builders/user-interaction-scenarios#scenario-1-normal-flow-and-successful-instant-withdrawal) * [Scenario 2: Fee Options Expire and Retry](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-withdrawal-for-frontend-builders/user-interaction-scenarios#scenario-2-fee-options-expire-and-retry) * [Scenario 3: No Policy Selected (Withdrawal Pending)](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-withdrawal-for-frontend-builders/user-interaction-scenarios#scenario-3-no-policy-selected-withdrawal-pending) * [Scenario 4a: Bot Inactive, Then Reactivated](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-withdrawal-for-frontend-builders/user-interaction-scenarios#scenario-4a-bot-inactive-then-reactivated) * [Scenario 4b: Bot Inactive after Policy Selected, Manual Withdrawal](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-withdrawal-for-frontend-builders/user-interaction-scenarios#scenario-4b-bot-inactive-after-policy-selected-manual-withdrawal) * [Scenario 5: Reset Locked Fee Options](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-withdrawal-for-frontend-builders/user-interaction-scenarios#scenario-5-reset-locked-fee-options) * [4\. Additional UI Actions and Buttons](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-withdrawal-for-frontend-builders/user-interaction-scenarios#id-4.-additional-ui-actions-and-buttons) * [5\. Error Codes](https://docs.symm.io/protocol-architecture/documentation-for-frontend-builders/instant-withdrawal-for-frontend-builders/user-interaction-scenarios#id-5.-error-codes) sun-brightdesktopmoon sun-brightdesktopmoon --- # Pair Trading - Settlement costs | SYMMIO Protocol Gitbook circle-exclamation Pear Protocol exclusive Use Grant for Pair Trading version of Cloverfield. Currently Pear Protocol enjoys an exclusivity to be the only Subnet to use the dedicated Pair Trading version of Cloverfield via our [Frontend Use Grants](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/frontend-license/frontend-use-grants) . Other frontend builders are still able to build pair products ontop of our permissionless contracts from scratch. [hashtag](https://docs.symm.io/building-on-symmio/trading-fees/pair-trading-settlement-costs#settlement-costs-overview-pair-trading) Settlement Costs overview: `Pair Trading` ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Settlement cost for Endusers: `37,5 Basis Points` Settlement cost for Solvers: `0 Basis points` Settlement cost for Pair trading Subnets (Frontend Builders): `reduced based on Table` [Settlement Cost reduction Table](https://docs.symm.io/building-on-symmio/trading-fees/pair-trading-settlement-costs#settlement-cost-reduction-table) [hashtag](https://docs.symm.io/building-on-symmio/trading-fees/pair-trading-settlement-costs#settlement-cost-reduction-table) Settlement Cost reduction Table ------------------------------------------------------------------------------------------------------------------------------------------------------------------ Monthly Volume $SYMM Holdings in % Settlement costs in % $10,000,000 ($10M) 0.0625% 70% $25,000,000 ($25M) 0.125% 60% $50,000,000 ($50M) 0.25% 50% $100,000,000 ($100M) 0.5% 40% $1,000,000,000 ($1B) 0.75% 30% $10,000,000,000 ($10B) 1.15% 20% $30,000,000,000 ($30B) 1.5% 15% #### [hashtag](https://docs.symm.io/building-on-symmio/trading-fees/pair-trading-settlement-costs#example-a-volume-based) EXAMPLE A - VOLUME based: Frontend A generated **10M in monthly volume** it receives a **30% fee rebate. EXAMPLE B - $SYMM Holding based:** Fontend B locked 0.5% of the circulating $SYMM Supply into an NFT, it receives a **60% fee rebate.** circle-info Please note that these thresholds are subject to adjustment, and we aim to optimize them in the best interest of our frontend partners and the wider Symmio network. This program aims to provide a significant fee rebate to subnets, incentivizing increased $SYMM holdings. This will, in turn, drive the overall growth of Symmio. ### [hashtag](https://docs.symm.io/building-on-symmio/trading-fees/pair-trading-settlement-costs#early-adopter-program) Early Adopter Program We understand early adopters' crucial role in successfully growing and adopting new technologies. To appreciate and reward this, we are launching an "Early Adopter Program" where the first five frontend builders will be given special deals to push our adoption at the beginning. During the Early Adopter Program, frontend builders will start earning 60% of the profit right away. ### [hashtag](https://docs.symm.io/building-on-symmio/trading-fees/pair-trading-settlement-costs#early-adopter-fronter-builders) Early adopter Fronter Builders: Frontend Frontend Share Protocol Share Service Fee 1. Pear Protocol 70% 30% 0% ### [hashtag](https://docs.symm.io/building-on-symmio/trading-fees/pair-trading-settlement-costs#final-note) Final Note By creating this settlement cost reduction program for subnets, we aim to foster an ecosystem where collaboration and mutual growth are at the forefront. We firmly believe that this symbiotic relationship with frontend builders will enhance the overall strength, stability, and prosperity of the SYMMIO network. We encourage all frontend builders to participate in this program and join us in revolutionizing the SYMMIO landscape. For any further information, please check out our [SDK - SYMM client](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/sdk-symm-client) [Solver documentation](https://docs.symm.io/building-on-symmio/solving-for-symmio/solver-documentation) [Technical Documentation](https://docs.symm.io/protocol-architecture/technical-documentation) or contact us via Discord [https://discord.gg/invite/symmioarrow-up-right](https://discord.com/invite/symmio) or email us at [\[email protected\]](https://docs.symm.io/cdn-cgi/l/email-protection) [PreviousPerps - Settlement Costschevron-left](https://docs.symm.io/building-on-symmio/trading-fees/perps-settlement-costs) [NextExchanges (Frontend Builders)chevron-right](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders) Last updated 7 months ago * [Settlement Costs overview: Pair Trading](https://docs.symm.io/building-on-symmio/trading-fees/pair-trading-settlement-costs#settlement-costs-overview-pair-trading) * [Settlement Cost reduction Table](https://docs.symm.io/building-on-symmio/trading-fees/pair-trading-settlement-costs#settlement-cost-reduction-table) * [Early Adopter Program](https://docs.symm.io/building-on-symmio/trading-fees/pair-trading-settlement-costs#early-adopter-program) * [Early adopter Fronter Builders:](https://docs.symm.io/building-on-symmio/trading-fees/pair-trading-settlement-costs#early-adopter-fronter-builders) * [Final Note](https://docs.symm.io/building-on-symmio/trading-fees/pair-trading-settlement-costs#final-note) sun-brightdesktopmoon sun-brightdesktopmoon --- # GET Get Funding Info | SYMMIO Protocol Gitbook ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-get-funding-info#get_funding_info) /get\_funding\_info Copy /get_funding_info **Example Query:** Copy https://base-hedger82.rasa.capital/get_funding_info **Example Response:** Copy "BTCUSDT": { "next_funding_time": 1744070400000, "next_funding_rate_short": "0.000040455", "next_funding_rate_long": "-0.000053940", "funding_rate_epoch_duration": 14400 }, "FILUSDT": { "next_funding_time": 1744070400000, "next_funding_rate_short": "0.000045081", "next_funding_rate_long": "-0.000060108", "funding_rate_epoch_duration": 14400 }, [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-get-funding-info#get-funding-info-rasa-implementation) Get Funding Info Rasa Implementation --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-get-funding-info#router) Router **Output**: * Dict mapping ticker → `FundingInfoResponseSchema`. ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-get-funding-info#data-sources) Data Sources 1. **Symbol table (DB)** * `Symbol.funding_rate_epoch_duration` * `Symbol.funding_rate_window_time` 2. **External exchange (Binance)** * `binance_client.futures_mark_price()` → `lastFundingRate`, `nextFundingTime` 3. **Hedger coefficients** (from `settings.py`) * `FundingRateHedgerToUserCoefficient` * `FundingRateUserToHedgerCoefficient` 4. **Positions table (DB)** * Used for filtering and in expressions (`Positions.position_type`, `Positions.opened_price`, etc.) ### [hashtag](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-get-funding-info#logic) Logic In short, the logic can be summarized like this: **Fetch Symbol & Market Details** **Coefficient Application Logic** [PreviousGET Get Locked Paramschevron-left](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-get-locked-params) [NextPOST Position Statechevron-right](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/post-position-state) Last updated 9 months ago * [/get\_funding\_info](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-get-funding-info#get_funding_info) * [Get Funding Info Rasa Implementation](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-get-funding-info#get-funding-info-rasa-implementation) * [Router](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-get-funding-info#router) * [Data Sources](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-get-funding-info#data-sources) * [Logic](https://docs.symm.io/protocol-architecture/documentation-for-solvers/building-a-solver-on-symmio/creating-the-apis/get-get-funding-info#logic) sun-brightdesktopmoon Copy @common_router.get( '/get_funding_info', response_model=Dict[str, FundingInfoResponseSchema], dependencies=[\ Depends(CustomRateLimiter(times=1, seconds=1)),\ Depends(CustomRateLimiter(times=40, minutes=1)),\ Depends(CustomRateLimiter(times=1500, hours=1)),\ ] ) async def get_funding_info(symbols: List[symbol_enum] = Query(None)): # symbols: optional list of tickers; defaults to BaseSymbols if None return get_funding_rates(symbols or BaseSymbols) Copy class FundingInfoResponseSchema(BaseModel): next_funding_time: int next_funding_rate_short: Decimal next_funding_rate_long: Decimal Copy GET /get_funding_info ↓ get_funding_info(symbols) #Entry point ↓ get_funding_rates(symbols) ├─→ FundingRate.get_symbol_funding_details() ├ # read Symbol.is_valid from DB ├ # call binance_client.futures_mark_price() ├ # return List[SymbolFundingDetail] └─→ FundingRate.get_funding_details(..., to_apply=False) ├ # 1) build SQL CTE from symbol_funding_details ├ # 2) apply hedger’s long/short coefficients ├ # 3) compute contract_rate expression ├ # 4) group by Positions.party_a_address ├ # 5) optional $-amount filtering if to_apply=True ├ # 6) session.all_(stmt) → [FundingDetail(...)] ↓ map into Dict[str, FundingInfoResponseSchema] ↓ return JSON Copy @staticmethod def get_symbol_funding_details() -> List[SymbolFundingDetail]: # 1) Fetch mark‐price & funding‐time info for all symbols from Binance binance_markets: Dict[str, BinanceMarketDetail] = binance_client.futures_mark_price() # 2) Record current time (in seconds) to compare against each symbol’s funding window start_time = get_now_epoch() result: List[SymbolFundingDetail] = [] # 3) Load every valid symbol row from your local Symbol table for symbol in session.scalars_all( Symbol.select().where(Symbol.is_valid.is_(true())) ): # 4) Read the next funding timestamp (ms→s) from Binance’s data binance_next_funding_time = binance_markets[symbol.title].nextFundingTime // 1000 # 5) Only keep symbols whose next funding falls within the on-chain funding window if binance_next_funding_time < start_time + symbol.funding_rate_window_time: symbol_funding_detail = SymbolFundingDetail( symbol_id = symbol.symbol_id, binance_mark_price = binance_markets[symbol.title].markPrice, binance_last_funding_rate= binance_markets[symbol.title].lastFundingRate, binance_next_funding_time= binance_next_funding_time, funding_rate_window_time = symbol.funding_rate_window_time, ) # 7) Sanity check: confirm on-chain epoch aligns with Binance’s tick # If it doesn’t, emit an alert and skip this symbol if binance_next_funding_time % symbol.funding_rate_epoch_duration != 0: send_instant_error_message( title='Funding time of contract not compatible with Binance.', amend=asdict(symbol_funding_detail) ) continue # 8) Add to the list of symbols we’ll compute funding for result.append(symbol_funding_detail) # 9) Return all valid SymbolFundingDetail entries return result Copy @staticmethod def get_funding_details( symbol_funding_details: List[SymbolFundingDetail], to_apply: bool = True ) -> Optional[List[FundingDetail]]: # 1) Build an in-SQL CTE of symbol timing & rates symbol_details_expr = values( column('symbol_id', Integer), column('price', Numeric(**numeric_args)), column('funding_rate', Numeric(**numeric_args)), column('funding_window_open_time', BigInteger), column('binance_next_funding_time', BigInteger), name='funding_details' ).data([\ detail.get_data_for_cte()\ for detail in symbol_funding_details\ ]) # 2) Apply hedger coefficients to raw funding_rate funding_rate_expr = symbol_details_expr.c.funding_rate * case( # SHORT & positive → hedger pays user (negate HedgerToUserCoef) (and_(Positions.position_type == PositionType.SHORT, symbol_details_expr.c.funding_rate >= 0), -FundingRateHedgerToUserCoefficient), # SHORT & negative → user pays hedger (negate UserToHedgerCoef) (and_(Positions.position_type == PositionType.SHORT, symbol_details_expr.c.funding_rate < 0), -FundingRateUserToHedgerCoefficient), # LONG & positive → user pays hedger (and_(Positions.position_type == PositionType.LONG, symbol_details_expr.c.funding_rate >= 0), FundingRateUserToHedgerCoefficient), # LONG & negative → hedger pays user (and_(Positions.position_type == PositionType.LONG, symbol_details_expr.c.funding_rate < 0), FundingRateHedgerToUserCoefficient) ) # 3) Embed into full “contract rate” formula sign = case((Positions.position_type == PositionType.SHORT, -1), else_=1) contract_rate = func.round( ( ( (funding_rate_expr * symbol_details_expr.c.price) / (Positions.funding_rate_diff * Positions.opened_price) * sign + 1 ) * Positions.funding_rate_diff - 1 ) * sign, NumberFloatingPoint ) # 4) Build query: group by counterparty (party A) stmt = Positions.select( Positions.party_a_address, func.json_agg(Positions.quote_id), func.json_agg(contract_rate) ).outerjoin( AppliedFundingRate, Positions.quote_id == AppliedFundingRate.quote_id ).join(Symbol).select_from(symbol_details_expr).join( symbol_details_expr, Symbol.symbol_id == symbol_details_expr.c.symbol_id ).where( AppliedFundingRate.id.is_(None), Positions.state.in_([PositionState.OPEN, PositionState.CLOSE_PENDING]), Positions.open_time <= symbol_details_expr.c.binance_next_funding_time, or_( Positions.last_funding_time < symbol_details_expr.c.funding_window_open_time, Positions.last_funding_time.is_(None) ) ).group_by(Positions.party_a_address) # 5) If “to_apply”, also calculate $-amount and filter tiny ones if to_apply: funding_amount = ( (Positions.quantity - Positions.filled_closed_amount) * Positions.opened_price * contract_rate ) stmt = stmt.add_columns( func.json_agg( case( (contract_rate > Positions.max_funding_rate, Positions.max_funding_rate), else_=contract_rate ) ), func.sum(funding_amount).label('funding_amount') ).where( func.abs(funding_amount) > GasWorthyFundingThresholdPerPosition ).order_by(desc('funding_amount')) # 6) Execute and map to dataclass rows = session.all_(stmt) return [FundingDetail(*row) for row in rows] sun-brightdesktopmoon --- # Intent-Based Trading System | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/intent-based-trading-system#intent-states) **Intent States** ----------------------------------------------------------------------------------------------------------------------------------------------------- State Description **PENDING** Initial state when intent is created by Party A **LOCKED** Intent reserved by a Party B **FILLED** Intent executed and trade created **EXPIRED** Intent passed expiration time **CANCELLED** Intent cancelled by Party A before filling **CANCEL\_PENDING** Party A cancelled locked intent, awaiting Party B confirmation [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/intent-based-trading-system#trading-lifecycle) **Trading Lifecycle** ------------------------------------------------------------------------------------------------------------------------------------------------------------- ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252Fvm1TaUpuyO9ya9JTzzFF%252Fimage.png%3Falt%3Dmedia%26token%3D714a211f-6b1b-461d-8a41-ef12ad7e1eb3&width=768&dpr=3&quality=100&sign=7ce1e99f&sv=2) ### [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/intent-based-trading-system#step-1-send-open-intent) **Step 1: Send Open Intent** Party A initiates an open intent by calling: * **Fees**: Party A pays three fees : protocol fee + affiliate fee + solver fee. * **Fund locking**: **BUY options:** * Party A locks the option premium: `premium = option_price × quantity`. * The premium will be transferred to Party B when the trade is settled. **SELL options** * Party A locks the required maintenance margin. The intent is stored with **PENDING** status and becomes visible to eligible Party B accounts. [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/intent-based-trading-system#step-2-lock-open-intent) **Step 2: Lock Open Intent** -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- **Eligibility requirements for Party B** * The intent is **PENDING** and has not expired. * Party B’s address is included in `partyBsWhiteList`. * Party B has a sufficient balance to meet its obligations. * Party B accepts the terms. * The intent status changes from **PENDING** to **LOCKED** and is reserved for the locking Party B. [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/intent-based-trading-system#step-3-fill-open-intent) **Step 3: Fill Open Intent** -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- **BUY options :** * The locked premium is debited from Party A and credited to Party B. It will be paid to Party B after settlement. **SELL options :** * The locked maintenance margin is added to Party A’s total maintenance margin balance for solvency checks. * Party B pays the premium to Party A. * A new trade is created with **OPENED** status. * The intent status changes from **LOCKED** to **FILLED**. ### [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/intent-based-trading-system#step-4-close-position) **Step 4: Close Position** #### [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/intent-based-trading-system#id-4.1-early-close-before-expiration) **4.1 Early Close (before expiration)** Party A may close a position early by sending a close intent: **BUY positions:** * The premium is paid to Party B. * Party A sells the option back to Party B. * Party B pays Party A the PnL: `PnL = (closePrice − openPrice) × quantity`. If **PnL < 0**, Party A pays the loss to Party B. **SELL positions** * The corresponding maintenance margin is released to Party A. * Party A pays Party B the PnL (same formula as above). If **PnL < 0**, Party B pays the loss to Party A. #### [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/intent-based-trading-system#id-4.2-settlement-at-expiration) **4.2 Settlement at Expiration** * Party B keeps the premium already received (for trades where Party A was the buyer). **In‑the‑Money (ITM)** * Settlement price is obtained from the oracle. * `PnL = (settlementPrice − strikePrice) × quantity`. * The seller pays the positive P&L to the buyer (or vice versa if negative). **Out‑of‑the‑Money (OTM)** * The option expires worthless. * Any maintenance margin locked by the Party A seller is released. [PreviousCollateral & Margin Systemchevron-left](https://docs.symm.io/options-protocol-architecture/technical-architecture/collateral-and-margin-system) [NextLiquidation Systemchevron-right](https://docs.symm.io/options-protocol-architecture/technical-architecture/liquidation-system) Last updated 4 months ago * [Intent States](https://docs.symm.io/options-protocol-architecture/technical-architecture/intent-based-trading-system#intent-states) * [Trading Lifecycle](https://docs.symm.io/options-protocol-architecture/technical-architecture/intent-based-trading-system#trading-lifecycle) * [Step 1: Send Open Intent](https://docs.symm.io/options-protocol-architecture/technical-architecture/intent-based-trading-system#step-1-send-open-intent) * [Step 2: Lock Open Intent](https://docs.symm.io/options-protocol-architecture/technical-architecture/intent-based-trading-system#step-2-lock-open-intent) * [Step 3: Fill Open Intent](https://docs.symm.io/options-protocol-architecture/technical-architecture/intent-based-trading-system#step-3-fill-open-intent) * [Step 4: Close Position](https://docs.symm.io/options-protocol-architecture/technical-architecture/intent-based-trading-system#step-4-close-position) sun-brightdesktopmoon Copy function sendOpenIntent( address[] calldata partyBsWhiteList, uint256 symbolId, uint256 price, uint256 quantity, uint256 strikePrice, uint256 expirationTimestamp, uint256 mm, TradeSide tradeSide, MarginType marginType, ExerciseFee memory exerciseFee, uint256 deadline, address feeToken, address affiliate, bytes memory userData ) external returns (uint256 intentId) Copy function lockOpenIntent(uint256 intentId) external onlyPartyB Copy function fillOpenIntent(uint256 intentId, uint256 quantity, uint256 price) external Copy function sendCloseIntent( uint256 tradeId, uint256 quantity, uint256 price, uint256 deadline ) external Copy function executeTrade( uint256 tradeId, SettlementPriceSig memory settlementPriceSig ) external sun-brightdesktopmoon --- # Oracle Integration | SYMMIO Protocol Gitbook ### [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/oracle-integration#oracle-integration) Oracle Integration The Symmio Options Protocol uses secure, decentralized price feeds to power settlement, liquidation, and real-time solvency checks. Its oracle system is built on the **Muon Network**, which provides cryptographically verified price data using a distributed validator set. [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/oracle-integration#muon-network) Muon Network -------------------------------------------------------------------------------------------------------------------------------------- * **Threshold Signature Scheme (TSS):** Prevents single points of failure. * **Schnorr Signatures:** Enables efficient multi-party signature verification. * **Gateway Validation Layer:** Adds an off-chain signature from a trusted gateway. * **Decentralized Validation:** Multiple validators must agree on price updates. [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/oracle-integration#oracle-architecture) Oracle Architecture ---------------------------------------------------------------------------------------------------------------------------------------------------- Component Purpose **MuonOracle** Main on-chain oracle contract for price delivery **Schnorr Verifier** Performs cryptographic verification of signatures **Gateway Signature** Ensures a second, trusted source signs data **SettlementPriceSig** Encapsulates verified price + metadata for trades [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/oracle-integration#verification-process) Verification Process ------------------------------------------------------------------------------------------------------------------------------------------------------ Copy function verifyTSSAndGW( bytes32 _data, bytes calldata _reqId, SchnorrSign calldata _signature, bytes calldata _gatewaySignature ) external view; 1. **TSS Verification:** Uses Schnorr signatures and public key matching to validate data from Muon. 2. **Gateway Signature:** Validates an additional ECDSA signature from a trusted gateway signer. 3. **Integrity Checks:** Confirms request freshness, symbol correctness, and data authenticity. #### [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/oracle-integration#key-integration-points) Key Integration Points **1\. Trade Settlement** * Prices are verified during trade execution. * Verified price is used to calculate PnL and finalize trades. **2\. Liquidation Triggers** * Collateral prices and unrealized PnL are validated before liquidation. * Oracle data ensures fair execution and risk isolation. **3\. Real-Time Risk Monitoring** * Party-level PnL is updated using oracle-verified snapshots. * Enables automated flagging of risky accounts. [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/oracle-integration#role-in-liquidation-lifecycle) Role in Liquidation Lifecycle ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Phase Oracle Role Flagging Real-time collateral valuation for solvency checks Execution Provides final settlement prices and deficit validation Closure Supports asset redistribution based on verified values [hashtag](https://docs.symm.io/options-protocol-architecture/technical-architecture/oracle-integration#oracle-data-flow) Oracle Data Flow ---------------------------------------------------------------------------------------------------------------------------------------------- ![](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252Fx6ILa3DkMQx8JKVHz9Ur%252Fimage.png%3Falt%3Dmedia%26token%3D8da28ce7-53b1-4934-a8af-58599250a49e&width=768&dpr=3&quality=100&sign=3753fea1&sv=2) [PreviousParty Binding Systemchevron-left](https://docs.symm.io/options-protocol-architecture/technical-architecture/party-binding-system) [NextHelper Contractschevron-right](https://docs.symm.io/options-protocol-architecture/technical-architecture/helper-contracts) Last updated 4 months ago * [Oracle Integration](https://docs.symm.io/options-protocol-architecture/technical-architecture/oracle-integration#oracle-integration) * [Muon Network](https://docs.symm.io/options-protocol-architecture/technical-architecture/oracle-integration#muon-network) * [Oracle Architecture](https://docs.symm.io/options-protocol-architecture/technical-architecture/oracle-integration#oracle-architecture) * [Verification Process](https://docs.symm.io/options-protocol-architecture/technical-architecture/oracle-integration#verification-process) * [Role in Liquidation Lifecycle](https://docs.symm.io/options-protocol-architecture/technical-architecture/oracle-integration#role-in-liquidation-lifecycle) * [Oracle Data Flow](https://docs.symm.io/options-protocol-architecture/technical-architecture/oracle-integration#oracle-data-flow) sun-brightdesktopmoon sun-brightdesktopmoon --- # Exchanges (Frontend Builders) | SYMMIO Protocol Gitbook [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders#symmio-subnets-or-simply-brokers-are-protocols-that-are-built-ontop-of-our-settlement-layer-and-acti) Symmio subnets or simply Brokers are protocols that are built ontop of our settlement Layer, and actively offer and settle derivatives on SYMM, also referred to as Brokers or Frontend Builders. ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ triangle-exclamation [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders#trading-on-symmio) Trading on SYMMIO ----------------------------------------------------------------------------------------------------------------------- The Symmio Foundation does not operate its own Brokerage or engages in any Derivatives offerings, to ensure censorship resistance of the underlying bilateral & intent technology, the foundation only provides the infrastructure for third parties to provide such services. To interact with the protocol, users may choose from the list of Brokers & Subnet Operators below. Again, to be clear, there is no trading taking place directly via https://symm.io [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders#currently-operating-brokers) Currently operating Brokers: -------------------------------------------------------------------------------------------------------------------------------------------- ![Cover](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FC4kkqIOTb8mCOp5LbQK8%252FIntentX.png%3Falt%3Dmedia%26token%3D62c625fe-bfd7-48ff-9202-5a3fcb08042d&width=490&dpr=3&quality=100&sign=a576f81f&sv=2) [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders#intentx) IntentX --------------------------------------------------------------------------------------------------- OTC Perpetual Futures Exchange [https://intentx.io](https://intentx.io/) ![Cover](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FNGscsIzFFoFIvt8Cx7pA%252Fthena_LOGO.png%3Falt%3Dmedia%26token%3D4b58c2a6-1caf-4695-ab56-42815af3ed08&width=490&dpr=3&quality=100&sign=4f31ab47&sv=2) [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders#thena) THENA ----------------------------------------------------------------------------------------------- THE Trading Hub and Liquidity Layer Built on BNB Chain and opBNB [https://thena.fi/](https://thena.fi/) ![Cover](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FJY8Lp2ST8ASeg4MQnVM2%252FLode_logo%2520%282%29.png%3Falt%3Dmedia%26token%3D6f531310-ba7a-4d0b-a3c1-1ed06756412f&width=490&dpr=3&quality=100&sign=8f0d09e2&sv=2) [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders#pear-protocol) Pear Protocol --------------------------------------------------------------------------------------------------------------- Pair-Trading Perps Exchange [https://www.pear.garden/](https://www.pear.garden/) ![Cover](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FaLVxrc7DPVh2UxBoWuyV%252FLode_logo.png%3Falt%3Dmedia%26token%3D284992c9-0506-45b1-8a18-5c8c46598881&width=490&dpr=3&quality=100&sign=ca24eb93&sv=2) [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders#lode) LODE --------------------------------------------------------------------------------------------- Scalable & Capital-Efficient Perp DEX [https://www.lode.trade/](https://www.lode.trade/) ![Cover](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FfR0P2FovNrTPbYRGmmBz%252FUSKoa-Ve_400x400.jpg%3Falt%3Dmedia%26token%3D28609227-0bb4-476a-b8d9-55aeff3f2a01&width=490&dpr=3&quality=100&sign=c95b00e3&sv=2) [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders#privex) Privex ------------------------------------------------------------------------------------------------- Perp-DEX for Human and AI Trading Collaboration [https://prvx.io/](https://prvx.io/) ![Cover](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FeEcR0bQtFpVRAY6ml5MK%252F9237.png%3Falt%3Dmedia%26token%3Dfa36f3de-58fb-4a65-90c0-cac74b0f7a8f&width=490&dpr=3&quality=100&sign=1d20c67a&sv=2) [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders#xpanse) Xpanse ------------------------------------------------------------------------------------------------- An AI-Powered, Multi-Liquidity Perpetual Futures [https://xpanse.trade/](https://xpanse.trade/) ![Cover](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252F11QgQQHKfuMuhcIwHxC0%252FGMqkjTpXgAAKxt8.png%3Falt%3Dmedia%26token%3Dc187be62-1ad8-4c82-ae94-de12bee713f6&width=490&dpr=3&quality=100&sign=94ce3759&sv=2) [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders#befi-labs) BeFi Labs ------------------------------------------------------------------------------------------------------- BRC20, Runes and Ordinals Trading Terminal [https://befilabs.com/](https://befilabs.com/) ![Cover](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FUsAQM6bYPhUiTdllicYN%252FLode_logo%2520%281%29.png%3Falt%3Dmedia%26token%3D81b4c008-ecf9-4249-9317-7f80535e6c8c&width=490&dpr=3&quality=100&sign=3c26fb3f&sv=2) [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders#bmx) BMX ------------------------------------------------------------------------------------------- Decentralized Perpetual Trading Platform [https://www.bmx.trade/](https://www.bmx.trade/) ![Cover](https://docs.symm.io/~gitbook/image?url=https%3A%2F%2F1257875949-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FYQhBmTCs9MwhhuPQrV5v%252Fuploads%252FE53Mag0WbtylNNE8zGmV%252FMain%2520%281%29.png%3Falt%3Dmedia%26token%3D9395b00e-ec64-4457-9a89-47b16e42f141&width=490&dpr=3&quality=100&sign=cece4d02&sv=2) [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders#carbon) Carbon ------------------------------------------------------------------------------------------------- Smart Perp DEX with Cartel Trading. [https://app.carbon.inc/trade](https://app.carbon.inc/trade) [hashtag](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders#undefined) [Frontend Use Grants](https://docs.symm.io/legal-and-brand-and-security/terms-of-service-and-licensing/frontend-license/frontend-use-grants) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [PreviousPair Trading - Settlement costschevron-left](https://docs.symm.io/building-on-symmio/trading-fees/pair-trading-settlement-costs) [NextFrontend Builder Introductionchevron-right](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders/frontend-builder-introduction) Last updated 4 months ago * [Symmio subnets or simply Brokers are protocols that are built ontop of our settlement Layer, and actively offer and settle derivatives on SYMM, also referred to as Brokers or Frontend Builders.](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders#symmio-subnets-or-simply-brokers-are-protocols-that-are-built-ontop-of-our-settlement-layer-and-acti) * [Currently operating Brokers:](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders#currently-operating-brokers) * [](https://docs.symm.io/building-on-symmio/exchanges-frontend-builders#undefined) sun-brightdesktopmoon sun-brightdesktopmoon ---