# Denaria Docs > Canonical Denaria protocol, product, security, risk, and user documentation. ## Denaria Agent Action Bootstrap This documentation is the canonical knowledge source for Denaria. For a concrete request to prepare a Denaria position, use the official Action Handoff flow instead of browsing the app or constructing a transaction. - Landing instructions: https://denaria.finance/llms.txt - MCP guide: https://denaria.finance/agent-mcp.md - Installable skill: https://github.com/denaria-finance/denaria-skills - MCP endpoint: https://mcp.denaria.finance/mcp Denaria Agent Service prepares. Denaria App/PWA verifies. The user signs. External agents do not execute. # Agent Action Handoff Canonical page: https://docs.denaria.finance/agent-action-handoff Status: current Last reviewed: Fri Jul 10 2026 00:00:00 GMT+0000 (Coordinated Universal Time) Audience: agent Denaria Docs is the canonical knowledge source for protocol and product information. Concrete user requests to prepare a Denaria position use the official Action Handoff flow. ## Canonical Resources - [Landing agent instructions](https://denaria.finance/llms.txt) - [MCP handoff guide](https://denaria.finance/agent-mcp.md) - [Installable skill](https://github.com/denaria-finance/denaria-skills) - [Official MCP endpoint](https://mcp.denaria.finance/mcp) ## Operational Boundary ~~~text Denaria Agent Service prepares. Denaria App/PWA verifies. The user signs. External agents do not execute. ~~~ An agent may prepare and display an unsigned QR handoff. It must not claim to have opened, signed, submitted, broadcast, or executed the position. ## Expected Route 1. Read the landing agent instructions. 2. Use the installed Denaria Action Handoff skill when available. 3. If installation is required, ask the user before installing it. 4. Call the official MCP preparation flow. 5. Display the QR and fallback URLs. 6. The user scans, reviews, and signs in Denaria App/PWA. --- # Welcome to Denaria Canonical page: https://docs.denaria.finance/ Status: current ![](https://docs.denaria.finance/img/welcomeDenaria/cover_welcome.png) Denaria is a **mobile-first trading layer**, built to make perpetual trading simple, fast, and accessible from anywhere. Through a custom trading experience on Arbitrum, Denaria integrates GMX markets and liquidity, allowing users to trade crypto, stocks, and commodities 24/7 from their phone. By abstracting the complexity of the underlying DeFi infrastructure, Denaria focuses on what matters most: a seamless trading experience. --- # Introducing Denaria Canonical page: https://docs.denaria.finance/general/introducing-denaria Status: current ![](https://docs.denaria.finance/img/general/gettingStarted/introducing_denaria.png) Onchain markets are expanding fast, but the trading experience remains fragmented across protocols, wallets, networks and interfaces. **Denaria is building the trading layer that brings them together.** Denaria provides a mobile-first experience for trading perpetual markets, abstracting the complexity of the infrastructure underneath. --- ### Built for Mobile Trading - Trade perpetual markets directly from your phone, 24/7. - Open, close and manage positions through a trading experience designed specifically for mobile. - Access leverage of up to **100× on selected markets**. - Manage orders, leverage, take-profit and stop-loss without relying on a desktop trading setup. --- ### GMX Markets. Denaria Experience. - Denaria integrates **GMX markets and liquidity infrastructure on Arbitrum**. - GMX provides the underlying markets and execution infrastructure; Denaria builds the user-facing trading experience on top. - The initial Denaria experience includes markets across **crypto, stocks and commodities**. - By integrating existing infrastructure, Denaria can expand access to new markets without rebuilding the entire trading stack. --- ### Frictionless Wallet UX - Denaria use **passkey-based smart wallets powered by ZeroDev**. - Log in using familiar authentication methods without managing a traditional seed phrase. - Account recovery is designed to preserve access even when changing or losing a device. - The wallet experience is built around mobile users rather than traditional crypto wallet workflows. --- --- # Getting Started Canonical page: https://docs.denaria.finance/general/getting-started Status: current ![](https://docs.denaria.finance/img/general/gettingStarted/getting_started.png) ### Your First Trade in Four Steps 1. **Create your Denaria account** – Visit https://denaria.app/ from your smartphone, sign up or log in with your email, and secure your smart wallet using passkey-based authentication. 2. **Deposit funds** – Deposit USDC into your Denaria wallet on **Arbitrum** to start trading. 3. **Open a position** – Choose a market, select **Long or Short**, set your collateral and leverage, and open your position through the Denaria interface. 4. **Manage & close** – Monitor your open positions, adjust your risk with **Take Profit and Stop Loss orders**, and close your position directly from your phone. --- # Account, Smart Wallet & Passkeys Canonical page: https://docs.denaria.finance/perpetual-dex/account Status: current ### Account Abstraction by ZeroDev Denaria integrates the **ZeroDev stack** to provide every user with a smart contract wallet powered by **account abstraction**. Instead of requiring users to install a browser wallet, store a seed phrase, or manually sign complex blockchain transactions, Denaria provides a wallet experience designed around familiar mobile authentication. Each Denaria account is connected to an onchain smart wallet that users control directly through the app. ### Passkey-Based Trading Denaria uses **passkeys** as the primary authentication and transaction-signing mechanism. Instead of manually approving transactions through an external wallet, users can interact with Denaria using their device's native authentication methods, such as **Face ID, fingerprint, or device PIN**. Passkeys are used to securely authorize onchain actions across the Denaria experience, including trading and wallet operations. This means users can interact with onchain markets without having to manage traditional private keys or seed phrases. ### Your Denaria Smart Wallet Every Denaria user is automatically provisioned with a **smart contract wallet powered by ZeroDev**. These wallets are: - **Non-custodial** – users retain control over their wallet and assets. - **Passkey-secured** – transactions can be authorized directly from a mobile device. - **Programmable** – account abstraction enables features that are difficult to provide with traditional wallets. - **Built for mobile** – the wallet experience is integrated directly into Denaria rather than requiring external wallet applications. The result is an experience designed to feel closer to a modern financial application while keeping trading and asset ownership onchain. --- # Permissionless Passkey Recovery Canonical page: https://docs.denaria.finance/perpetual-dex/passkey-recpvery Status: current ![](https://docs.denaria.finance/img/perpetualDex/passkeyRecovery/passkey_recovrey.png) Passkeys remove much of the friction associated with traditional crypto wallets, but they introduce an important question: **what happens if the device storing your passkey is lost, stolen, or replaced?** Without a recovery mechanism, losing access to a passkey could also mean losing access to the smart wallet it controls. Denaria addresses this through a **permissionless, peer-to-peer recovery system** built in partnership with **ZeroDev**. Users can nominate another trusted Denaria user as their **Guardian**. The Guardian does not receive access to the user's wallet, funds, or passkey. Their only role is to authorize a recovery request if the original user loses access to their passkey. #### How Recovery Works 1. **Choose a Guardian** – Select a trusted Denaria user by entering their email address. They receive an in-app request and can accept the Guardian role. 2. **Lose access to your passkey** – If your device is lost, stolen, or otherwise inaccessible, log back into Denaria using your email. 3. **Request recovery** – Start a recovery request and create a new passkey. 4. **Guardian approval** – Your Guardian receives an in-app notification and verifies the recovery request. 5. **Restore access** – Once approved, the new passkey becomes authorized and you regain control of the same smart wallet and its funds. The entire process is handled **onchain and peer-to-peer**. Denaria does not hold backup keys, cannot access user passkeys, and cannot independently recover or take control of a user's wallet. This creates a recovery model that combines **self-custody with a familiar account-recovery experience**, without introducing a centralized custodian. **Lose your phone. Not your wallet.** --- # Risk Disclosure Canonical page: https://docs.denaria.finance/perpetual-dex/risk-disclosure Status: current Trading perpetual contracts involves significant risk, particularly when leverage is used. Denaria provides a mobile trading layer through which users interact with perpetual markets and liquidity infrastructure provided by integrated protocols such as **GMX on Arbitrum**. Denaria does not eliminate the risks associated with the underlying protocols, blockchain infrastructure, smart contracts, market conditions, or leveraged trading. Users should understand these risks before opening a position. --- ### General Risks - **Blockchain Infrastructure Risk:** Denaria currently operates on **Arbitrum One**. Users therefore inherit risks associated with Arbitrum, Ethereum, blockchain networks, bridges, RPC infrastructure, network congestion, outages, reorganizations, or other technical failures. - **Underlying Protocol Risk:** Trading through Denaria currently relies on **GMX markets, liquidity, smart contracts, and execution infrastructure**. Bugs, exploits, economic attacks, governance decisions, configuration changes, or other issues affecting GMX may consequently affect Denaria users. - **Smart Contract Risk:** Onchain protocols rely on smart contracts. Audits, testing, and security reviews can reduce risk but cannot guarantee that smart contracts are completely free from vulnerabilities or unexpected behavior. - **Oracle and Price Feed Risk:** Perpetual markets depend on external price data to determine execution prices, position PnL, and liquidations. Incorrect, delayed, unavailable, or manipulated price data could negatively affect positions. - **Stablecoin Risk:** Users may use stablecoins or other supported assets as collateral. These assets can lose their intended value, experience liquidity problems, or become subject to issuer, protocol, bridge, or market risks. - **Liquidity Risk:** Market liquidity can change rapidly. During volatile or stressed market conditions, users may experience increased price impact, difficulty executing at the expected price, or unfavorable conditions when opening or closing positions. - **Third-Party Infrastructure Risk:** Denaria integrates external infrastructure including **GMX, Arbitrum and ZeroDev**. Disruptions or vulnerabilities affecting these systems may impact the availability or functionality of Denaria. --- ### Denaria Trading Layer Risk Denaria provides the **user-facing trading interface** through which users interact with underlying onchain markets. Because execution ultimately depends on external protocols, the availability of the Denaria interface does not guarantee that an order will be executed, executed immediately, or executed under the conditions initially displayed. Potential risks include: - temporary interface or API unavailability; - delayed or outdated information displayed in the application; - transaction submission failures; - network congestion or failed blockchain transactions; - differences between a quoted value and the final onchain execution; - temporary inability to access certain integrated markets. The state recorded onchain and by the underlying trading protocol ultimately determines the status of a position or transaction. --- ### Trader Risk Trading perpetual contracts is inherently risky. Leverage significantly amplifies both profits and losses. #### 1. Market Risk The price of the underlying market can move against a trader's position. A trader who opens a **Long** position generally loses money when the market moves downward, while a trader who opens a **Short** position generally loses money when the market moves upward. Volatile markets can experience large price movements over very short periods. #### 2. Leverage Risk Selected Denaria markets may support leverage of up to **100×**. Higher leverage reduces the amount of adverse price movement required to produce substantial losses or trigger liquidation. A highly leveraged position can therefore lose most or all of its collateral following a relatively small market movement. #### 3. Liquidation Risk If the value of a position falls below the margin requirements established by the underlying trading protocol, the position may become eligible for liquidation. Liquidation can result in the loss of part or all of the collateral allocated to the position. Users are responsible for monitoring their positions and maintaining sufficient collateral. #### 4. Funding and Trading Fee Risk Perpetual positions may incur **funding, borrowing, execution, price impact, or other protocol fees** depending on the underlying market and trading infrastructure. These costs can accumulate while a position remains open and reduce its profitability or contribute to liquidation risk. #### 5. Execution and Price Impact Risk The price displayed when preparing a trade may differ from the final execution price. Market volatility, liquidity conditions, position size, price impact, blockchain latency, and changes occurring before transaction confirmation can all affect execution. #### 6. Take Profit and Stop Loss Risk Take Profit and Stop Loss orders are risk-management tools, but they **do not guarantee execution at an exact price**. Rapid price movements, liquidity conditions, oracle updates, network issues, or limitations of the underlying trading protocol may result in execution at a different price or prevent an order from executing as expected. --- ### Global Market Risk Denaria provides access to perpetual markets representing different asset classes, including **crypto, commodities and global financial markets**. These markets can behave differently and involve distinct risks. In particular: - the reference market for an asset may have specific trading hours even while the perpetual market remains accessible; - prices may move sharply around the opening or closing of traditional markets; - macroeconomic announcements can cause sudden volatility; - commodity markets can be affected by geopolitical events, supply disruptions, inventories and other market-specific factors; - perpetual prices may temporarily diverge from the price traders expect from the referenced underlying market. Users should understand the characteristics of each market before trading it. --- ### Wallet and Passkey Risk Denaria uses **smart accounts and passkeys powered by ZeroDev** to provide a simplified wallet experience. Users remain responsible for securing access to their account and devices. Potential risks include: - losing access to the device containing a passkey; - compromised devices or authentication credentials; - unauthorized access to the user's email account; - incorrectly configuring or failing to configure a Guardian; - approving a malicious or unintended transaction. Denaria provides a **Guardian-based permissionless recovery mechanism** that can help users replace a lost passkey. However, users should configure a trusted Guardian **before losing access to their original passkey**. A Guardian should only be assigned to someone the user trusts to correctly verify and approve a legitimate recovery request. Denaria does not have access to user passkeys and cannot independently recover a user's wallet. --- ### Important Notes - **Perpetual trading is high risk and may result in the complete loss of the collateral allocated to a position.** - Leverage magnifies both gains and losses. - Denaria provides access to underlying trading infrastructure but does not remove the risks associated with that infrastructure. - Users are responsible for understanding the markets, protocols and transactions they interact with. - Risk-management tools such as Stop Loss orders reduce risk but cannot eliminate it. - Past performance does not guarantee future results. - Users should never trade with funds they cannot afford to lose. --- # Denaria Points Campaign Canonical page: https://docs.denaria.finance/points-campaign Status: current ![](https://docs.denaria.finance/img/campaign/01_campaign.jpg) The **Denaria Points Campaign** is designed to reward users who trade on Denaria, remain active over time, and contribute to the growth of the ecosystem. DXP have already been distributed across previous phases of Denaria's development. With the **Arbitrum** **Mainnet Campaign**, rewards are now centered around real trading activity on Denaria. Points earned across the different campaign phases **are combined** and will be used to determine future rewards. ### The Past Campaigns - **Denaria Demo** The first phase of Denaria, created to validate the trading experience, collect early feedback, and test the original perpetual infrastructure. - **Onchain Testnet** The following phase moved activity onchain and allowed users to interact with Denaria's smart contracts while the protocol and trading experience continued to evolve. - **Mainnet on Linea** DXP were also distributed during Denaria's first Mainnet phase on **Linea**, where users could trade with real funds and participate in the points campaign under real market conditions. Users who participated in any previous campaign retain the DXP they accumulated. These points are carried forward and combined with DXP earned during the current Arbitrum Mainnet Campaign. --- ### How the Arbitrum Mainnet Campaign Works There are four main ways to earn DXP: maintaining a daily trading streak, generating trading volume, referring new traders, and growing your referral network. ### 1. Daily Trading Streak ![](https://docs.denaria.finance/img/campaign/02_daily_trade.png) Consistency is rewarded. Complete at least **one trade with $100 or more in volume each day** to keep your streak active. Rewards increase as your streak grows: - **Day 1** → 40 DXP - **Day 2** → 40 DXP - **Day 3** → 40 DXP - **Day 4** → 40 DXP - **Day 5** → 100 DXP - **Day 6** → 100 DXP - **Day 7+** → 120 DXP per day The Daily Trading Streak reward can be earned **once per day**. If you miss a day, your streak resets and starts again from Day 1. ***Please note: the $100 requirement must be reached with a single trade. Multiple smaller trades cannot be combined to qualify for the daily streak.*** --- ### 2. Trading Volume ![](https://docs.denaria.finance/img/campaign/03_volume.jpg) Every dollar of valid trading volume generated on Denaria earns DXP. **$1 trading volume = 0.5 DXP** For example: - **$1,000** volume → 500 DXP - **$10,000** volume → 5,000 DXP - **$100,000** volume → 50,000 DXP Trading Volume rewards are cumulative and can be earned alongside Daily Trading Streak rewards. The more you trade, the more DXP you accumulate. --- ### 3. Referral Bonus ![](https://docs.denaria.finance/img/campaign/04_referral.jpg) Referral codes are **optional**. You do not need a referral code to access or trade on Denaria. However, users who join through a referral can unlock additional DXP rewards. When a referred trader reaches **$500 in cumulative trading volume**: - **Referred trader** → +1,000 DXP - **Referrer** → +1,000 DXP Each referral bonus can be earned **once per qualified referred user**. Invitation codes used during previous Denaria campaigns are no longer part of the current referral system. --- ### 4. Grow Your Network Referrers can earn additional DXP as the traders in their referral network generate volume on Denaria. Rewards are unlocked when the network reaches specific cumulative trading-volume milestones: - **$1K network volume** → +250 DXP - **$50K network volume** → +350 DXP - **$100K network volume** → +1,500 DXP - **$500K network volume** → +4,000 DXP - **$1M network volume** → +15,000 DXP - **$5M network volume** → +50,000 DXP - **$10M network volume** → +200,000 DXP Each milestone can be unlocked **once**, and milestone rewards are cumulative. For example, a referral network reaching **$10 million in total trading volume** unlocks every milestone along the way, for a total of **271,100 DXP** in network-volume rewards. --- ### DXP Across Campaigns Points earned across the different phases are **combined**, allowing early users to carry their previous activity forward while continuing to accumulate DXP through Mainnet trading. To avoid account fragmentation and ensure previous DXP can be associated with the correct account, users who participated in earlier campaigns should use the **same email address** previously associated with their Denaria account. Start trading, keep your streak active, grow your network, and climb the **DXP leaderboard**. --- # How Obtain Denaria Canonical page: https://docs.denaria.finance/tutorial/how-obtain-denaria Status: current [Video](https://docs.denaria.finance/img/tutorial/03_howObtainDenaria.mp4) ## Step-by-Step Trading Tutorial 1. **Visit denaria.app** Open **Chrome** or **Safari** on your smartphone and go to **denaria.app**. 2. **Add Denaria to your home screen** Once the website loads, tap anywhere on the screen to bring up the browser options. Then tap the **Share** button (top right), select **“More”**, and choose **“Add to Home Screen.”** 3. **Name your PWA** Choose a name for the app and confirm. Denaria will now be accessible directly from your smartphone’s home screen, just like a native app. --- # Long Position Canonical page: https://docs.denaria.finance/tutorial/long-position Status: current [Video](https://docs.denaria.finance/img/tutorial/05_01_Long Position.mp4) Opening a LONG position on Denaria is super easy. 1. Select the market you want to trade. 2. Select Long, then choose the size and leverage. 3. Open your Long, sign with your passkey, and wait a few seconds. Trading perps, 24/7, has never been this easy. --- # Close Position Canonical page: https://docs.denaria.finance/tutorial/close-position Status: current [Video](https://docs.denaria.finance/img/tutorial/05_02_Close position.mp4) Closing a trading position on Denaria is super easy. 1. Go to the **Portfolio** tab and select the position you want to close. You’ll be redirected to the trading page. 2. Scroll down until you find the yellow **Close Position** icon, next to the Take Profit / Stop Loss and Adjust Margin options. 3. Tap the yellow icon, sign with your passkey, and confirm to close your position. Trading perps, 24/7, has never been this easy. --- # How To Set Up a Guardian Canonical page: https://docs.denaria.finance/tutorial/how-setup-guardian Status: current [Video](https://docs.denaria.finance/img/tutorial/04_howSettingGuardian.mp4) ## Step-by-Step Guardian Tutorial 1. **Access Account Settings** In the portfolio section, tap the **"Settings"** icon (gear symbol) located in the top right corner of the interface. 2. **Initiate Guardian Protection** Scroll down to the **"Account Settings"** section and tap the **"Request Guardian Protection"** button. This will open the setup wizard. 3. **Choose a Guardian Method** On the "Add Guardian" screen, tap the **"Choose a Guardian"** button. 4. **Enter Guardian Details** Input the **email address** of the person or secondary account you wish to set as your guardian and tap **"Send."** A notification will be sent to that address. Remember, the guardian must be another Denaria user. 5. **Authorize on the Guardian Device** On the guardian's device (another smartphone), open the notification and tap **"Click here"** to review the request. The guardian must then slide the **"Slide to accept"** toggle and tap **"Confirm Guardian"** to agree to the role. 6. **Wait for Blockchain Confirmation** Once the guardian accepts, the main device will display a **"Please Wait"** screen while the guardian installation is processed on the blockchain. This may take a few moments. 7. **Verify Guardian Status** After the transaction is confirmed, return to your settings. You will now see **"Guardian Protection Active"** highlighted in green, confirming that your recovery setup is complete and secure. --- # How To Request The Passkey Recovery Canonical page: https://docs.denaria.finance/tutorial/how-request-guardian-recovery Status: current [Video](https://docs.denaria.finance/img/tutorial/06_howRecoveryGuardin.mp4) ## Step-by-Step Passkey Recovery Tutorial 1. **Start Recovery on the New Device** Open the app on the new device where you want to recover access. On the login screen, tap **“Lost your Passkey”** to begin the recovery process. 2. **Request Help From Your Guardian** The app will inform you that recovery is possible by contacting your Guardian. Confirm the action to send a recovery request to your designated Guardian account. 3. **Guardian Receives the Recovery Request** On the Guardian’s device (another smartphone), open the app and view the incoming recovery request notification. 4. **Authorize Recovery on the Guardian Device** On the Guardian screen, review the recovery request details. Slide the **confirmation toggle** and tap **“Accept Recovery”** to approve the operation. 5. **Proceed With Email Verification** After Guardian approval, go back in the login page, enter your **email address** and tap **“Verify”** to continue the security check. 6. **Complete Account Recovery** Once the email verification is completed, access is restored. You are redirected into the app and the **portfolio dashboard** loads successfully. 7. **Verify Guardian Protection Status** From the portfolio screen, tap the **Settings (gear) icon** in the top right corner. Navigate to **Account / Security Settings** and confirm that **Guardian Protection** is shown as **Active**, indicating the account has been fully recovered and secured. --- # Best trade by funding rate Canonical page: https://docs.denaria.finance/tutorial/best-tade-funding-rate Status: current [Video](https://docs.denaria.finance/img/tutorial/07_best trade Funding.mp4) Denaria highlights the best trade by funding rate. 1. In the Home section, you’ll find the “Best Trade by Funding Rate” tab. 2. It highlights the market currently offering the best funding rate APY. It could be either a short or a long position. 3. If you decide to take the trade, simply click the white button and open the position. Trading funding rate opportunities has never been this easy. --- # New Onboarding Flow Canonical page: https://docs.denaria.finance/tutorial/onboarding Status: current Getting started with Denaria is now easier than ever. You can create your trading account in just a few seconds. 1. sign up 2. enter your name 3. save your passkey, 4. you’re in. You have now access to 24/7 perps, with up to 100x leverage, directly from your phone. [Video](https://docs.denaria.finance/img/tutorial/08_Onboarding.mp4) --- # Partners & Integrations Canonical page: https://docs.denaria.finance/additional/partner-integration Status: current # Blockchain Denaria is deployed on **Arbitrum One**, one of the leading Ethereum Layer 2 networks for DeFi and onchain trading. Arbitrum provides the execution environment for the current Denaria experience and connects the app with the broader ecosystem of protocols and liquidity available on the network. # Trading Infrastructure Denaria integrates **GMX** as the underlying trading and liquidity infrastructure for its current perpetual markets. The architecture is simple: **User → Denaria Trading Experience → GMX Markets & Liquidity → Arbitrum** GMX provides the underlying markets and execution infrastructure, while Denaria focuses on the layer closest to the trader: **mobile UX, market discovery, position management, wallet experience, rewards and distribution**. This allows Denaria to offer established onchain markets without needing to bootstrap independent liquidity for every asset. # Markets At launch, Denaria provides access to **11 perpetual markets** across crypto, commodities and global market exposure: ### Crypto - **BTC** – Bitcoin - **ETH** – Ethereum - **SOL** – Solana - **HYPE** – Hyperliquid - **LINK** – Chainlink ### Commodities - **WTIOIL** – WTI Crude Oil - **GOLD** – Gold - **SILVER** – Silver ### Stocks - SPCX - SpaceX ### ETFs - **SPY** – S&P 500 - QQQ - Nasdaq The available market catalogue may expand over time as Denaria integrates additional markets and trading infrastructure. # Account Abstraction Denaria uses **ZeroDev** as its account abstraction infrastructure provider. Every Denaria user interacts through a smart account secured by **passkeys**, allowing transactions and trading actions to be authorized through familiar device authentication such as Face ID, fingerprint or PIN. The ZeroDev integration also enables Denaria's **permissionless passkey recovery system**, allowing users to nominate a trusted Guardian who can help authorize a new passkey if access to the original one is lost. Together, **Arbitrum, GMX and ZeroDev** provide the infrastructure underneath the Denaria trading layer, while Denaria focuses on delivering a unified mobile trading experience. --- # Links Canonical page: https://docs.denaria.finance/additional/links Status: current 🔗 Website: [https://denaria.finance/](https://denaria.finance/) 🐦 X: [https://x.com/DenariaFinance](https://x.com/DenariaFinance) 🌐 Telegram: [https://t.me/DenariaFinance/1](https://t.me/DenariaFinance/1) 🏠 Discord: [https://discord.gg/N7DjEqvTKw](https://discord.gg/N7DjEqvTKw) --- # FAQs Canonical page: https://docs.denaria.finance/additional/faqs Status: current ### **How do I log back into Denaria after logging out?** If you log out of Denaria, you can log back in using the **email address associated with your account** and your registered passkey. Your passkey can be authorized through your device's authentication method, such as **Face ID, fingerprint, or PIN**. It is important to use the **same email address** associated with your Denaria account, as your smart wallet is linked to it. If you lose access to the device containing your passkey, Denaria's **permissionless recovery system** can allow you to register a new passkey with the approval of your previously selected Guardian. --- ### **What are passkeys and how do they work with Denaria?** Denaria uses **passkeys** to authenticate users and authorize onchain transactions without requiring traditional seed-phrase management. A passkey is securely stored through your device or operating system and can be unlocked using familiar authentication methods such as **Face ID, fingerprint, or device PIN**. Once configured, your passkey is used to authorize actions within Denaria, including trading and wallet transactions. Denaria itself does **not have access to your passkey or biometric information**. **Key advantages of passkeys include:** - **Strong security** – authentication credentials are protected by your device and operating system. - **Simple UX** – no seed phrase needs to be manually entered for everyday use. - **Fast transaction signing** – authorize actions using familiar mobile authentication. - **Recovery support** – Denaria's Guardian system can help restore access if the original passkey is lost. --- ### **What happens if I lose my passkey or my phone?** Losing your phone does not necessarily mean losing access to your Denaria wallet. Denaria provides a **permissionless passkey recovery system** that allows users to nominate another trusted Denaria user as a **Guardian**. If you lose access to your original passkey: 1. Log into Denaria using the email associated with your account. 2. Start a recovery request and create a new passkey. 3. Your Guardian receives an in-app recovery request. 4. Once the Guardian approves it, the new passkey is authorized. 5. You regain access to the same smart wallet and funds. The process is peer-to-peer and permissionless. **Denaria cannot access your passkeys, recover your wallet independently, or take control of your funds.** --- ### **I can't set up my passkey. What should I do?** If you're having trouble creating or using a passkey, try the following: - Make sure your device and operating system **support passkeys**. - Make sure device authentication such as **Face ID, fingerprint, or PIN** is enabled. - Use an up-to-date version of your browser. - If you previously cancelled or denied the passkey creation request, reload Denaria and try again. - Avoid using private/incognito browsing when creating your Denaria account. - Check that your browser and operating system are not blocking passkey functionality. For additional information about passkeys, you can refer to Google's official documentation: 👉 [What are passkeys?](https://safety.google/authentication/passkey/) 👉 [Google Passkey FAQ](https://support.google.com/accounts/answer/13548313?hl=en) If the issue persists, refer to the support section below. --- ### **How can I update the app?** Denaria is distributed as a **Progressive Web App (PWA)** rather than through a traditional mobile app store. When a new version is available, you may be prompted to reload the application. To make sure you are running the latest version: 1. **Close** Denaria completely. 2. **Reopen** it from your home screen. The application will reload and retrieve the latest available version. --- ### **Where can I find updates and documentation about Denaria?** You can follow Denaria's official updates on [**X (@DenariaFinance)**](https://x.com/DenariaFinance) and join the [**official Telegram community**](https://t.me/+4izPGFrz299hODdk) for announcements, discussion, and support. For product information and technical documentation, visit [**docs.denaria.finance**](https://docs.denaria.finance/). --- ### **Where can I find support if I encounter an issue?** If you encounter a problem while using Denaria, you can ask for assistance through the **official Denaria community channels**. For direct support: - [**Telegram**](https://t.me/+4izPGFrz299hODdk) – contact the official ***@DenariaSupporterBot*** or access it through the **Official Links** section of the community. For security reasons, always verify that you are interacting with an official Denaria account or support channel. **Denaria team members will never ask for your passkey or access to your wallet.** --- # Overview & Protocol Architecture Canonical page: https://docs.denaria.finance/protocol-architecture/overview-architecture Status: current # ![Overview cover](https://docs.denaria.finance/img/protocol%20Architecture/04_coverOverview.png) ### Introduction Denaria Perpetual DEX is a next-generation decentralized trading platform delivering a **permissionless and entirely onchain trading experience.** Designed for capital efficiency and institutional-grade performance, Denaria reimagines perpetual futures by integrating a **dynamic virtual AMM** anchored to **real-time oracle pricing**. Every trade, funding payment, and collateral movement is **executed transparently onchain,** ensuring trustless composability without centralized dependencies. Unlike many DeFi perpetual exchanges that rely solely on static vAMMs or order books, Denaria uses an **dynamic liquidity curve** that continuously aligns with the real market price. While trades occur at the exact oracle price, slippage remains minimal due to the curve's hybrid structure. A **funding mechanism incentivizes market balance** by redistributing payments based on long/short open interest rather than price premiums. At its core, Denaria features a **multi-stable vault system** designed to enable collateral deposits in various stablecoins. While the initial version of the platform will support **only a single stablecoin,** the full multi-collateral architecture, with flexible ratios and virtual balance tracking, will be introduced in a future release. This upgrade will unlock seamless PnL accounting and enhanced collateral management without relying on fixed ratios. Whether you’re a retail trader or a passive liquidity strategist, Denaria offers a **_permissionless, composable, and capital-efficient infrastructure_**, setting a new standard in onchain perpetual markets. --- # Dynamic Virtual AMM - dynAMM Canonical page: https://docs.denaria.finance/protocol-architecture/dynamic-virtualAMM Status: current ### Introduction to the dynAMM **Denaria’s perpetuals run on a dynamic virtual AMM** that delivers deep, capital-efficient, and oracle-anchored execution entirely onchain. Unlike traditional vAMMs with static liquidity curves, Denaria’s solution adjusts dynamically to market conditions by anchoring pricing around a real-time oracle and shaping slippage based on liquidity distribution and trade size. Instead of moving along a fixed liquidity curve, the dynAMM **constructs a new invariant curve for each trade based on the current pool state and oracle price**, ensuring that execution begins from a price-aligned baseline. This architecture ensures that traders receive pricing close to the fair market value, while the system introduces slippage only when necessary to protect LPs and preserve security. Crucially, Denaria’s dynAMM relies on _virtual assets_ (vAssets and vStables) as an efficient and flexible **internal accounting mechanism**. These synthetic balances represent position exposure and quote balances without requiring actual asset transfers, allowing the system to accurately track user positions and the protocol’s liquidity state in a capital-efficient, non-custodial way. # ![](https://docs.denaria.finance/img/protocol%20Architecture/01_virtualAMM.png) ### Core Mechanics: Curve Anchoring & Dynamic Shape Each time a trade is executed, the dynAMM uses **two inputs** to shape its pricing curve: * **The latest oracle price**, fetched from a trusted decentralized feed. * **The current pool state**, i.e., the virtual balances of vAsset and vStable held in the AMM. From these, dynAMM applies two operations: **Recentering and Resloping.** Before each trade, the curve is dynamically constructed based on the oracle price and the liquidity present in the system. This ensures that trades occur around the market price, with slippage conditions determined by the mathematical formulation. A well-balanced and sufficiently deep liquidity pool results in a **flatter curve,** which minimizes slippage and enables more cost-efficient trading. Conversely, when the pool is imbalanced due to disproportionate liquidity or directional trading, the curve becomes **steeper**. This design increases slippage for trades that would further exacerbate the imbalance, discouraging such actions and thereby protecting LPs from excessive exposure. Denaria achieves this behavior through a [**transparent mathematical formulation**](https://docs.denaria.finance/protocol-whitepaper/#the-formula-of-the-dynamm), inspired by and improving upon the most effective AMM models developed in DeFi, such as Curve’s hybrid approach, ensuring both precision and resilience in pricing. ### Slippage Logic: Curve-Inspired, Custom-Built Denaria’s dynAMM is conceptually inspired by Curve’s CryptoSwap invariant, blending constant sum and constant product curves, but **re-engineered** with a new mathematical foundation tailored for leveraged perpetual trading. A dynamic function `A(x, y)`denoted as the slippage control parameter, drives the shape of the pricing curve: * When vAsset and vStable are balanced **relative to the market price**, and the trade size is consistent with the available liquidity,`A` flattens the curve, minimizing slippage. * When imbalance grows, `A` dynamically increases, steepening the curve and introducing slippage that discourages further one-sided trading. ### Global Position Denaria adopts a **global position architecture**, where each trader holds only one unified position per market. This design simplifies risk management, ensures consistent accounting, and enhances protocol solvency. At the protocol level, every user's exposure is aggregated into a single global position that represents the **net result of all trades,** combining all longs and shorts into one virtual balance and debt. All **PnL calculations, funding payments, and liquidation conditions** are derived exclusively from this global position. This approach eliminates redundant position tracking, minimizes computational complexity, and allows for **an optimized liquidation threshold**, since all collateral and exposure are evaluated as a whole. From a user perspective, all trading actions (opening, closing, increasing, or reducing exposure) dynamically adjust the same position: * Opening a trade in the same direction increases the position size. * Opening in the opposite direction reduces or flips it. * Closing partially or fully reduces the global exposure. ### Advantages of the dynAMM Here is your TL;DR on the key advantages the dynAMM brings to traders and LPs: * **Oracle Execution** – Trades execute directly around the oracle price, ensuring fair fills for traders and eliminating arbitrage opportunities at LPs’ expense. This alignment optimizes outcomes for both sides of the market. * **Virtual Market Depth** – Deep liquidity is simulated around the market price using virtual balances, enabling capital-efficient trading without requiring equivalent real asset deposits. * **Low Slippage Execution** – The dynAMM delivers minimal slippage under normal conditions, even during volatility, by adapting the curve’s shape in real time. * **Dynamic LP Protection** – As the pool becomes unbalanced, slippage steepens automatically to deter further imbalance, protecting LPs from excessive directional exposure. * **Trustless and Onchain** – Every aspect of trade pricing, execution, and funding is computed and enforced onchain—without centralized actors or offchain matching layers. --- # Vault & Liquidity Management Canonical page: https://docs.denaria.finance/protocol-architecture/vault-liquidity-management Status: current ### Vault Overview Denaria uses a **modular vault** architecture to isolate risk and manage collateral with precision. Each perpetual market has its **own dedicated vault**, meaning systemic issues or bad debt in one market will not affect others. In the **initial release of the perpetual DEX,** the BTC vault will support a **single stablecoin**. This simplifies accounting, reduces operational complexity, and provides a seamless user experience for both traders and liquidity providers. However, the vault smart contracts are already built to support a **multi-stablecoin architecture**, which will be activated in a future upgrade. Once enabled, this feature will allow users to deposit a **mix of approved stablecoins** into a single vault. The system will enforce soft composition thresholds to prevent excessive exposure to any one asset, enabling more flexible collateral management while maintaining safety and predictability. ### How the Vault Works The vault is the **only component** of the Denaria protocol that interacts with real assets. It underpins the entire economic system: * For **traders**, it ensures all leveraged positions are backed by real collateral and that losses can be absorbed safely. * For **liquidity providers**, it tracks deposits with high granularity, enabling fair and automated distribution of fees, funding, and PnL. When traders and LPs deposit collateral, no virtual balances are immediately assigned. Instead, the deposit grants users the **right to** **open trades or to deposit liquidity up to a certain leverage.** **Only when a user opens a position, its virtual balance is assigned to its wallet.** For example, opening a long involves borrowing vStable, exchanging it through the vAMM for vAsset, and creating a corresponding virtual asset debt. This mechanism ensures that **only virtual tokens** are used within the dynAMM for trading, while the **vault holds real assets securely, isolated from direct trading activity**. The separation strengthens the protocol’s security model and facilitates transparent and flexible pricing mechanisms through the virtualized environment. ### Trader Flow Example — Alice Alice wants to open a long position on BTC with \$2,000 in stablecoin as collateral. When she chooses to open the position, the system automatically locks this collateral in the BTC vault and updates her account balance. To open a 5× leveraged long (i.e., \$10,000 notional exposure), the protocol assigns her a $10,000 balance in vStable, **recorded as debt.** This vStable is then immediately swapped through the virtual AMM into the corresponding amount of vBTC, giving Alice BTC exposure. To close the position, Alice will need to swap back the vBTC into vStable and repay her debt in full. # ![](https://docs.denaria.finance/img/protocol%20Architecture/02_traderExample.png) ### LP Flow Example — Bob Bob is a liquidity provider with $10,000 in stablecoins. He deposits this amount into the BTC vault, specifying how much he wants to allocate as vStable or vAsset exposure, depending on his strategy. The protocol uses **internal tracking** to register Bob’s position in the pool. His deposited value becomes part of the dynAMM’s virtual liquidity, **used to simulate trades by users like Alice.** Every time a trade occurs, the system updates Bob’s position using a **two-share model**, separately tracking his exposure to virtual stable and virtual asset sides of the pool. His share of fees, funding payments, and PnL from trades is calculated based on his vStable and vAsset shares. It’s important to note that simply holding vAsset in the liquidity pool **does not automatically expose Bob to the underlying asset’s** market price. His exposure changes only when his liquidity becomes the counterparty to a trade; for example, when a trader buys vAsset from the pool. This dynamic design allows LPs to hold **imbalanced liquidity without necessarily carrying continuous** **directional risk**, with exposure adapting to actual market activity. # ![](https://docs.denaria.finance/img/protocol%20Architecture/03_lpExample.png) --- # Providing Liquidity on Denaria Canonical page: https://docs.denaria.finance/protocol-architecture/liquidity-providing/providing-liquidity-denaria Status: current ### Providing Liquidity on Denaria Liquidity Providers are a fundamental component of the Denaria perpetual DEX. LPs enable leverage trading by supplying the virtual assets that traders interact with when opening or closing positions. In return, LPs **receive protocol fees** and **may earn funding payments**, depending on market conditions and traders exposure. Denaria has developed a **flexible and capital-efficient liquidity provisioning model** that, unlike traditional solutions, which require deposits in fixed ratios, allows LPs to provide liquidity in vAssets and vStable in personalized ratios.: **balanced, imbalanced, or even one-sided.** # ![LP diagram](https://docs.denaria.finance/img/protocol%20Architecture/liquidityProviding/01_LP.png) ### **Depositing Liquidity** On Denaria, providing liquidity starts with a simple step: the **LP deposits stablecoins.** The system then converts this deposit into balances of vAsset and vStable inside the chosen market. Each market (e.g., vETH/vUSD or vBTC/vUSD) has its **own dedicated pool,** and LPs can freely decide **how to split their collateral between vAsset and vStable in any ratio**, according to their strategy. Based on the ratio chosen by the LP, the protocol issues **LP shares,** one for the vAsset side and one for the vStable side. [This dual-share accounting](https://docs.denaria.finance/protocol-whitepaper/#LP%20shares) system allows flexible strategies while ensuring that returns remain properly balanced between both assets. These shares determine each LP’s entitlement to: * The virtual assets in the pool, * Accumulated trading fees (collected in vStable), * Potential funding payments. By supplying liquidity, LPs **passively take the opposite side** of trader positions, absorbing market exposure in exchange for a share of the protocol’s earnings. This mechanism ensures that trades can be executed with minimal slippage while offering LPs incentives to support the system. ### Imbalance Fees for Liquidity Providers Denaria allows LPs to add liquidity in any ratio of **vAsset** and **vStable**, including one-sided deposits. While this flexibility enables customized risk strategies, it can also create **imbalanced pools**, where the asset ratio drifts away from the oracle price. Such imbalances increase slippage for traders and distort LP exposure. To counter this, the protocol introduces **imbalance fees** on new deposits: * **Balanced contribution:** If the deposit brings the pool ratio closer to the market price, the LP pays only a minimal fee or even nothing. (`fmin`). * **Imbalanced contribution:** If the deposit worsens the imbalance, a higher penalty (`fmax`) applies. The exact fee coefficient is determined by comparing the pool’s ratio before and after the deposit with the market price. This ensures that: * Deposits that **improve balance** are rewarded with near-zero penalties. * Deposits that **skew the pool further** are disincentivized through higher fees. Importantly, these fees do **_not_** go to the protocol. Instead, they are distributed to existing LPs, compensating them for the additional risk created by imbalanced deposits. The same logic also applies to **withdrawals**: if a withdrawal worsens the pool imbalance, the same type of fee is charged. This mechanism ensures that LP incentives align with system health, maintaining **tight spreads and reducing the risk of extreme pool skew.** ### Share Accounting and Dynamic Tracking To manage LP balances accurately, Denaria employs a dual-share accounting system. Each LP holds two share balances: one for vAsset and one for vStable. As trades occur and liquidity is used to back the trading activity, LP balances are dynamically updated using an efficient onchain algorithm. This system allows a **fair distribution of fees and funding payments,** calculated according to the LP’s share of each asset in the pool. Fees collected in vStable are distributed proportionally to LPs based on their vStable shares. LPs can withdraw their liquidity at **any time.** The withdrawal will be processed according to the LP’s current share distribution, which reflects both their original deposit and the net effects of trading activity. --- # Strategy Explanation Canonical page: https://docs.denaria.finance/protocol-architecture/liquidity-providing/strategy-explanation Status: current ### Liquidity Strategies Denaria’s protocol lets LPs deposit liquidity in **any ratio of vAsset and vStable**, including imbalanced or one-sided deposits. This flexibility allows LPs to structure their initial setup according to their market predictions and risk appetite. In this context, **exposure** refers to the market direction that an LP passively takes through the liquidity they provide. Because LPs always stand on the opposite side of trader positions, the way they split deposits determines whether they benefit more from price increases, price decreases, or remain neutral. * **Only vAsset deposited (100% vAsset / 0% vStable)** → The LP mainly provides liquidity for traders going long. They become the counterparty to those longs and are therefore passively exposed to a price _decline_ in the asset (short exposure). * **Only vStable deposited (0% vAsset / 100% vStable)** → The LP mainly provides liquidity for traders going short. They become the counterparty to those shorts and are therefore passively exposed to a price _increase_ in the asset (long exposure). * **Balanced deposit (50% vAsset / 50% vStable)** → The LP starts with a neutral position, providing liquidity in both directions. This setup reduces directional risk and lets the LP earn fees from both long and short activity. * **Imbalanced deposit (e.g., 70% vAsset / 30% vStable)** → The LP tilts their setup toward short exposure but still keeps some long exposure. This type of allocation lets LPs express a directional view (bearish in this case) while not going fully one-sided. By adjusting the ratio of vAsset to vStable, LPs can fine-tune their position, from strongly directional to neutral, depending on their **market outlook and risk appetite.** This design allows LPs to define their **initial exposure** through the chosen deposit composition. However, since **trader activity continuously affects the pool's balance,** LPs do not retain full control over their exposure, which will shift over time based on market dynamics. LPs can always withdraw and rebalance their position if they wish to adjust their liquidity setup. # ![LP diagram](https://docs.denaria.finance/img/protocol%20Architecture/liquidityProviding/02_strategyLP.png) ### Long Strategy An LP with long exposure primarily benefits when the protocol experiences higher **short-side trading volume**, since most of the protocol fees (the main LP incentive) will be paid by traders opening short positions. This setup occurs when the LP provides mainly vStable (0%–30% vAsset / 70%–100% vStable). When traders short, they sell vAsset into the pool, increasing its reserves and generating more protocol fees for LPs. At the price level, a long-exposed LP gains when the underlying asset appreciates, as the value of the vAsset reserves grows. Conversely, price declines reduce the LP’s notional value. Long exposure is thus rewarded in environments dominated by shorts; both through protocol fees and, when applicable, via positive funding payments from short traders. ### Short Strategy An LP with short exposure is rewarded when the protocol sees stronger **long-side trading volume**, since most protocol fees are collected from traders opening long positions. This configuration occurs when the LP mainly provides vAsset (70%–100% vAsset / 0%–30% vStable). When traders go long, they buy vAsset from the pool, reducing its reserves and paying fees to the LPs. At the price level, a short-exposed LP profits when the asset price declines, since the pool can later repurchase vAsset at lower prices. Short exposure is therefore favored when the market is long-biased, benefiting from fee flow and, if funding is positive, receiving funding from the long side. ### Balanced Strategy A **balanced LP** (around 50% vAsset / 50% vStable) starts in a **delta-neutral** state. The LP earns fees from both long and short trades, and its position value is less affected by directional market moves. While neutral exposure minimizes price risk, the pool composition will evolve as traders interact, meaning that LP exposure will drift over time. Continuous monitoring and periodic rebalancing can maintain neutrality. --- # Funding Rate Canonical page: https://docs.denaria.finance/protocol-architecture/funding-rate Status: current To maintain a healthy balance between long and short positions, Denaria introduces a continuous, onchain funding rate mechanism. Whenever the market tilts too heavily in one direction, for example, if too many traders are long, the system compensates participants on the less popular side **through funding payments.** In this context, **exposure** refers to the net position that traders collectively hold in the system. Since LPs always take the opposite side of trader positions, they inherit the reverse exposure by design. For example, if traders in aggregate are long, LPs as a group are short. Funding payments are the tool that rebalances this dynamic: traders on the crowded side of the market pay funding, and those payments flow to LPs and traders on the opposite side. This means that **overall, traders pay funding fees to LPs**, who are naturally positioned as the counterparty to excess trader exposure. Unlike traditional perpetual protocols that calculate funding as the difference between an external index price and an internal mark price, Denaria’s model ties the funding rate directly to **net open interest imbalance**. The result is a simpler, more transparent incentive structure that continuously redistributes value from the majority side of the market to the minority side and to liquidity providers. # ![](https://docs.denaria.finance/img/protocol%20Architecture/05_fundingForm_1.png) Where: * **Net Trader Exposure** is the total value of long positions minus short positions. * **Total Liquidity** is the combined value of all the vAsset and vStable in the pool, expressed in USD. * **c** is the funding coefficient, a configurable variable that determines how aggressively the funding rate reacts to imbalance. This funding rate accrues continuously, in real time. Rather than settling payments in fixed intervals (e.g., every 8 hours), Denaria updates funding calculations on **every relevant protocol interaction,** including trading, liquidity changes, and position closures. This block-level granularity ensures that funding remains accurate and resistant to timing-based manipulation. ### A Practical Example Suppose the system holds **$100 million** in total virtual liquidity, with a **net long exposure of $500,000**. If the **funding coefficient** is set to **10**, the daily funding rate becomes: # ![](https://docs.denaria.finance/img/protocol%20Architecture/06_fundingForm_2.png) This rate is not paid out instantly but is continuously accumulated and attributed to each position based on its notional size and holding time. It adjusts dynamically as new trades are executed or existing positions are closed, ensuring that incentives always reflect the current market imbalance. ### How Funding is Accrued and Settled Funding payments are accounted for **continuously** but **settled lazily,** meaning they are not streamed block by block, but instead computed and applied when a trader or LP interacts with the system. This could include opening, closing, modifying a position, or withdrawing liquidity. Every user holds a snapshot of the last known funding state when they interacted with the protocol. When the user returns, their owed or earned funding fees are calculated as the product of their position size and the change in the global funding rate since that snapshot. For LPs, whose positions and exposure shift continuously with every trade executed in the pool, the protocol employs a [matrix-based accounting model](https://docs.denaria.finance/protocol-whitepaper#an-algorithm-for-efficiently-computing-the-funding-payments-of-traders-and-lps ). This approach dynamically reconstructs their effective exposure over time and ensures precise computation of funding payments. This model ensures **scalability without requiring constant onchain writes** or fund transfers. It also minimizes gas costs while preserving real-time accuracy, aligning perfectly with Denaria’s goal of performance without compromise. --- # Liquidation System and Insurance Fund Canonical page: https://docs.denaria.finance/protocol-architecture/liquidation-and-insurance Status: current ### Rationale The liquidation mechanism safeguards the solvency of each perpetual market by ensuring that positions whose collateral no longer covers potential losses can be closed in a timely manner. When a margin ratio falls below the defined thresholds, the position is flagged as liquidatable. At this point, **any external liquidator can step in to acquire the exposure at a discount**, securing a profit while protecting the protocol. ### Liquidation Bands Liquidation is triggered when a position’s margin ratio (MR) drops below defined thresholds: | Band | Threshold (default) | Action | Result | | ---| ---| ---| --- | | Soft (partial) | `2% < MR < 4%` | Up to 50% of the position can be purchased by a liquidator. | MR is recalculated; position may survive | | Hard (full) | `MR < 2%` | Full liquidation allowed | Trader is force-exited from the market entirely | These thresholds are governance-configurable and may be fine-tuned over time. The 2% floor is a conservative default designed to shield vaults from most gap-risk scenarios. ## Dynamic Discount Mechanism Unlike flat-fee systems, Denaria applies a **margin-ratio–dependent discount** to liquidations. * At higher MR levels (near the 4% soft threshold), the liquidator receives the base discount. * As MR decreases toward the 2% hard threshold, the discount scales upward. * At very low MR values, liquidators capture the maximum discount, reflecting the elevated systemic risk. This design ensures liquidators are **naturally incentivized** to prioritize the riskiest positions first, those closest to default, thereby protecting vault solvency while keeping the incentive structure economically sustainable and avoiding bad debt ### Liquidation Workflow 1. **Flagging** – When a position’s MR falls into a liquidation band, it is automatically marked as liquidatable. 2. **Acquisition** – Any liquidator can call `liquidate(positionId, size)`to purchase part or all of the position. The acquisition price will depend on the amount of liquidity available in the system rather than the oracle price, in order to ensure that the liquidator, after closing the position, secures a profit from the operation. 3. **Optional Close** – The liquidator can: * **Immediately close** the acquired exposure on the dynAMM within the same transaction (e.g., via flash-close), realizing the discount profit minus trading fees. * **Hold** the exposure, assuming directional risk. 4. **Settlement** – The trader’s debt is netted against liquidation proceeds. Surplus collateral, if any, is returned to the trader. If collateral is insufficient, the deficit becomes bad debt and is absorbed by the insurance fund. ### **Bad Debt Condition** A position enters **bad debt** when its margin ratio drops below zero: **`MR < 0%`    ⇒    Bad Debt** In this state, the collateral is fully exhausted and cannot cover the outstanding obligation. The insurance fund steps in to absorb the deficit. However, the **likelihood and size of bad debt** also depend on two additional parameters: 1. **Market Price** – If the underlying asset price moves sharply against the trader, the collateral’s value can fall below the notional debt. This accelerates the path to MR < 0%. 2. **Liquidator Discount** – Liquidations must occur _before_ MR reaches 0%, since liquidators need an incentive to act. The trader effectively “pays” this incentive through a discounted transfer of their position. This means part of their remaining margin is set aside to cover the liquidator’s profit, reducing the buffer against insolvency. Together, these dynamics explain why bad debt can still occur even when liquidations are timely: * **Fast market moves** erode collateral faster than liquidation can recover it. * **Discount costs** ensure liquidations remain attractive to liquidators, but this margin is lost to the trader.! # ![](https://docs.denaria.finance/img/protocol%20Architecture/07_liqduidation_process.png) ### Fees & Incentives During liquidations, liquidators acquire the position at a discounted notional value: * **The liquidator pays less than the oracle notional**, securing a built-in profit margin. * **The trader forfeits the discount**, which is split between the liquidator (execution incentive) and the insurance fund (system protection). * **The discount magnitude is a function of MR**, with higher discounts for more under-collateralized positions. This structure guarantees that liquidations remain profitable for external actors, even under high gas fees or sharp price moves, while continuously strengthening the insurance fund. ### Insurance Fund – Purpose and Role The Insurance Fund is the protocol’s final line of defense against insolvency. It activates only when a liquidated position’s collateral fails to fully cover its outstanding debt, typically due to sudden **price gaps, oracle delays, or liquidity exhaustion.** In such cases, the fund absorbs the shortfall, ensuring that: * Liquidity providers are not exposed to protocol losses, * The solvency of each vault remains intact, * User trust is preserved, even in extreme conditions. The fund is automatically replenished through a portion of trading fees. * * * ## Example – Hard Liquidation **Setup:** A trader opens a long position of +3 vBTC at \$100/vBTC, using \$100 in collateral (3× leverage). This creates a $300 notional exposure. | Event | Price | MR | Action | | ---| ---| ---| --- | | Entry | 100 | 33% | Position is healthy | | Market drops | 70 | 3,33% | MR enters soft band | | Further drop | 68 | 1,33% | MR enters hard band → full liquidation | --- # Perp Parameters Canonical page: https://docs.denaria.finance/protocol-architecture/perp-parameters Status: current In this section, we list the main parameters of the protocol and explain how they work ### Leverage * **MMR:** The Maintenance Margin Ratio is the margin ratio value below which the first liquidation step is triggered. When the MR of a position falls below this threshold, the position becomes liquidable according to the logic defined by the subsequent parameters. The margin ratio (MR) is defined as follows: ![](https://docs.denaria.finance/img/protocol%20Architecture/08_margin%20ratio.png) * **multipleMMRsteps:** It defines the number of liquidation steps and the MMR value at which each step is triggered. If we have two liquidation steps with values MMR/2,MMRMMR / 2, MMRMMR/2,MMR, this means that if mr < MMR, liquidation step 1 applies, and if mr < MMR / 2, liquidation step 2 applies. * **TradermaxLeverage:** maximum leverage allowed for traders by the protocol. * **LPmaxLeverage:** maximum leverage allowed for liquidity providers by the protocol. ### **Liquidation settings** * **liquidationFractions:** percentages of the position to be liquidated depending on the liquidation step. * **liquidationDiscounts:** discount offered to the liquidator to take over the position in the case of full liquidation, that is, when mr = MMR / 2. The other discount values depend on mr according to a specific formulation that makes the discount increase as the mr decreases. * **insFundFraction:** Percentage of the liquidator discount that goes to the insurance fund. ### **Trading & Liquidity Minimums** * **minimumTradeSize:** minimum trade size allowed by the protocol. * **Minimum allowed liquidity deposit:** minimum deposit required in the Vault to open a position. ### **Trading Fees** * **tradingFee:** Fee applied to trades on opening and closing. * **public fee:** portion of the trading fees allocated to cover fixed cost. * **feeLP:** portion of the trading fees collected by LPs directly within the AMM. * **autoCloseFee:** flat fee for automatic position closures. * **minFee:** minimum fee applied to the trading fee. ### **Insurance Fund**  * **insuranceFundCap:** maximum amount of insurance fund retained by the AMM in that specific market. Once this cap is reached, the funds allocated to the insurance fund are redirected toward the growth of the protocol. ### **Liquidity Fee Settings**  * **liquidityMinFee:** minimum fee that LPs are required to pay when depositing liquidity. * **public liquidityMaxFee:**  maximum fee that LPs are required to pay when depositing liquidity. These fees are collected by the other LPs. * **public liquidityFeeK:** parameter that defines how sensitive the fee variation is; the higher it is, the more slowly the fee changes. ### **Funding Rate** * **fundingC Asset:** parameter that defines how high the Funding Rate is based on LP exposure; the higher this parameter is, the lower the FR will be under the same conditions. ### **Curve Parameters** * **shortCurveParameterA, shortCurveParameterB, longCurveParameterA, longCurveParameterB:** parameters that affect the system’s slippage by defining how quickly it changes based on trade size. These parameters therefore determine, given the same liquidity conditions and all other market parameters, the slippage: meaning how far the trader’s execution price deviates from the oracle price. Slippage thus represents a cost for traders and a gain for LPs. --- # Trading Fees and Others Canonical page: https://docs.denaria.finance/protocol-architecture/trading-fees Status: current ### Trading Fees By default, Denaria applies two types of fees when trading: - **Trade fee** → A fixed percentage fee of 0.1% is charged on the notional value of every trade, both when opening and closing positions. This fee is collected in the quote asset (vStable). - **Flat fee** → A separate fee is applied to cover gas sponsorship costs. This fee ensures the protocol remains economically sustainable by offsetting blockchain interaction expenses. As of today, this fee is $0.12. ### Trading Fee Breakdown and Distribution The protocol uses a flexible mechanism to define how fees are allocated. A configurable percentage `ϕ` of each fee is assigned to the **protocol** and **Insurance fund,** while the remaining `(1 - ϕ)` is distributed to **liquidity providers.** As today, the ratio for the distribution of the fees is the following: - **50%** to Liquidity Providers - **30%** to Frontend Providers - **20%** to Insurance Fund. When cap, to Protocol ![](https://docs.denaria.finance/img/protocol%20Architecture/09_tradingFees.png) ### Other Fees - **Funding fee** → A funding fee is paid or received based on market conditions. Please explore this topic in the dedicated section [Funding Rate](/protocol-architecture/funding-rate) - **Withdraw stable** → Sending stablecoins out of the PWA incurs a flat fee of $0.12. This fee is used to cover blockchain transaction costs and prevent spam attacks. - **Add/Remove collateral** → Adding or removing collateral in a trade position incurs a flat fee of $0.12. This fee is used to cover blockchain transaction costs and prevent spam attacks. --- # Testing Stats Canonical page: https://docs.denaria.finance/security/testing-stats Status: current ### Some Stats About Denaria The following stats clearly demonstrate the depth and intensity of the Denaria testing process, validating both the robustness and reliability of the protocol over time. **Demo stats** * 6,400 traders onboarded, with 4,600 users completed Proof of Personhood verification * $3.5B total trading volume, with $2.1B traded in long positions and $1.4B traded in short positions * 118,000 total trades * 85,000 liquidations recorded **Testnet stats** * Cumulative 8,700 users onboarded, with 5,900 users completed human verification * 133,000 trading positions executed * 11,700 positions liquidated by the liquidator ### **Risk Disclosure** Despite the rigorous validation, testing, and security review process, interacting with the protocol involves inherent risks. Users are encouraged to carefully review the [Risk Disclosure](/risk_disclosure) section before interacting with the protocol. --- # Security & Audits Canonical page: https://docs.denaria.finance/security/audits Status: current Denaria is a Perpetual DEX designed with the objective of having all critical components of the protocol fully onchain, minimizing reliance on trusted offchain infrastructure. This ambitious design choice required a **rigorous and security-first approach** starting from the earliest stages of protocol design. All core components of the protocol were designed and **implemented from scratch** to ensure a coherent, consistent, and fully integrated system aligned with this objective. Security in Denaria is conceived as a continuous validation process that begins during the ideation and design phases and extends through validation, implementation, and ongoing operation. The purpose of this section is to provide transparency into the security process adopted throughout the development of the protocol. ### **Security Validation Lifecycle** 1. **Modeling and simulation** \- A proprietary simulation framework was developed to test the behavior of the financial system, measure performance, and evaluate system behavior under stress conditions. This framework is continuously used to validate economic assumptions, stress-test extreme market scenarios, analyze liquidation flows, and support parameter tuning. 2. **Public incentivized off-chain demo** - A public, incentivized interface was released to allow real users to interact with the system logic through an offchain backend that mirrors the logic, enabling real-user validation. 3. **Public incentivized testnet** \- A public incentivized testnet was launched to validate the protocol’s smart contracts in a live onchain environment, testing execution logic, state transitions, liquidation mechanisms, funding flows, and accounting behavior under real network conditions. 4. **Internal security audits** \- Two rounds of internal security audits were conducted by an internal auditor who was not involved in the implementation phase, focusing on core protocol logic, mathematical correctness, access control, and potential economic or logical vulnerabilities. 5. **System Invariants** - A set of system invariants was defined and analyzed to identify unsafe states or inconsistencies within the protocol, ensuring correct collateral accounting, bounded risk exposure, and solvency across all valid system states. In parallel, continuous simulation and fuzz testing campaigns are run to explore a large number of possible system states and execution paths, validating protocol behavior under extreme and unexpected conditions. 6. **External Security Audits** - Two rounds of external security audits were conducted with the Consensys Diligence team. All identified issues were either fully remediated or assessed as not requiring corrective action, and the final audit report summarizes the findings and resolutions. [Full Report Here](https://diligence.security/audits/2025/09/denaria-2/) 7. **Fine Tuning** -  An extensive testing campaign was conducted using the simulation framework and aggregated testing data to calibrate protocol parameters and reach the desired security, stability, and performance standards. Explore the Perp Parameters here: [Perp Parameters](/protocol-architecture/perp-parameters) 8. **Continuous Security & Responsible Disclosure** \- The protocol is continuously monitored and improved to enhance financial security and system performance, including proactive hack-prevention mechanisms such as invariant-based rules that are enforced and blocked at the sequencer level to prevent invalid or unsafe transactions. 9. **Assertions Validation** \- An innovative security system has been implemented that allows transactions to be excluded directly at the sequencer level if they do not comply with certain rules. This makes it possible to prevent specific and sophisticated attacks that may not have been identified during the security validation lifecycle. --- # Assertions Canonical page: https://docs.denaria.finance/security/assertions Status: current Denaria, in collaboration with the [Phylax team](http://docs.phylax.systems), has implemented an innovative security system. Thanks to the Credible Layer technology, it is possible to define rules, called assertions, which, if not satisfied, cause transactions to be excluded and therefore not executed. This technology allows the introduction of rules that must hold for transactions interacting with specific contracts. When a transaction interacts with a contract that is subject to an assertion, the rule is evaluated; if it is not satisfied, the sequencer does not include the transaction in the block, and it is therefore not executed. ### Bad Debt Assertions The first assertion we implemented follows this logic: **_Any user cannot cause bad debt to himself as a result of his transaction._** This rule translates into the following mathematical formulation: _For any user U and any transaction T that interacts with user U:_ Let: _PnL\_post(U) = PnL(U) after transaction T_ _Collateral\_post(U) = Collateral(U) after transaction T_ _Then the following invariant must hold:_ _Collateral\_post(U) + PnL\_post(U) ≥ 0_ Any transaction that does not satisfy this rule is not included in the block at the sequencer level and therefore not validated by the chain. This assertion prevents some: * Protocol bugs that cause unexpected losses. * Economic attacks that intentionally produce bad debt. * Implementation errors in protocol operations. And still allows: * Normal protocol operations (trades, liquidity deposits, and withdrawals). * Legitimate liquidations, which may cause bad debt without failing the assertion. --- # Protocol Whitepaper 0.1 Canonical page: https://docs.denaria.finance/protocol-whitepaper-v01 Status: archived Version: 0.1 Last reviewed: Fri Jul 10 2026 00:00:00 GMT+0000 (Coordinated Universal Time) Audience: developer ## Protocol overview Perpetual futures are derivative contracts that allow users to speculate on the future price of an underlying asset without an expiry date. In our protocol, every perpetual contract revolves around two virtual assets. The first, vAsset, mirrors the underlying asset whose price the trader intends to predict, while the second, vStable, is a dollar‑pegged stablecoin employed solely for accounting and quotation. Users never purchase or sell the real underlying asset; their positions exist only in these virtual tokens, which they exchange through our dynamic virtual automated market maker (dynAMM). The protocol's architecture intertwines several modules. A **multi‑collateral vault** secures user deposits; the **dynAMM** provides price computation and trade execution; an in‑house **share‑tracking algorithm** keeps precise records of each liquidity provider's contributions and fee earnings; a dedicated **funding fee mechanism** limits market exposure; a carefully designed schedule of trader and LP **fees** stabilizes the pool; and, finally, a **liquidation process** safeguards solvency whenever positions become under‑collateralised. Together these components create a seamless environment where traders can take leveraged positions and liquidity providers (LPs) can earn fees while managing risk. Interaction with the system begins with depositing collateral. The vault accepts several approved assets and does not impose rigid, hard‑coded ratios between them, so users may deposit any blend of the allowed tokens, subject only to mild limits that prevent extreme changes in the vault's composition. When a position is opened, the collateral is locked and any profit‑and‑loss (PnL) payments are, under ordinary circumstances, returned in the same proportions as the original deposit. If the vault's overall mix differs sharply from a new user's deposit -imagine the vault holds mostly Asset A, but the user provides Asset B- the protocol dynamically adjusts withdrawals so that payouts reflect both the vault's global ratios and the user's preferred mix. The first version of our protocol restricts collateral to USD‑pegged stablecoins, valued initially at one dollar each. Each underlying asset has its own dedicated vault. After funding their account, users may borrow vAsset or vStable up to the leverage cap. vAsset is valued through an external oracle, while vStable is fixed at one dollar. These vTokens remain internal bookkeeping entries; they never leave the protocol. To open a long position the trader borrows vStable and swaps it for vAsset in the dynAMM; to close, the trader performs the inverse swap, and the difference between vStable repaid and vStable received---adjusted for funding payments---constitutes the final profit or loss. The dynAMM itself continuously recentres its pricing curve on the oracle price, following mathematics akin to Curve's StableSwap and CryptoSwap [1], [2] formulas but re‑implemented from scratch for gas efficiency. As a result, trades are executed at the prevailing market price with minimal slippage, and the funding rate is no longer tied to AMM slippage. Liquidity providers may supply balanced, imbalanced, or even single‑sided liquidity, enabling precise control over exposure---depositing only vAsset, for example, is equivalent to taking a passive short. Because every trade shifts the pool's composition, we maintain each LP's claim with a single global accumulator plus periodic per‑LP snapshots, an approach that keeps gas costs low without sacrificing accuracy. Trading fees are charged on every swap and collected in vStable, while additional composition fees steer LP deposits toward a healthy pool balance. Funding payments counteract prolonged market trends: traders on the popular side pay, and traders on the less‑popular side receive, a fee proportional to position size and a novel funding rate computed from LP exposure rather than a mark‑index price gap. The same accumulator‑and‑snapshot technique that tracks LP shares also measures each account's funding liability or entitlement. Positions must maintain a minimum margin ratio, defined as collateral value after PnL were applied divided by the notional position value. If this ratio falls below the liquidation threshold, anyone may liquidate the position by purchasing it at a discount. The discount is chosen so that slippage cannot erode the liquidator's expected profit, ensuring strong incentives to keep the system solvent. ## Multi stable-asset collateral vault {#vault} In the initial release of the protocol, collateral is restricted to USD‑pegged stablecoins. Users may deposit any combination of the approved coins in whatever proportions suit them, and -under ordinary conditions- their PnL is settled in those same proportions. This symmetry cannot always be satisfied, though. Suppose a vault contains funds from only two users, one who contributed exclusively stablecoin A and another who supplied only stablecoin B. The vault clearly cannot satisfy each payout in the exact coin mix originally deposited. To handle such situations the protocol employs an adaptive settlement algorithm, outlined in this next section, that redistributes assets fairly whenever the vault's composition diverges from a user's preferred mix. The user is permitted to deposit collateral in any of $n$ stablecoins, denoted by Stable_1 to Stable_n . Let $y_1,...,y_n$ the amount of each coin he deposits respectively as collateral. Some $y_i$ can be 0. We define: $$ r_i = \frac{y_i}{y_1 +y_2...+y_n}, i=1,2,...n $$ All the stable coins are assumed to hold their peg. The sum in the denominator (let's denote it by $y$) is the total value in USD deposited as collateral by the user. If these ratios were the same for each user we could force the users to pay for their PnL in these same ratios and then the system would have the desired properties. But this would be too restrictive, so we will describe a more flexible approach. We denote by $r_{i,tot}$ the same ratios for the whole system/vault before the new collateral deposit i.e if $y_{1,tot},...y_{n,tot}$ the total amount of Stable_1 to Stable_n tokens in the vault before this new collateral deposit: $$ \tag 1 r_{i,tot}=\frac{y_{i,tot}}{y_{1,tot}+...+y_{n,tot}} $$ and by $r'_{i,tot}$ the total ratios after the new deposit i.e.: $$ \tag 2 r'_{i,tot}=\frac{y_{i,tot}+y_i}{(y_{1,tot}+y_1)+...+(y_{n,tot}+y_n)} $$ - The user is free to deposit collateral in any ratio provided that: $$ \tag 3 \left| \frac{r_{i,tot}-r'_{i,tot}}{r_{i,tot}}\right|< th_i $$ The thresholds $th_i$ will be determined before deployment. - When the user wants to close his position: Let's say that his total PnL are $y_{PnL}$ USD (negative PnL means that the user should be paid and positive that he should pay). The total USD value of the collateral he can withdraw is $y-y_{PnL}$. We compute $r'_i, i=1,2,...n$, as described below, and give him back $r'_1\cdot (y-y_{PnL})$ Stable_1 , \... $r'_n\cdot (y-y_{PnL})$ Stable_n . **Computation of the ratios**:If everyone was depositing collateral in the exact same ratios $r_i$, then $r'_i$ should also be equal to $r_i$, meaning the user pays their PnL proportionally to their initial deposit. However, since not everyone deposits collateral at the same ratio, $r'_i$ will depend on the user's initial ratio ($r_i$), as long as the total ratios of the pool immediately before ($r_{i,tot}$) their collateral withdrawal. We first compute $dy_i=(y-y_{PnL})\cdot r_i$ and then the total ratios after the withdrawal: $$ \tag 4 r'_{i,tot}=\frac{y_{i,tot}-dy_i}{(y_{1,tot}-dy_1))+...+(y_{n,tot}+dy_n )} $$ Observe that the denominator equals $y'=y_{1,tot}+...+y_{n,tot}-(y - y_{PnL})$ and therefore does not depend on the splitting. If $$ \tag 5 \left| \frac{r_{i,tot}-r'_{i,tot}}{r_{i,tot}}\right|< th'_i $$ holds for every $i$, we set $r'_i=r_i$ for every $i$. The withdrawal threshold $th'_i$ could be the same or smaller than $th_i$. If the above condition is not satisfied, or if some of the $dy_i$ as copmputed above exceed the available $y_{i,tot}$ in the vault, we set $r'_i=r_{i,tot}$ for every $i$. *Note*: We are aware that the user can bypass the restrictions (3) and (4) by splitting his deposit or withdrawal to smaller ones that will gradually shift the total ratios of the vault. A mitigation against it is to use instead of the actual ratios $r_{i,tot}$ time averages. ## Dynamic AMM {#vAMM} Every perpetual protocol needs a pricing mechanism -a way to decide how much vAsset a trader receives for their vStable when opening a long position and vice verse for short- while keeping that quoted price aligned with the underlying market price. Traditionally, protocols either use oracle pricing, which takes the live market price of the underlying from an oracle, or virtual AMM (vAMM) pricing, which lets a constant‑product AMM determine the price and relies on arbitrage to pull it back toward the market. Our design blends the strengths of both. We start with an AMM that has very low slippage and then continuously re‑center its curve around the oracle price instead of waiting for external arbitrage. We call this mechanism a dynamic virtual AMM, or dynAMM. The dynAMM fairly compensates LPs because trades clear close to the true market value. Capital efficiency is preserved: minimal slippage protects the pool from being drained yet still lets trading pressure show up in prices. For traders, execution remains near the market price without needing outside market makers. Dynamic AMMs have been discussed in prior academic works [3], but not in the context of perpetual futures and only for simpler AMM models. Our dynAMM extends the concept to a more sophisticated perpetual‑trading environment. In this section we denote by $(x_0,y_0)$ and $(x,y)$ the amounts of the two assets in the pool (vAsset and vStable respectively for our dynAMM case) right before thd right after a trade, respectively, and $p$ is the market price (provided by an external oracle) of the first asset with respect to the second one. We will introduce an invariant $I_{p,x_0,y_0}(x,y)$. From this equation one variable can be expressed in terms of the other -solving for $x$ yields $y$ and vice versa. Plotting $I_{p,x_0,y_0}(x,y) = 0$ in the $(x,y)$-plane produces a continuous curve. We choose the invariant so that this curve passes through the point $(x_0,y_0)$ and its spot price at that point, i.e. $-dy/dx$ equals $p$. As a result, trades clear close to the prevailing market price (small orders incur only minimal slippage; significant slippage appears only when the trade size becomes large). We construct the invariant by starting with the graph of a constant function, then applying suitable shifts and scalings so that it meets both conditions. The graphs for all the formulas discussed in this section can be found [here](https://www.desmos.com/calculator/ptnnvsv1eo). ### The formula of the dynAMM Our invariant is a dynamic extension of the Curve Finance invariant. For the sake of completeness -and because the resulting formulas may be useful beyond our protocol- we present a detailed derivation below. We begin by introducing two simpler invariants, whose combination will produce the final invariant. The first one is a dynamic version of the constant sum formula: $$ \tag 6 S_{p,x_0,y_0}(x,y) := \frac{p(x-x_0)+y-y_0}{px_0+y_0} $$ Using this invariant, all trades are executed exactly at the market price $p$, with zero slippage. Note also that this and all subsequent invariants are normalized and dimensionless. The second is a dynamic version of the constant product formula [4]. For this invariant there are two possible choices, as the shift can be applied either in the $x$ or the $y$ variable: $$ \begin{aligned} \tag 7 P^x_{p,x_0,y_0}(x,y) := 1 - \frac{y_0^2}{[p(x-x_0)+y_0]y} \\ P^y_{p,x_0,y_0}(x,y) := 1 - \frac{px_0^2}{[y-y_0+px_0]x} \end{aligned} $$ Although both shifted versions of the constant product formula exhibit qualitatively similar behavior, they define two distinct AMMs -meaning that, for the same input, they produce entirely different outputs. We use the first version for short positions and the second for long positions. Here's why: Consider the first formula. A key distinction arises between the cases $p\cdot x_0 < y_0$ and $p\cdot x_0 >y_0$ (the special case $p\cdot x_0 =y_0$ corresponds to the standard -non dynamic- constant product formula). When $p \cdot x_0 y_0$, the graph can be used for both longs and shorts. But for long positions in particular, the graph becomes asymptotic to the line $x = x_0 - y_0/p$. This implies that the amount of the x-asset cannot decrease below this threshold, which limits the efficiency of the AMM -it prevents full utilization of the x-asset in the pool. This inefficiency becomes especially pronounced when $p\cdot x_0 >> y_0$. For the second formula, this behavior is reversed: it is more suitable for long positions and less effective for shorts. We would prefer a dynAMM that combines the best properties of both the constant sum and constant product formulas. Specifically, we would like its graph to approximate the constant sum curve for values of $(x,y)$ close to $(x_0,y_0)$. This approach minimizes slippage for swaps that do not significantly move the pool, ensuring such trades are executed near the market price $p$. However, for larger swaps that shift the pool far from $(x_0,y_0)$, significant slippage should apply, as with the constant product rule, to prevent the pool from being depleted. This behavior can be achieved by defining a new invariant that is a linear combination of the constant sum and constant product invariants: $$ \tag 8 A_{p,x_0,y_0}(x,y) \cdot S_{p,x_0,y_0}(x,y) + P^x _{p,x_0,y_0}(x,y) = 0 $$ for short positions and $$ \tag 9 A_{p,x_0,y_0}(x,y)\cdot S_{p,x_0,y_0}(x,y) + P^y _{p,x_0,y_0}(x,y) = 0 $$ for long. $A_{p,x_0,y_0}(x,y)$ should be a positive function. Observe that for $A=0$ we get the (shifted) constant product formula and for $A \rightarrow\infty$ the constant sum. The graph of this new AMM will lie between the graphs of the constant sum and that of the constant product. We will use a function $A_{p,x_0,y_0}(x,y)$ inspired from Curve: $$ \tag{10} A_{p,x_0,y_0}(x,y)=\frac{Ay_0^4}{\left( By_0^2+y_0^2-[p(x-x_0)+y_0]y \right)^2} $$ We can then can write the invariant as a polynomial equation of degree 3: $$ \tag{11} ay^3+by^2+cy+d=0 $$ where: $$ \begin{aligned} a &= \lambda ^3\\ b &= \frac{Ay_0^4}{px_0+y_0}\lambda -2\lambda^2By_0^2-3y_0^2\lambda^2\\ c &= \lambda \left(\frac{Ay_0^4}{px_0+y_0}(p(x-x_0)-y_0)+(B+1)^2y_0^4+2(B+1)y_0^4 \right)\\ d &= -y_0^6(B+1)^2\\ \lambda &= p(x-x_0)+y_0 \end{aligned} $$ For longs we can use: $$ \tag{12} A_{p,x_0,y_0}(x,y)=\frac{Ap^2x_0^4}{\left( Bpx_0^2+px_0^2-[y-y_0+px_0]x \right)^2} $$ and the corresponding polynomial equation is: $$ \tag{13} ax^3+bx^2+cx+d=0 $$ where: $$ \begin{aligned} a &= \lambda ^3\\ b &= \frac{Ap^2x_0^4}{px_0+y_0}\lambda p -2\lambda^2(B+1)px_0^2-px_0^2\lambda^2\\ c &= \lambda\left( \frac{Ap^2x_0^4}{px_0+y_0}(y-y_0-px_0)+(B+1)^2p^2x_0^4+2p^2x_0^4(B+1) \right)\\ d &= -p^3x_0^6(B+1)^2\\ \lambda &= y - y_0 +px_0 \end{aligned} $$ We will also need the \"inverse\" formulas of the above. To compute the amount of vAsset required to receive a specified amount of vStable, the following equation should be used: $$ \tag{14} ax^3+bx^2+cx+d=0 $$ where: $$ \begin{aligned} A' &=\frac{Ay_0^4}{px_0+y_0}\\ \lambda &= y-y_0-px_0\\ k &= y_0-px_0\\ a &= p^3y^3\\ b &= A'y p^2 + 2p^2y^3k - 2p^2(B+1)y_0^2y^2 +(ky-y_0^2)p^2y^2\\ c &= A'py(k+\lambda) + (B+1)^2py_0^4y + pk^2y^3 -2(B+1)py_0^2y^2k + 2py^2k(ky-y_0^2) - 2(B+1)y_0^2yp(ky-y_0^2)\\ d &= A'yk\lambda + (ky-y_0^2)(B+1)^2y_0^4 + (ky-y_0^2)k^2y^2 - 2(B+1)y_0^2yk(ky-y_0^2) \end{aligned} $$ If the state of the pool before the trade was $(x_0,y_0)$ and someone wants to get exactly $dy$ vStable ($y=y_0 - dy$), he should add to the pool $dx$ vAsset ($x=x_0 + dx$), and this $dx$ can be found by solving equation (13). Also, we can use this equation to compute the amount of vAsset a user should add to the pool to get the amount of vStabe he needs to close his long position.\ On the contrary, to calculate the amount of vStable required to obtain a specific amount of vAsset, we use the following equation: $$ \tag{15} ay^3+by^2+cy+d=0 $$ where: $$ \begin{aligned} A' &=\frac{Ap^2x_0^4}{px_0+y_0}\\ \lambda &= p(x-x_0)-y_0\\ k &= px_0 - y_0\\ a &= x^3\\ b &= A'x + 2x^3k - 2p(B+1)x_0^2x^2 +(kx-px_0^2)x^2\\ c &= A'x(k+\lambda) + (B+1)^2p^2x_0^4x + k^2x^3 -2(B+1)px_0^2x^2k + 2(kx-px_0^2)kx^2 - 2(B+1)(kx-px_0^2)px_0^2x\\ d &= A'xk\lambda + (kx-px_0^2)(B+1)^2p^2x_0^4 + (kx-px_0^2)k^2x^2 - 2(B+1)px_0^2xk(kx-px_0^2) \end{aligned} $$ If the state of the pool before the trade was $(x_0,y_0)$ and someone wants to get exactly $dx$ vAsset ($x=x_0 - dx$), he should add to the pool $dy$ vStable ($y=y_0 + dy$), and this $dy$ can be found by solving equation (15). Also, we can use this equation to compute the amount of vStable a user should add to the pool to get the amount of vAsset he needs to close his short position. *Note*: In the smart contract implementation, we solve these equations using numerical methods, specifically Newton's method. We chose to work with the polynomial form of the invariant because, once the polynomial coefficients are computed, each iteration of the numerical method becomes simpler---and, importantly, more gas-efficient. ### Using our dynamic vAMM to execute trades Let's now discuss how these formulas are employed to execute trades. Recall that in the previous sections we used distinct formulas/graphs for short and long positions (they coincide only when $x_0/y_0 = p$). This was done to ensure that the resulting equations yield positive solutions and that the deposited liquidity is used optimally for trades. For clarity -purely for exposition purposes without affecting the implementation- we combine these formulas and graphs into a single unified curve. This curve uses the formula for shorts when $x > x_0$ and the formula for longs when $x < x_0$, resulting in a graph that is both continuous and smooth, with a continuously differentiable first derivative. It can be described by an invariant $f(p, x_0, y_0, x, y)$, where the equation follows equation (11) or (14) for $x > x_0$, and equation (13) or (15) for $x < x_0$. How should a trade be executed? Since we would like to execute trades as close to the market price as possible -a key motivation behind our vAMM design-, we could do the following. We start by retrieving the current pool deposits ($x_0$ and $y_0$) along with the current market price $p$ from the oracle, and then solve the equation $f(x_0, y_0, p, x_0 + dx, y_0 + dy) = 0$, where $dx,dy$ are the exchanged amounts. In simpler terms, we continuously readjust the graph so that the initial state is always the current $(x_0, y_0)$, ensuring that the price asymptotically aligns with the market price and slippage remains minimal. However, this dynamic mechanism introduces a potential exploit: a user could split a larger position into several smaller trades, thereby reducing overall slippage. In the extreme, by splitting a position into infinitely small trades, the user could achieve an execution price arbitrarily close to the market price (albeit still marginally higher). To counter this exploit, we are imposing a minimum position size. Even without such a restriction, our dynamic vAMM ensures that LPs always receive at least the market price, thus protecting them from impermanent loss. We are also implementing another measure to prevent this attack. Rather than constantly readjusting the graph with every trade around the current state, we adjust it so that two consecutive trades in the same direction (for instance, opening two long or two short positions) executed in quick succession have the same impact -actually slightly worse for the user- as a single trade whose size is the sum of the two trades. This approach renders the attack ineffective. Let's discuss the specifics of how this works. For this method, the contracts will store three additional variables, denoted $dx_0$, $dy_0$, and $t_0$ (or $lastCurveUpdate$ in the contracts) and also the type of the last trade (long or short). Consider the case of long trades.A user executes a long trade (let's suppose that a long enough time has passed since the previous trade) by depositing $dy$ vStable and getting back $dx$ vAsset from the vAMM.We set $t_0$ to the current timestamp, $dx_0 :=+dx,dy_0 :=+dy$.We denote by $x_0,y_0$ the total amount of vAsset and vStable respectively in the vAMM after this trade. Let's assume the next trade is also long and its timestamp differs from $t_0$ by less than a specific threshold set in the contracts. If the user exchanges $dy'$ vStable, we first solve the equation $f(p,x_0+dx_0,y_0-dy_0, x_2, (y_0-dy_0)+dy_0+dy')$ for $x_2$ i.e. we align the graph around a state ( $(x_0+dx_0,y_0-dy_0)$)as if the previous long trade has not happened and we just deposited the total vStable amount of all the last long trades ($dy_0+dy'$) at once. The difference $dx_{tot}= (x_0+dx_0) - x_2$ is the total amount of vAsset someone would get if he executed both trades at once (actually a little bit less, because of the slippage inrease after the first trade).The amount of vAsset the second trader gets is computed as $dx_{tot}-dx_0$. We finally increase $dx_0$, $dy_0$ by $dx'$ and $dy'$ respectively and set $x_0,y_0$ equal to the total vAsset and vStable liquidity in the pool after this second trade. If the second trade was a short trade, or time more than the specified threshold had passed, we would reset $dx_0$ and $dy_0$ to 0 and would store this new timestamp as the new $t_0$. ## Algorithm for efficiently tracking the LP shares {#LP shares} We aim to allow imbalanced deposits, meaning LPs can contribute liquidity to the pool in proportions where the ratio of the two deposited assets does not necessarily match either the pool's current ratio or the market price. This flexibility allows LPs to implement more general strategies and select risk profiles that best suit their needs. However, this added flexibility introduces extra complexity into the system. The LP's share of each asset is not the same and, in fact, not even constant. Consider an edge case where an LP deposits only one asset. In this scenario, the LP's share for that particular asset is non-zero, but their share of the other asset is zero. After a swap that utilizes some portion of the deposited asset, the LP will also own a non-zero amount of the second asset. This change must be reflected in the dynamic adjustment of their shares. To make this approach feasible, we need an efficient method to compute these constantly changing shares in a way that is scalable and independent of the number of swaps or LPs. In these notes, we outline an algorithm to achieve this. By defining the LP shares dynamically, we can accurately track the liquidity that each LP can withdraw, depending on what they have deposited and also fairly distribute the fees earned through swaps, proportional to each LP's dynamically updated shares. ### Description of the algorithm Let's start by introducing some notation: - $t$: discritized time, updated by 1 after each action (either swap or liquidity deposit/withdrawal). - $x(t),y(t)$: the amount of the X and Y assets in the pool respectively, at time $t$. - $S_x(t),S_y(t)$: The total shares for the X and Y asset respectively, at time $t$. - $s_{x,i}(t),s_{y,i}(t)$: The shares of the $i$ LP for the X and Y asset respectively, at time $t$. The ratio of the LPs shares to the corresponding total shares, equals the percentage of the assset in the pool the LP owns and therefore can withdraw. We will prove in the next section that the shares of each LP are linear combinations of his initial shares (we assume for convenience that his deposit happened at time t=0): $$ \tag{16} \begin{aligned} s_{x,i}(t) &= M_{x,x}(t)s_{x,i}(0) + M_{x,y}(t) s_{y,i}(0)\\ s_{y,i}(t) &= M_{y,x}(t)s_{x,i}(0) + M_{y,y}(t) s_{y,i}(0) \end{aligned} $$ The coefficients are the same for all LPs, therefore if we can compute them efficiently we will be able to compute every LP's shares at every moment. We will also prove that these coefficients should be updated as follows, depending on the action (short trade, long trade or liquidity deposit/withdrawal). For long swaps (i.e. when a user gets an amount of X asset from the pool and deposits an amount of Y asset): $$ \begin{aligned} & M_{x,x}(t+1) = M_{x,x}(t)\\ & M_{x,y}(t+1) = M_{x,y}(t)\\ & M_{y,y}(t+1) = M_{y,y}(t) + M_{x,y}(t) \cdot A_y(t+1)\\ & M_{y,x}(t+1) = M_{y,x}(t) + M_{x,x}(t) \cdot A_y(t+1) \end{aligned} $$ For short swaps (i.e. i.e. when a user gets an amount of Y asset from the pool and deposits an amount of X asset) $$ \begin{aligned} & M_{x,x}(t+1) = M_{x,x}(t) + M_{y,x}(t) \cdot A_x(t+1)\\ & M_{x,y}(t+1) = M_{x,y}(t) + M_{y,y}(t) \cdot A_x(t+1)\\ & M_{y,y}(t+1) = M_{y,y}(t)\\ & M_{y,x}(t+1) = M_{y,x}(t)\\ \end{aligned} $$ For liquidity deposits and withdrawals only the total shares are updated and not the individual shares (with the exception of the LP that deposits or withdraws, of course), therefore in this case the coefficients should not be updated. It will be very helpful to express these equations using 2x2 matrices. We define: $$ M(t) = \begin{bmatrix} M_{x,x} & M_{x,y} \\ M_{y,x} & M_{y,y} \end{bmatrix}(t) $$ Using this notation, the equations describing the updates of the coefficints can be written as: $M(t+1) = A(t+1) \cdot M(t)$ $$ M(0) = \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix} $$ where: $$ A(t+1) = \begin{bmatrix} 1 & 0 \\ A_y(t+1) & 1 \end{bmatrix} \quad \text{or }\quad \begin{bmatrix} 1 & A_x(t+1) \\ 0 & 1 \end{bmatrix} $$ if the swap is long or short respectively. The formulas for $A_x,A_y$ are given in the next section. The important thing is that they depend only on global variables (total shares, total deposits) and on the exchanged amounts and therefore are the same for all LPs. Applying recursively this formula we get theformula for $M(t)$: $$ \tag{17} M(t) = A(t)\cdot A(t-1) \dots A(1) $$ This formula can be used for the computation of the shares of an LP that has deposits since time $t=0$. If an LP deposits at time $t_0$ the matrix coeeficient for him should at time $t \geq t_0$ be: $$ \tag{18} M_{t_0}(t)=A(t)\cdot A(t-1) \dots A(t_0+1)=M(t) \cdot M^{-1}(t_0) $$ Putting all these together, the steps for computing the shares for the LPs are: - For the first LP we are minting shares equal to the deposited amounts (or any multiple of them). - At every action we update the matix $M$ using (17). - When a new LP deposits some liquidity we are computing his initial deposits $(s_{x,i}(0),s_{y,i}(0))$ and take a snapshot of the matrix $M$. Whenever we need to compute the shares of this LP, we should first compute the coefficient matrix using (18) and then use (16) replacing $M$ by $M_{t_0}$. ### Proof that the algorithm correctly computes the shares We will prove that (16) hold for every $t$ by induction. For $t=0$ this is trivial, since: $$ \begin{aligned} s_{x,i}(0) &= 1 \cdot s_{x,i}(0) + 0 \cdot s_{y,i}(0)\\ s_{y,i}(0) &= 0 \cdot s_{x,i}(0) + 1 \cdot s_{y,i}(0) \end{aligned} $$ We assume that the formulas are valid for $t$ and we will prove that they are also valid for $t+1$. The shares should be updated only after an action. We will study each action separately. **Long swaps**: A user buys a $dx$ amount of X-asset from the pool by depositing a $dy$ amount of Y-asset. Of course $dx$ and $dy$ are related through the formula of the AMM, but a nice feature of our approach is that it does not depend on the details of the AMM. The X-shares of the LPs do not change. What changes is the amount of X-asset corresponding to these shares. Each LP loses $dx\frac{s_{x,i}(t)}{S_x(t)}$ and therefore he should earn the same percentage in Y-assets. $y(t)$ is increased by $dy$. We increase the total Y-shares by: $$ \begin{aligned} & \delta S_y = S_y(t) \frac{dy}{y(t)} \Rightarrow \\ & S_y(t+1) = S_y(t) \cdot \left( 1+\frac{dy}{y(t)} \right) \end{aligned} $$ The i LP owns $\delta s_{y,i}$ of these extra $\delta S_y$ shares: $$ \begin{aligned} \delta s_{y,i} &= \delta S_y \frac{s_{x,i}}{S_x(t)}\\ &= s_{x,i}(t)\frac{S_y(t)}{S_x(t)}\frac{dy}{y(t)}\\ &= s_{x,i}(t)A_y(t+1) \end{aligned} $$ where $$ A_y(t+1)= \frac{S_y(t)}{S_x(t)}\frac{dy}{y(t)} $$ Therefore: $$ \begin{aligned} s_{y,i}(t+1) &= s_{y,i}(t) + \delta s_{y,i}\\ &= M_{y,x}(t)s_{x,i}(0) + M_{y,y}(t) s_{y,i}(0) + \left( M_{x,x}(t)s_{x,i}(0) + M_{x,y}(t) s_{y,i}(0) \right) \cdot A_y(t+1) \quad \text{(t inductive step)}\\ &= \left( M_{y,x}(t) + M_{x,x}(t) \cdot A_y(t+1) \right)s_{x,i}(0)+\left( M_{y,y}(t) + M_{x,y}(t) \cdot A_y(t+1) \right)s_{y_i}(0) \end{aligned} $$ **Short swaps**: The idea is identical, we only have to replace x by y and vice versa. **Liquidity deposits**:When a new LP deposits $dx$ and $dy$amounts in the pool, the shares of the old LPs do not change. Only the total shares change. For this new LP, the protocol should mint initial shares (assuming that the time of the deposit is $t+1$): $$ \begin{aligned} s_{x,i}(0) &= S_x(t)\frac{dx}{x(t)}\\ s_{y,i}(0) &= S_y(t)\frac{dy}{y(t)} \end{aligned} $$ and the total shares increase, as follows: $$ \begin{aligned} S_x(t+1) &= S_x(t)\left( 1 + \frac{dx}{x(t)} \right)\\ S_y(t+1) &= S_y(t)\left( 1 + \frac{dy}{y(t)} \right) \end{aligned} $$ ## Fees ### Fees for opening/closing a position Whenever a user opens, closes, or modifies a position, a small fee is applied. This fee is calculated as a percentage of the traded amount and is always denominated in the quote asset -vStable, in our protocol. By using a stable quote asset, fee revenues remain unaffected by market fluctuations. The fees collected are divided among: the protocol, the insurance fund, and the LPs. The portion allocated to the protocol supports ongoing development and maintenance. The insurance fund receives a share to cover potential losses in cases of bad debt when positions are closed. The remaining portion goes to LPs and is added directly to the liquidity pool. In the case of short positions, where vStable is taken from the pool, the LP fee distribution is based on each LP's vStable shares. For long positions, the distribution is instead based on their vAsset shares. This mechanism ensures LPs are fairly compensated according to the type of position being taken and the assets being utilized. ### Fees for liquidity deposits that imbalance the pool The protocol we are designing allows for liquidity deposits in any ratio $r =\frac{Dy}{Dx}$, where $Dx$ represents the amount of vAsset and $Dy$ the amount of vStable deosited by an LP in the pool. This includes one-sided liquidity deposits ($r=0$ or $\infty$).This flexibility is made possible by two key features of the protocol: - *The dynAMM*: This enables exchanges to occur near the market price, even when the ratio of total deposits in the pool differs from the market price. - *Two-Shares-Per-LP Mechanism*: This approach efficiently tracks the continuously changing shares of LPs for imbalanced deposits. This flexibility is an advantage of our protocol, as it allows LPs to implement strategies fitting their risk profiles and market expectations. For example, by depositing one-sided liquidity (e.g., only vAsset), an LP primarily gains short exposure, since traders can only buy their vAsset (although, over time, as trades occur, the LP's shares will naturally shift, and they will gradually own a mix of both vAsset and vStable). While this flexibility benefits LPs and allows for diverse trading strategies, it can also lead to imbalanced pools---where the ratio of total vStable to total vAsset in the pool deviates significantly from the market price. Although our protocol remains robust under such conditions, continuing to offer prices close to the market price for most trades, heavily imbalanced pools can result in higher slippage. We are implementing a fee mechanism for liquidity deposits that incentivizes LPs to help maintain a balanced pool. The pool is considered balanced when the ratio of vStable to vAsset in the dynAMM matches the current market price. To encourage this equilibrium, higher fees will be applied to deposits that increase the imbalance, while minimal or even zero fees will be charged for deposits that move the pool closer to balance. ## Funding payments {#funding} Funding payments are a core component of any perpetual protocol. While different protocols use various formulas to calculate funding rates (see [5] for a summary), they generally share two key features: - *Direction of Payments*: If the funding rate is positive, long positions pay short positions; if negative, short positions pay long positions. This is just a convention. - *Balancing the System*: Funding payments are designed to help balance the system.Although, what it means \"balancing of the system\" varies for each protocol. Most commonly, funding payments help keep the perpetual price (mark price) aligned with the index price (market price of the underlying asset). For instance, if the perpetual price is too high, funding becomes positive, encouraging shorts and discouraging further longs -helping prices converge. In our protocol, this alignment is already achieved through the dynAMM, which keeps the perpetual price close to the market price without relying on funding payments. This allows us to offer lower funding costs, giving us a competitive edge. However, funding payments serve broader purposes: - They incentivize traders to take the less popular side. - In balanced markets, the funding payments lead to positive returns for LPs; in directional markets, they help reduce LPs' losses. - They also reduce system exposure by discouraging the most popular positions and encouraging balanced participation, limiting the risk LPs must absorb. ### Definitions In its most general form the fundyng payment a position holder -either a trader or an LP- should make (or receive) is given by the formula: $$ \textit{Funding fees for the position} = \textit{position value} \cdot \textit{Funding rate} $$ where - positive funding fees means that the position should pay these fees and negative that the position should receive the fees. - position value: equals $\textit{(position size} \cdot \textit{price)}$, and is positive for long and negative for short positions - Funding rate: it is a global quantity (the same for every position), changes with time and trades and liquidity changes, is positive if longs should pay shorts and negative if shorts should pay longs #### The time component of the funding rate First, we need to determine how frequently the funding payments should be calculated and accounted for. To clarify, this does not necessarily mean that actual payments must occur immediately. The funding rate can be expressed as: $$ \textit{Funding rate = }\frac{\textit{Funding coefficient}\cdot \Delta t}{\textit{Funding Interval}} $$ where - *Funding coefficient*:T his is not a standard term and will be formally defined in a later section. It represents a global variable that updates with every user action (e.g. trades or liquidity deposits). - *Funding interval*: When time equal to the Funding interval has passed, the total fees (that should be paid) equal ( (Funding coefficient) $\cdot$ (total value of the most popular position type) ). The standard choice for the funding interval is 1 day (computed in seconds), but we could decrease it to increase the rate. - $\Delta t$: Represents the elapsed time (in seconds) since the previous user interaction (e.g. trade or liquidity update). Our system uses a continuous funding model rather than discrete time intervals. This approach minimizes the risk of manipulation -such as timing position changes around scheduled funding events- and ensures smoother, more consistent fee accrual. On each user action, the funding rate is computed using the current funding coefficient and $\Delta t$, after which the funding coefficient is updated to reflect the new state. #### Position sizes If $FF_j$ are the funding fees for a position $j$ (this could be either a trader or an LP position), then the sum of the funding fees should be zero (total sum of positive fees should equal minus the total sum of negative i.e. payments of funding fees should cancel out and there should be no need for extra funds). This should be true for every funding payment (after every action) and not only for total payments over a period. This is true iff: $$ \begin{aligned} \sum _j FF_j &= \sum _j \textit{Funding rate}\cdot \textit{Value of position j}\\ &= \textit{Funding rate}\cdot \sum _j \textit{Value of position j} \end{aligned} $$ i.e. iff the sum of the position values (positive for long and negative for shorts) is zero. The position value can be computed by multiplying the position size (that we have to define) by the price (average price over the time period between two consecutive actions -check the algorithms in the next section-): $$ \begin{aligned} \sum _j FF_j &= \textit{Funding rate}\cdot \sum _j \textit{Value of position j}\\ &= \textit{Funding rate}\cdot price \cdot \sum _j \textit{Size of position j} \end{aligned} $$ Therefore, the sum of the funding payments will be zero if and only if the sum of the position sizes is zero. This holds true because positions are opened by exchanging amounts in a vAMM. However, let's explore this further to clarify the details. A long trader will borrow vStable and exchange them in the vAMM for vAssets. Therefore at the end his vAsset debt will be zero (he didn't borrow any vAssets) and his vAssets balance will be the the output of the vAMM. In the contrary a short trader will borrow vAssets and exchange them for vStable. In both cases the difference: $$ \begin{aligned} \textit{Position size} = \textit{vAsset balance}-\textit{vAsset debt} \end{aligned} $$ captures the size of the position, that will be positive for longs and negative for shorts. $$ \begin{array}{|l|l|l|l|} \hline & & Debt & Balance \\ \hline \text{long trader} & vAssets & 0 & dx \\ \hline & vStable & dy & 0 \\ \hline \text{short trader} & vAssets & dx & 0 \\ \hline & vStable & 0 & dy \\ \hline \end{array} $$ The debt of a position changes only if the owner of the position interacts with the protocol to close or update the position. This is true for both traders and LPs. The balance of a trader can also only change by a direct interaction of the trader with the protocol, therefore a trader's position has constant size (between two interactions of the user with the protocol) and this simplifies the computation of the funding payments as we will see in the next section. The balance, and therefore the position size, of an LP constntly changes, as traders open positions transforming the liquidity of the pool from vStable to vAssets and vice versa. But we can still effectively compute these balances, using the shares: $$ \begin{aligned} \textit{j LP's balance at time t} = \frac{s_{x,j}(t)\cdot x(t)}{S_x(t)} \end{aligned} $$ When an LP deposits liquidity in the pool, this can be splitted into two actions: borrowing vAssets and vStable from the protocol (these amounts are his debts) and depositing these amounts to the pool (these are his balances). Therefore immediately after the deposit (until the first trade) the position of the LP is zero. Therefore initially all the positions, and therefore their sum, is zero. Since each trade is executed through an exchange in the dynAMM, it is clear that opening a new position simultaneously increases the LPs' total position by an equal amount with the opposite sign. As a result, all trades preserve the zero-sum of the funding payments. #### A new approach to funding rates using the total exposure Since the primary purpose of funding payments in our system is to reduce total exposure, we define the funding coefficient to be proportional to total exposure as follows: $$ \textit{Funding coefficient} = \frac{\textit{Total exposure}}{c\cdot \textit{Total liquidity}} $$ where - *c*: a constant between 0 and 1 (percentage of the pool liquidity) - *Total liquidity*: total liquidity in the pool. The exact definition is not really crucial. We just use it to be able to define when an certain exposure should be considered small or large. It can simply be computed as $p\cdot x + y$.Where $x$ and $y$ are the amounts in the pool and $p$ the market price. - *Total exposure*: Sum of long minus sum of short positions **only for traders**. Since, as we have shown, the sum of all the positions is zero, this is also equal to minus the total position of the LPs. Setting the funding rate proportional to this, the traders are incentivized to decrease the total exposure of the LPs. ### An algorithm for efficiently computing the funding payments of traders and LPs We denote by $F(t)$ the funding rate at time $t$ (actually it will be the funding rate times the market price i.e. funding fees = position size $\cdot$ price $\cdot$ funding rate and we store to $F$ the product price times funding rate). The initial value of the funding rate should be zero, since there are no open positions by traders at the protocol initially. The funding rate should change after each trade and liquidity deposit/withdrawal, the LP's positions change after each swap or if the owner of the LP position deposits/withraws and position of a trader changes only when he updates it and not when other users interact with the protocol. After each trade we also compute the total exposure $Exp(t) = Exp_s(t) \cdot p$ (where $Exp_s$ is the size in terms of vAssets of the total exposure i.e. balance of vAssets held by long traders minus debt of vAssets of short traders) and total liquidity $L(t)$. We denote by $T$ the funding interval. - Funding paymements for traders: - The user opens his position at $t_0$ and the previous trade happened $\Delta t$ seconds ago. The size of the position is $D x$ vAssets (positive for long and negative for short). - We update the funding rate: $$ \begin{aligned} F(t_0) &=F(t_0 - \Delta t) + \Delta F (t_0 - \Delta t)\\ &= F(t_0 - \Delta t) +\bar{p}\frac{Exp_s(t_0-\Delta t)\cdot \bar{p} \cdot \Delta t}{c\cdot L(t_0-\Delta t)\cdot T} \end{aligned} $$ and take a snapshot and store it at the user's state info. $\bar{p}$ is the average market price for the $\Delta t$ time interval. We can get it from the price oracle. $L(t_0 - \Delta t)= \bar{p}\cdot x(t_0)+y(t_0)$. - We update the total exposure size: $$ \begin{aligned} Exp_s(t_0) &= Expt_s(t_0 - \Delta t) + Dx\\ \end{aligned} $$ - When, at some time $t$, the trader decides to close or update his position, we first compute the current funding rate $F(t)$ and his total funding fees (positive means he has to pay, negatve means he should receive funding payments) as: $$ \begin{aligned} \textit{Total trader's funding fees}=Dy \cdot (F(t) - F(t_0)) \end{aligned} $$ These fees should be added to his pnl from price changes and then settled, by pairing the trader with another user with opossite side unsettled pnl (check the notes with the example about funding payments). We then make the changes in the pool and update the funding rate as described in the previous step. - Funding payments for LPs: - The funding rate is computed and updated as in the case of traders'. When an LP deposits or withdraw liquidity, the total exposure does not change (it is just distributed to the remaining LPs), but the funding rate changes because of the change of the total liquidity. The tricky part is that the LP position change not only when an LP interacts directly with the protocol, but on every trade. - If two consecutive actions happen at times $t_i$ and $t_{i-1}$, then for this time interval the total position hold by the LPs equals $-Exp(t_{i-1})$ and the funding payment corresponding to all the LPs are: $$ \begin{aligned} FP_{LP}(t_i) &= -Exp(t_{i-1}) \cdot \frac{Exp(t_{i-1})\cdot (t_i - t_{i-1})}{c\cdot L(t_{i-1})\cdot T}\\ &= -\frac{Exp^2(t_{i-1})\cdot (t_i - t_{i-1})}{c\cdot L(t_{i-1})\cdot T} \end{aligned} $$ Observe that it is always negative (i.e. LPs in total will always receive and not pay funding fees-although some individual LPs may happen to pay fees-) as expected. - The extra difficulty in the computation of the funding payments of LPs, compared to the funding payments for traders, is that an LP position chaanges not only when the LP actively interacts with the protocol, but also on every trade (since when a trader opens a position, the LPs take passively the opossite position). We denote by $FP_j(t_i)$ the total funding payments of the $j$ LP till time $t_i$ (positive if he has to pay, negative if he should receive a payment). $$ \begin{aligned} FP_j(t_i) &= FP_j(t_i-1) + (\textit{j LP's position size}) \cdot \Delta F(t_{i-1})\\ &= FP_j(t_i-1) + (x_j(t_{i-1})-d_j)\cdot \Delta F(t_{i-1})\\ &= FP_j(t_i-1) + x_j(t_{i-1})\cdot \Delta F(t_{i-1})-d_j\cdot \Delta F(t_{i-1})\\ \end{aligned} $$ where $x_j(t_{i-1})$ is the vAsset balance of the j LP at time $t_{i-1}$ and $d_j$ is his vAsset debt (the balance constanlty change after each trade, but the debt changes only if the LP interacts with the protocol). Recall that we can compute effectively the liquidity of each LP at every time using the shares: $$ \begin{aligned} x_j(t_{i-1}) &= s{x,j}(t_{i-1})\frac{x(t_{i-1})}{S_x(t_{i-1})}\\ &= \left( M_{x,x}(t_{i-1})\cdot s_{x,j}(0) + M_{x,y}(t_{i-1}\cdot s_{y,j}(0)) \right) \cdot \frac{x(t_{i-1})}{S_x(t_{i-1})} \end{aligned} $$ Therefore: $$ \begin{aligned} FP_j(t_i) &= FP_j(t_i-1) + \frac{M_{x,x}(t_{i-1})\cdot x(t_{i-1})}{S_x(t_{i-1})}\Delta F(t_{i-1})\cdot s_{x,j}(0)+\\ &+\frac{M_{x,y}(t_{i-1})\cdot x(t_{i-1})}{S_x(t_{i-1})} \Delta F(t_{i-1})\cdot s_{y,j}(0) -d_j\cdot \Delta F(t_{i-1}) \end{aligned} $$ Using matrices, this can be written as: $$ FP_j(t_i) = FP_j(t_{i-1}) + [1 \quad 0]B(t_i)M(t_{i-1})\cdot \begin{bmatrix} s_{x,j}(0)\\s_{y,j}(0) \end{bmatrix} - d_j \cdot \Delta F(t_{i-1}) $$ where $$ B(t_i) = \begin{bmatrix} \frac{x(t_{i-1}) \cdot \Delta F(t_{i-1})}{S_x(t_{i-1})} & 0 \\ 0 & 0\end{bmatrix} $$ - Therefore we should store a global matrix sum (actually we need only his first row -two sums-): $$ G(t_i) = G(t_{i-1}) + B(t_i)M(t_{i-1}) $$ - Take two snapshots: $G(t_0)$, $F(t_0)$ whenever an LP deposits liquidity (two extra snapshots along with the snapshot of the matrix M, used for the computation of the shares). Whenever we want to compute the total collected funding payments for the LP we use the formula: $$ FP_j=[1 \quad 0](G(t) - G(t_0))M^{-1}(t_0) \begin{bmatrix} s_{x,j}(0)\\ s_{y,j}(0)\end{bmatrix} - d_j\cdot (F(t) - F(t_0)) $$ ## Liquidations To maintain system solvency, positions must be liquidated when the ratio of collateral to position value falls below a specified threshold. Liquidation is the process by which a user's position is sold to another participant at a discount. This discount acts as a fee imposed on the liquidated user, incentivizing traders to maintain sufficient collateral and avoid liquidation. ### Liquidation criteria A position becomes eligible for liquidation based on its margin ratio (MR), calculated as: $$ \begin{aligned} \textit{MR}=\frac{\textit{account value}}{\textit{position value}} \end{aligned} $$ where: - *Account value*: The USD value of the deposited collateral minus the total PnL for the position and any funding payments. - *Position Value*: The size of the position multiplied by the index price of the underlying asset. Here, the index price is a time-weighted average of the market price over a few minutes (around 10 minutes). We should avoid using the actual (spot) market price to avoid liquidations due to temporary price fluctuations. We define several margin thresholds: $$ \begin{aligned} MM_1>MM_2>...>MM_n \end{aligned} $$ and corresponding percentages: $$ \begin{aligned} p_1 1. [M. Egorov, *StableSwap- efficient mechanism for stablecoin liquidity*](https://docs.curve.fi/assets/pdf/whitepaper_stableswap.pdf) 2. [M. Egorov, *Automatic market-making with dynamic peg*](https://docs.curve.fi/assets/pdf/whitepaper_cryptoswap.pdf) 3. [B. Krishnamachari, Q. Feng and E. Grippo, *Dynamic Automated Market Makers for Decentralized Cryptocurrency Exchange*, 2021 IEEE International Conference on Blockchain and Cryptocurrency (ICBC), Sydney, Australia, 2021, pp. 1-2](https://anrg.usc.edu/www/papers/dynamicautomation.pdf) 4. [H. Adams, *Uniswap whitepaper*](https://hackmd.io/C-DvwDSfSxuh-Gd4WKE_ig#Introduction) 5. [*Funding rates:under the hood](https://medium.com/derivadex/funding-rates-under-the-hood-352e6be83ab) **Disclaimer**\ \ \ **Educational and Scientific Purpose**: This whitepaper and all contents herein are provided strictly for scientific, educational, and informational purposes only. The technical designs, financial models, and mechanisms described in this paper represent theoretical constructs and should not be interpreted as financial, investment, legal, or tax advice.\ **Intellectual Property Notice**: The implementation of Denaria's design into smart contracts is protected under a Business Source License. To learn more about the Business Source License visit mariadb(dot)com.\ **No Guarantees or Warranties**: The information provided in this paper is presented \"as is\" without any representations or warranties, express or implied. Denaria makes no guarantees regarding the accuracy, completeness, timeliness, suitability, or validity of the information contained herein. All forward-looking statements, projections, or future plans mentioned in this document are speculative in nature.\ **Risk Disclosure**: Decentralized finance (DeFi) protocols, particularly those involving perpetual derivatives, carry significant risks including but not limited to: smart contract vulnerabilities, market volatility and liquidation risks, regulatory uncertainty, oracle failures or manipulations, economic design flaws, and governance attacks. Users and developers who choose to interact with any implementation of the designs described in this paper do so entirely at their own risk.\ **Regulatory Compliance**: This paper does not constitute an offer to sell, a solicitation of an offer to buy, or a recommendation of any cryptocurrency, digital asset, or any other financial instrument. Users must ensure their compliance with all applicable laws and regulations in their respective jurisdictions before interacting with any implementation of the designs described.\ **Independence of Action**: No part of this document should be interpreted as encouraging or soliciting any person to engage in any action or transaction. All decisions related to the use of any protocol or product derived from this paper should be made independently after conducting appropriate due diligence.\ **Living Document**: This whitepaper is subject to updates, modifications, and amendments without prior notice. Readers are responsible for ensuring they are reviewing the most current version. --- # Protocol Whitepaper 0.2 Canonical page: https://docs.denaria.finance/protocol-whitepaper-v02 Status: current Version: 0.2 Last reviewed: Fri Jul 10 2026 00:00:00 GMT+0000 (Coordinated Universal Time) Audience: developer [Download Whitepaper](https://docs.denaria.finance/img/whitepaper/whitepaper02.pdf) ---