Stablecoins and leverage trading are the backbone of the crypto industry.
Surprisingly, most efficient approaches so far relied on a trust assumption that is the opposite of what DeFi stands for.
This time is over; let's dive into f(x) Protocol's paradigm shift.
Stablecoins
Most stablecoins are either centralized, capital inefficient or have unreliable pegs.
DeFi users, DAOs, and institutions need a scalable stablecoin that doesn't require trusting any entity.
Moreover, they need it to provide sustainable and attractive yields.
Leverage
By design, gaining leverage exposure can be dangerous. Liquidations melt the capital of the most adventurous traders, while funding rates erode it regardless.
Regarding decentralization, most perps are built on centralized layers or rely on centralized execution elements, while the decentralized money markets offer very low leverage options.
The Genesis
March 2023, the most trusted stablecoin across DeFi, USDC, lost its peg toward $0,86 due to the collapse of a TradFi institution: the Silicon Valley Bank.
Aladdin DAO attended, noted the above points, and, drawing on their experience as Concentrator and CLever, decided to change the paradigm of stablecoins and decentralized leverage forever.
f(x) Protocol V1 was released on August 2023. By splitting any yield-bearing asset into a zero-volatility asset (stablecoin) and a high-volatility asset (leveraged token), it has already created the most capital-efficient decentralized stablecoin ever while offering a zero-liquidation solution for leverage traders.
But the system could constantly be improved.
16 months and $70m TVL later, f(x) Protocol now unleashed it's V2 bringing:
On the leverage side.
Up to 7x leverage on ETH and BTC
Very minimized liquidation risk thanks to the rebalancing mechanism
No funding cost under normal market conditions
On the stable side, the first USD strategy:
Stays perfectly USD delta-neutral
Captures perp trading commissions
Earn enhanced stETH and WBTC yield
TLDR: the most attractive, scalable & sustainable, decentralized, stable yield strategy.
This documentation is here for you to get all the ins and outs of f(x) Protocol. You may finds all your questions answered.
Has no counterparty risks
Is 100% on-chain and doesn't rely on RWA
Key Functions of f(x)
Opening and Closing xPOSITION - Minting fxUSD
Users can open xPOSITION by providing stETH or WBTC as collateral. fxUSD is minted as a byproduct of the xPOSITION opening using the f(x) Invariant formula.
The system dynamically adjusts leverage ratios and fxUSD minting to maintain overall stability.
Opening an Closing sPOSITION
Users can open sPOSITION by providing fxUSD as collateral. The leverage is obtained using a flashloan which is repaid using the fxUSD's backing assets. .
The system adjust leverage ratios to maintain overall stability.
Rebalancing Operations
Automatically adjusts leveraged positions to safe levels (see ), significantly reducing liquidation risk.
This process is handled automatically by keepers.
Liquidation Mechanism
If rebalancing fails, the protocol initiates liquidation by redeeming associated fxUSD to always protect fxUSD's integrity.
This process is handled automatically by keepers.
Stability Pool
Offers yield opportunities for users while serving as a peg-keeper for fxUSD.
Maintains price stability through efficient arbitrage operations.
fxMINT allows you to mint fxUSD directly by depositing collateral (ETH/WBTC) at a 0% annual interest rate and with minimal liquidation risks. Instead of annual interests, we charge a one-time opening and closing fee for your loan. Keep the loan open for as long as you need. Note that a temporary borrowing cost can be applied to the whole collateral in rare circumstances. The mechanism is exactly the same as for xPOSITIONs, excluding the flashloan operation.
While xPOSITIONs give you overexposure to the collateral, fxMINT maintains a constant exposure while achieving better capital efficiency.
Using the xPOSITIONs infrastructure has multiple implications; let's break it down.
Here’s how the process works:
1. Collateral Submission
The user provides collateral (e.g., ETH or WBTC), which is used to mint fxUSD, the protocol's stablecoin, and fund the leverage mechanism.
2. Zap for Collateral
The protocol only uses wstETH and WBTC as collateral. If the users pledges WETH, it will be automatically swapped for wstETH. But remember, on f(x) Protocol, the collateral yields are mostly distributed to the stable stakers.
It means that your leverage position keeps an ETH or WBTC exposure and doesn't earn yield on the collateral.
3. Minting fxUSD
fxUSD is minted using your collateral. On f(x) Protocol, you only pay a one-time fee when opening the position and when closing it.
The fee is added to your debt position, resulting in a slightly higher amount of fxUSD to repay than what you receive in your wallet.
4. Repaying your debt
If you want to reduce your LTV/Leverage and or withdraw your collateral, you need to repay your fxUSD debt.
When doing so, the closing fee is applied to the amount of repaid debt.
Learn more about the fees below.
Understanding the temporary borrowing cost
Under certain market conditions, a temporary borrowing cost can be applied to your position. Since fxMINT utilizes the xPOSITION infrastructure, the cost is applied to the entire collateral. Please be aware that the lower the LTV of your position, the higher the borrowing cost is relative to your debt. Again, in most situations, that cost is temporary.
Learn more here:
What's the liquidation design for fxMINT?
Since fxMINT uses the same infrastructure as xPOSITIONS, the liquidation brake applies, protecting your position from any hard liquidation.
Learn more about the liquidation brake 🔽
Learn more about the liquidation brake and hard liquidation LTVs.
The f(x) Invariant is the core mechanism behind both V1 and V2. It enables on-chain leverage while delivering 100% capital efficiency for the stablecoins.
f(x) Protocol ensures that the total value of all fxUSD combined with the total value of all xPOSITIONs is always equal to the total value of the collateral reserves. Dynamic adjustments to the leverage ratio of xPOSITION and the peg ratio of fxUSD enable seamless collaboration between low-volatility stablecoins and high-leverage trading tools.
The relationship is represented as:
Where:
𝑛 is the number of TOKEN collateral,
𝑠 is the TOKEN price in USD,
nf is the number of fxUSD,
𝑓 is the fxUSD NAV in USD,
nx is the number of xPOSITION units, and
𝑥 represents the NAV of xPOSITION in USD.
This formula ensures that the system remains balanced, maintaining integrity and stability across its decentralized financial tools.
WIth the addition of sPOSITION, the invariant evolved to ensure every fxUSD, xPOSITION and sPOSITION remained fully backed and that the protocol maintaines internal solvency across both long and short positions.
The new invariant is:
Where:
𝑛 is the number of TOKEN collateral,
is the amount of TOKEN collateral borrowed for short positions,
𝑠 is the TOKEN price in USD,
nf is the number of fxUSD minted (longs),
n−f is the number of fxUSD locked (shorts),
X represents the NAV of xPOSITIONs in USD,
SP represents the total NAV of sPOSITIONs in USD.
n−
f(x) Protocol Documentation
The official source of information regarding f(x) Protocol
What is f(x) Protocol?
f(x) Protocol empowers DeFi to bring an innovative approach to stablecoins and leverage trading.
The f(x) invariant can split any yield-bearing asset into two components:
- A scalable decentralized stablecoin that captures sustainable on-chain real yield - fxUSD
- A leveraged position that delivers up to 10x leverage on ETH with minimal liquidation risk and funding cost - the xPOSITION.
On one hand, you can get the first USD delta neutral strategy that captures leveraged real yield (perps trading fees - ETH staking yield - FXN emissions) and; on the other hand, you can opt for a high-volatility position with minimized liquidation risk but without inherent yield.
100% on-chain & scalable. Let's get started 👇
Creating a Leveraged LONG Position (xPOSITION)
xPOSITION is a non-fungible, high-beta leveraged long position that provides a powerful decentralized tool for on-chain high-leverage trading. When a user opens an xPOSITION, the process is seamlessly facilitated through the use of a flash loan. This is executed via an atomic transaction, ensuring that all steps are completed successfully or the entire transaction is reverted, preserving the integrity of both user funds and the protocol.
Here’s how the process works:
1. Collateral Submission
The user provides collateral (e.g., stETH or WBTC), which is used to mint fxUSD, the protocol's stablecoin, and fund the leverage mechanism.
2. Flash Loan for Collateral
The protocol employs flash loans to obtain the required amount of collateral to back the leverage position. The flash loan and the position creation occur atomically, ensuring the entire transaction either execute completely or not at all, thus avoiding partial execution risks.
3. Minting fxUSD
For every unit of xPOSITION, the protocol mints the required amount of fxUSD to manage volatility and maintain full collateralization. For example, a 7x leveraged position will have 1 unit of xPOSITION backed by 6 units of fxUSD. Meanwhile, the underlying collateral remains in stETH or WBTC, harnessing its yield while maintaining the desired leverage ratio.
4. xPOSITION Creation
Once the collateral is secured through flash loans and the necessary fxUSD is minted, the leveraged position (xPOSITION) is activated. At this stage, the user gains exposure to the underlying assets, and their position is opened.
Understanding the band system
Rebalancing operations are handled when the underlying price reaches a certain threshold (see Risk parameters).
To maximize the efficiency of these operations and ensure it is profitable for the keeper to execute them, all xPOSITIONs are grouped into the same price bands.
Each price band width is 0.15%.
If your rebalance price is $1710, when the price of ETH falls below that price, all xPOSITION who have a rebalance price between $1710 and $1712 will be rebalanced together.
Example
Alice opens a 2x position when ETH trades at $3000. She will be rebalanced when ETH price falls 43.2%, which is $1704 (LTV=88%)
Bob opens a 5x position when ETH trades at $1880. He will be rebalanced when ETH price falls 9.09% which is $1704 (LTV=88%)
Both Alice and Bob put in the same band. Once ETH price falls below $1704, all positions in this band will be rebalanced and brought back below LTV=88%.
Rebalancing the Position (Liquidation Brake)
The rebalancing mechanism
After a position is opened, the protocol employs an automated rebalancing mechanism to maintain stability and ensure the leverage ratio stays within predefined safe limits.
Rebalance is an automatic operation triggered when the leverage of a position reaches a predefined threshold (rebalance line). The protocol adjusts the leverage to bring it back to the rebalance line instead of liquidating a significant portion of the position.
During this operation for xPOSITIONs:
fxUSD is first redeemed from the Stability Pool.
The underlying TOKEN is swapped for USDC to maintain system stability.
sPOSITIONs:
Borrowed asset is first paid back by keepers
The keeper gets fxUSD in return
1. Continuous Monitoring
External keepers continuously monitor market conditions and the leverage ratios of all open positions. If market fluctuations cause a position to drift outside safe leverage thresholds, the rebalancing mechanism is activated.
2. Reducing Leverage
xPOSITION & fxMINT - Via fxUSD Burning
If leverage exceeds the safe limits—such as when ETH or BTC prices drop—the protocol automatically burns a portion of the fxUSD associated with the xPOSITION. The collateral backing the burned fxUSD is sold for fxUSD or USDC and returned to the Stability Pool. This adjustment reduces the leverage ratio while maintaining the user’s exposure to the underlying asset, effectively avoiding liquidation.
This automated rebalancing process eliminates the need for manual interventions and prevents forced liquidations, offering users a more secure and reliable way to manage positions in volatile markets.
sPOSITION - Via debt repayment
If leverage exceeds the safe limits—such as when ETH or BTC prices surge—the protocol automatically repay a portion of the debt associated with the sPOSITION. The fxUSD backing the repaid debt is given to the keeper processing the operation. This adjustment reduces the leverage ratio while maintaining the user’s exposure to the underlying asset, effectively avoiding liquidation.
This automated rebalancing process eliminates the need for manual interventions and prevents forced liquidations, offering users a more secure and reliable way to manage positions in volatile markets.
Example of a rebalancing operation
Alice opens a 5x position with 1ETH when ETH trades at $3000. She will be rebalanced when ETH price falls 9.09%, which is $2727 (LTV=88% - see Risk parameters).
This is how her position looks at the opening.
ETH Price
xPosition size (USD)
Position size (USD)
Real time Leverage
fxUSD debt
LTV
$3000
$3000
$15000
5.00
$12000
80.00%
Lousy luck, ETH price collapsed by 10% and reached $2700: Alice's xPOSITION will be rebalanced.
Before rebalancing, this is how her position now looks:
ETH Price
xPosition size (USD)
Position size (USD)
Real time Leverage
fxUSD debt
LTV
$2700
$1500
$13500
9.00
$12000
88.89%
The rebalancing process must burn enough fxUSD from her debt to bring her LTV back to 88%.
The needed amount to burn can be calculated using the following formula.
The redeeming bounty (see Risk parameters) is added to this amount.
This is how the rebalancing process occurs:
$1000 worth of fxUSD are burnt from the stability pool and deducted from Alice’s debt
The corresponding amount of wsETH collateral + the keeper bounty is redeemed by the keeper.
The equivalent amount of fxUSD or USDC is returned to the Stability Pool.
Alice'sAfter the rebalancing process, Alice's position looks like this:
ETH Price
xPosition size (USD)
Position size (USD)
Real time Leverage
fxUSD debt
LTV
$2700
$1500
$12500
8.33
$11000
88%
Her real-time leverage was stabilized to prevent her from liquidation. She kept market exposure.
If the market recovers back to $3000:
Aladdin DAO's absolute priority is to ensure the integrity of all stakeholders' capital. Please find the incremental risk framework applied to f(x) Protocol below.
Rebalancing - Liquidation Brake
The liquidation brake mechanism maintains all leverage positions at the safest leverage levels in a progressive manner. It enables the best compromise between capital efficiency and the protocol's integrity.
In the event of failure in the previous step, hard liquidations can be triggered to preserve fxUSD's backing.
Reserve Fund
In the event of failure of the two previous steps, the protocol can face bad debt. A portion of the collected protocol fees is held in a Reserve Fund, which serves as a first layer of compensation in the event of any bad debt occurrence.
Bad Debt Redistribution
If the Reserve Fund can't compensate for all the bad debt, it is shared among the remaining leveraged positions.
More specifically:
In case of under-collateralized debt on xPOSITIONs, the shortfall is proportionally redistributed across active xPOSITIONs if the reserves are insufficient.
Regarding sPOSITIONS:
If the overall sPOSITION LTV is still below 100%, the system will redistribute bad debt from insolvent sPOSITIONs to healthy sPOSITIONs
Recapitalization
If the total collateralization ratio drops below 100%, the protocol halts new xPOSITION openings and deploys protocol assets to restore the fxUSD peg.
In the very unlikely occurrence of an overall sPOSITION LTV crossing 100%, which means all the previous steps would have failed:
All operations (open/close/rebalance/liquidate/redeem) are disabled
All outstanding sPOSITION bad debt gets charged as one-off funding to xPOSITIONs
All sPOSITIONs' outstanding collateral (fxUSD) is redeemed against xPOSITIONs. It works exactly the same as the fxUSD redemption process, except that there is no redemption fee in this case.
Offers up to 7x LONG and SHORT leverage on ETH and BTC
Fully decentralized, collateralized and on-chain
Minimal liquidation risk
Zero funding fees under normal market conditions, maximizing user returns
fxUSD (Stablecoin):
Fully decentralized and collateralized with a reliable and consistent peg
Minted and redeemed instantly in response to xPOSITION demand
Derives liquidity from collateral and generates sustainable on-chain yield
Creating a Leveraged SHORT Position (sPOSITION)
sPOSITION is a non-fungible, high-beta leveraged short position that provides a powerful decentralized tool for on-chain high-leverage trading. When a user opens an sPOSITION, the process is seamlessly facilitated through the use of a flash loan. This is executed via an atomic transaction, ensuring that all steps are completed successfully or the entire transaction is reverted, preserving the integrity of both user funds and the protocol.
Here’s how the process works:
1. Collateral Submission
The user provides collateral (fxUSD), which will be used to borrow directional collateral from the xPOSITION reserve.
2. Flash Loan for Collateral
The protocol employs flash loans to obtain the required amount of collateral (wstETH or WBTC) and sells it for fxUSD to back the leverage position, thus creating the short exposure. The flash loan and the position creation occur atomically, ensuring the entire transaction either executes completely or not at all, thus avoiding partial execution risks.
Please note that in the current iteration of sPOSITIONs, the ETH debt is wstETH-denominated. While the protocol doesn't charge any funding under normal conditions, the value of the debt naturally increases by the wstETH yield.
3. Borrowing directional assets from the xPOSITION reserve
The total fxUSD, consisting of both the user’s initial collateral and the flash loan-acquired fxUSD, is then deposited into the protocol to borrow the corresponding token (wstETH or WBTC) from the leverage long reserve. The borrowed collateral asset is immediately used to repay the flashloan, thereby establishing the user’s short position without requiring upfront access to the borrowed asset.
4. sPOSITION Creation
Once the collateral is secured through flash loans, the leveraged position (sPOSITION) is activated. At this stage, the user gains leveraged short exposure to the underlying assets, and their position is opened.
Stability Pool
Stability Pool is a cornerstone of the protocol, designed to maintain system stability and provide rewards for participants.
1. Purpose and Rewards
Users can deposit fxUSD or USDC into the Stability Pool to either earn:
- wstETH and WBTC (converted to wstETH) coming from xPOSITION fees and reserve yield and Aave yields.
- Or $FXN emissions.
This incentivizes participation and strengthens the protocol’s resilience.
2. Peg Stabilization
The Stability Pool ensures that fxUSD maintains its peg to USD through automatic swaps between fxUSD and USDC based on exchange conditions:
If fxUSD is undervalued: The pool swaps USDC for fxUSD to restore the peg.
If fxUSD is overvalued: The pool swaps fxUSD for USDC to stabilize its price.
These adjustments are executed using Chainlink oracle prices to ensure accurate valuations, offering price stability while optimizing returns for users.
3. Depeg Protection
In the rare event of a USDC depeg, the protocol halts peg maintenance and temporarily disables deposits to safeguard users and uphold system integrity.
4. Rebalance and Liquidation Procedures
When necessary, the protocol redeems fxUSD from the Stability Pool. If the pool lacks sufficient fxUSD, the USDC obtained is used to repurchase fxUSD at a ratio not exceeding 1:1, thereby stabilizing the peg.
5. Asynchronous or Synchronous Execution
Depending on market conditions, these operations can be carried out synchronously or asynchronously. This flexibility ensures sufficient liquidity while maintaining the fxUSD peg and supporting the overall stability of the system.
fxSAVE
fxSAVE is the tokenized stability pool built by (another protocol built by ). It is a 4626 vault that automatically compounds all wstETH and WBTC rewards into more fxUSD and USDC.
Another way of describing fxSAVE is that it is a yield-bearing stablecoin that harnesses the Stability Pool's yields.
Looking at integrating fxSAVE into your protocol or automating deposits and withdrawals? Check our docs. fxSAVE is fully integrated into Enso to facilitate interactions from any chain.
Learn how to deposit into the Stability Pool and earn Stable yield 👇
If the rebalancing process fails, your position could eventually reach the Liquidation line.
If that happens, the rest of the position is entirely closed. It uses the same mechanism as described in the Rebalancing section, with two differences:
The entirety of the debt is burned (xPOSITION) or repaid (sPOSITION)
The liquidation bounty isn't necessarily the same as for rebalancings
Redemptions act as a last resort protection of $fxUSD's peg. They should only happen if the other fail. For that reason, the redemption feature is only possible when fxUSD is deppeged according to the .
The redemption mechanism ensures that fxUSD can be redeemed for $1 worth of fxUSD's collateral.
The redeemed collateral is taken by reducing the debt xPOSITIONS, starting with the most leveraged one and not exceeding a certain proportion of each position before moving to the next leverage level.
It gives an incentive to buy discounted fxUSD and redeem it for its collateral for a profit while restoring fxUSD's peg.
The redemption can be triggered using the following . Please note that a redemption fee is applied.
Redemption fees and the maximum proportion of an xPOSITION to be redeemed can be found here.
f(x) offers the lowest trading commissions. To compensate for this, any unused slippage will be retained to incentivize stablecoin supply in the Stability Pool. You can set your own slippage.
The f(x) 2.1 price oracle mechanism for stETH/USD combines multiple data sources, including Chainlink, Uniswap, Curve, and Balancer, to calculate spot prices and anchor prices. It defines Max and Min Price for stETH/USD based on these sources and uses a governance-adjustable threshold (default 1%) to decide whether to rely on the Anchor Price or the Max/Min Price for operations like rebalancing, minting, or redeeming. This ensures accurate and stable pricing while accommodating market fluctuations. Below is the detailed breakdown of the stETH Spot Price Oracle Mechanism:
ETH/USD Spot oracle:
[]
[]
[]
stETH/ETH Spot oracle:
[]
[]
[
stETH/USD Anchor Price oracle:
[ ]*[]
The Algorithm of stETH/USD Max and Min Price:
Max: stETH/USD Price=Max(Anchor Price, [stETH/ETH Spot Max Price ]* [ETH/USD Spot Max Price ])
Min: stETH/USD Price=Min(Anchor Price, [stETH/ETH Spot Min Price ]* [ETH/USD Spot Min Price ])
Price Checking Mechanism:
Anchor Price is used, while the price difference between Anchor Price and Max/Min Price exceeds the threshold
The threshold is a governed parameter, 1% in default
Conclusion:
Min stETH/USD Price is used for Open/Close of xPOSITION risk control, Rebalance and Liquidation if the price difference between Anchor Price and Min Price doesn’t exceed the threshold. Anchor Price is used otherwise.
Max stETH/USD Price is used for Redeeming fxUSD if the price difference between Anchor Price and Max Price doesn’t exceed the threshold. Anchor Price is used otherwise.
Max stETH/USD Price is used for Open/Close of sPOSITION risk control, Rebalance and Liquidation if the price difference between Anchor Price and Max Price doesn’t exceed the threshold. Anchor Price is used otherwise.
Advanced Peg Protection Mechanisms
The protocol ensures fxUSD's peg at all times by implementing 4 different incremental peg-keeping mechanisms.
Stability Pool acts as Peg-Keeper
The stability pool accepts both fxUSD and USDC. If fxUSD trades below $1.00, it will automatically buy it and sell it back to USDC if fxUSD trades above $1.00.
➡️ Ensures fxUSD stability through arbitrage operations in the fxUSD/USDC AMM pool.
Operational Restrictions During Depegging
If fxUSD is depegged, new xPOSITION openings are prohibited. This prevents excessive fxUSD minting and reduces selling pressure on fxUSD.
➡️ No more selling pressure on fxUSD if traded below peg.
Funding Fees
If the Stability Pool lacks the needed assets to keep the peg close enough to $1, funding can temporarily be applied to x and s POSITIONS.
Different incremental levels of funding are used depending on the situation to keep the best peg while delivering the best user experience to leverage traders and minimizing their costs.
xPOSITION:
Funding fees of xPOSITONs are determined based on the percentage of fxUSD held within the Stability Pool:
When the percentage of fxUSD in the Stability Pool exceeds Threshold A, Funding Level I activates.
If fxUSD depegs and exceeds Threshold B in the Stability Pool, Funding Level II activates. This higher funding fee is set at a significantly elevated level (e.g., a multiplier of Aave USDC borrow rate) to accelerate deleveraging and encourage peg restoration.
This funding is delivered to:
The Stability Pool, making it more attractive to USDC deposits, thus facilitating the peg restoration.
sPOSITIONs, making it more attractive to open a short position that will support fxUSD's peg by essence.
➡️ The Stability Pool gets a high real yield, facilitating the peg keeping.
➡️ Users get an incentive to open sPOSITIONs when needed, preventing fxUSD's depeg.
sPOSITION:
The addition of sPOSITION to the protocol brings an organic and consistent buying pressure to fxUSD that may prevent the previous operations from being necessary.
sPOSITION funding fees are applied when the utilization of long collateral assets exceeds prudent lending thresholds.
When the percentage of leverage long collateral lent out to sPOSITIONs exceeds Threshold C, Funding Level III activates. This funding fee is applied to all open sPOSITIONs borrowing the corresponding
collateral asset.
The funding fees are delivered to xPOSITIONs, making it more attractive to open a long position, thus preventing fxUSD from trading above $1.
➡️ Users get an incentive to open xPOSITIONs when needed, avoiding fxUSD's overpeg.
Redemption of fxUSD
When fxUSD is depegged, users can purchase it on the secondary market and redeem it for $1.00 worth of collateral, subject to applicable fees.
➡️ Redemption acts as a last resort mechanism to guarantee fxUSD's peg if the previous mechanisms have failed.
Min stETH/USD Price is used for Redeeming sPOSITIONs when the system runs out of leverage long collaterals to meet xPOSITIONs’ closing and risk management options if the price difference between Anchor Price and Min Price doesn’t exceed the threshold. Anchor Price is used otherwise.
The f(x) 2.0 price oracle mechanism for WBTC/USD combines multiple data sources, including Chainlink, Uniswap and Curve, to calculate spot prices and anchor prices. It defines Max and Min Price for WBTC/USD based on these sources and uses a governance-adjustable threshold (default 2%) to decide whether to rely on the Anchor Price or the Max/Min Price for operations like rebalancing, minting, or redeeming. This ensures accurate and stable pricing while accommodating market fluctuations. Below is the detailed breakdown of the WBTC Spot Price Oracle Mechanism:
BTC/USD Spot oracle:
[]
[]
[] * []
WBTC/BTC Spot oracle:
[]
WBTC/USD Anchor Price oracle:
[] * []
The Algorithm of WBTC/USD Max and Min Price:
Max: WBTC/USD Price=Max(Anchor Price, [WBTC/BTC Spot Max Price ]*[BTC/USD Spot Max Price ])
Min: WBTC/USD Price=Min(Anchor Price, [WBTC/BTC Spot Min Price ]*[BTC/USD Spot Min Price ])
Price Checking Mechanism:
Anchor Price is used, while the price difference between Anchor Price and Max/Min Price exceeds the threshold
The threshold is a governed parameter, 2% in default
Conclusion:
Min WBTC/USD Price is used for Open/Close of xPOSITION risk control, Rebalance and Liquidation if the price difference between Anchor Price and Min Price doesn’t exceed the threshold. Anchor Price is used otherwise.
Max WBTC/USD Price is used for Redeeming fxUSD if the price difference between Anchor Price and Max Price doesn’t exceed the threshold. Anchor Price is used otherwise.
Max WBTC/USD Price is used for Open/Close of sPOSITION risk control, Rebalance and Liquidation if the price difference between Anchor Price and Max Price doesn’t exceed the threshold. Anchor Price is used otherwise.
USD high & sustainable yield
f(x) Protocol V2 delivers a unique USD yield value proposition with its Stability Pool.
It offers the best risk rewards strategy by being collateralized with Tier 1 DeFi assets and collecting high and sustainable yield sources.
Learn more here 👇
The "Earn" section of the protocol also offers different stable strategies, such as the Curve fxUSD/USDC pool or V1 stability pool.
Learn more about V1 stability pools here.
Min WBTC/USD Price is used for Redeeming sPOSITIONs when the system runs out of leverage long collaterals to meet xPOSITIONs’ closing and risk management options if the price difference between Anchor Price and Min Price doesn’t exceed the threshold. Anchor Price is used otherwise.
Absolutely not. All stablecoins issued by f(x) Protocol, including its flagship fxUSD, are fully collateralized with top-tier DeFi assets. Specifically, fxUSD is backed solely by Lido's stETH and WBTC. The f(x) invariant ensures unparalleled capital efficiency by maintaining the stablecoin's 100% collateralization, while the xPOSITION (v2) and leveraged tokens (v1) manage the protocol's over-collateralization.
Get involved - Community Booster Program
Aladdin DAO has always been a community-oriented project.
Anyone can contribute to the protocol's growth and be rewarded.
There is no limit to the ways one can contribute. Here are a couple of examples:
Creating online content about f(x)
Getting intros to the team with DeFi Funds and large LPs
Getting intros with qualitative KoLs
Building relevant DeFi integrations with other protocols
...
Anything that helps bring awareness, TVL, and volume to the protocol is beneficial.
Currently, 500FXN are distributed every month among the Community Boosters. The rewards are linearly vested over 12 months. Still, they can be converted into cvxFXN or sdFXN, respectively, Convex or StakeDAO's liquid lockers to let boosters earn the veFXN yields during the vesting period.
How to get started?
Join the Aladdin DAO's and post your contribution to the #contribute-fx channel.
Each month, the rewards distribution will be announced in Discord and on X.
$FXN Tokenomics
f(x) Token Distribution
Token Name: f(x) Protocol Token
Token Symbol: FXN
Token Supply: 2,000,000 $FXN
FXN Distribution
CategoryPercentageVesting Schedule
Category
Percentage
Vesting Schedule
FXN Release Schedule
Protocol Revenue & Distribution
The f(x) Protocol generates revenue through multiple mechanisms designed to sustain the system while rewarding participants and long-term supporters.
1. Revenue Sources
Collateral Yields: Earnings derived from the collateral (e.g., stETH) backing the protocol.
Opening and Closing Fees: Fees collected when users open or close xPOSITIONs, contributing to the protocol's revenue stream.
veFXN
$FXN runs under the ve tokenomics popularized by Curve. Locking FXN gets you veFXN. The longer the lock time, the more veFXN received.
1 FXN locked for 4 years = 1 veFXN
1 FXN locked for 3 years = 0.75 veFXN
How does f(x) Protocol minimize liquidations?
f(x) Protocol uses its rebalancing mechanism to minimize any risk of liquidation. This means scenarios where a sudden market drop that would normally liquidate your entire long position just before a rally are unlikely to occur. However, this doesn't eliminate the risk of losing money as leverage amplifies both potential gains and losses.
xTokens (v1): In highly extreme scenarios, leveraged xTokens could potentially lose all of their value. However, the protocol's primary goal is to prevent this. Multiple are in place to ensure this doesn't happen.
xPOSITION (v2): If your position reaches a price level that would normally trigger liquidation on a regular perpetual exchange, it will instead be rebalanced to a different leverage level. While this operation incurs a small fee, it keeps you as much as possible exposed to the market, giving you a chance to recover. In extreme cases where the rebalancing operation fails, liquidation may occur to protect fxUSD's backing and peg. But there is a very small risk of this occurring.
Learn more by following the link below.
FXN Farming and veFXN Boost
TheFXN overall token allocationspecifies 980,000 FXN tokens (49% of max supply) to be emitted as liquidity incentives over a 50-year period, with the emission rate starting at 98,000 FXN for the first year and declining by 10% (relative) each year thereafter. Each year is divided into weekly epochs, with a veFXN governance vote determining how that epoch’s FXN will be allocated among the available gauges, the same as in the Curve’s pioneering model. In the details, however, there are several differences to Curve, driven by technical considerations in the f(x) system.
Gauge Types
f(x) Protocol supports two types of gauges: Stability Pool gauges, and liquidity pool gauges. For LP gauges, farmers can earn FXN by providing liquidity to certain Curve liquidity pools. These gauges are based on a double-gauge structure: farmers stake their Convex farming positions, allowing them to earn both Curve/Convex rewards as well as FXN. Of course, zaps hide this complexity for users who wish to simply deposit underlying tokens. LP gauge yields are boosted by owned, shared or delegated veFXN boost.
On the other side, Stability Pools are even more different to Curve gauges. First, they are not strictly gauges in the Curve sense, due to the fact that they are not tokenized. This has implications for how tokens are distributed, how boost is allocated, and more. Additionally, Stability Pool gauges can be boosted by owned or shared veFXN boost, but not delegated.
Is there any LUNA-like risk?
No, f(x) stablecoins are fundamentally different from Luna. While Luna collateralized its stablecoin with endogenous assets (its own governance token), f(x) stablecoins are backed exclusively by tier-1 exogenous DeFi assets.
You can check fxUSD and its related xPOSITIONS backing .
Referral Program
f(x) Protocol offers a very straightforward referral program that lets both referrer and referee earn extra yield.
The mechanism is very simple:
Create a referral code using the
Share your referral link or invite friends to use your code. To use your code, they can either follow your link or click on the "Earn extra APR" button on the Earn page to type your code. In both cases, they must sign the subscription using their wallet (no gas required).
Your friends earn an extra 0,5% APR on every stablecoin deposited into the V2 Stability pool or the fxUSD/USDC Curve pool. Convex deposits are eligible.
You earn 1% APR on all your friends deposits.
You can claim the FXN rewards monthly by going to the referral center.
Vested linearly over 24 months, ve-locked after vesting
Initial Liquidity
1%
Strategic Partnerships
1%
Vested linearly over 12 months
Liquidity Incentives
49%
5% vested linearly in the first year, decreasing by 10% each year thereafter.
e.g., 5% on the first year, 4.5% on the second year, 4.05% on the third year... until 0%.
Full emission will take 50 years to complete, starting in 2023.
Community Contributors
3%
Vested linearly over 12 months & lasting 3 years:1.5% for Year 1, 1% for Year 2, 0.5% for Year 3
Treasury Reserve
10%
Vested linearly over 24 months
IDO
5%
2. Revenue Distribution
All fees and collateral yields are redistributed between the Stability Pool, the xPOSITIONs and sPOSITIONs, and the f(x) Treasury, with the allocation determined by governance.
Stability Pool: A portion of the revenue supports the Stability Pool, reinforcing system stability and rewarding participants.
xPOSITIONs and sPOSITIONs: as they are leveraged positions, incentivizing their openings brings significant impacts on fxUSD's peg.
f(x) Treasury: The remaining revenue is allocated to the Treasury, where a proportion of it is distributed to veFXN holders. This mechanism provides long-term supporters with substantial financial benefits, fostering a robust and engaged community around the protocol.
Fees Distribution Parameters
Global
Fee
Distribution
fxUSD redemption fee
70% to the Stability Pool / 30% Protocol Revenue
Stability Pool early exit fee
100% to the Stability Pool
ETH xPOSITIONs and fxMINT positions
Fee
Distribution
Collateral Yields
A dynamic percentage based on the shorts debt ratio versus the longs collateral goes to the sPOSITIONs / The rest to the Stability Pool
xPOSITION and fxMINT opening/closing fees
70% to the Stability Pool / 30% Protocol Revenue
Rebalance / Liquidation: 10% of the bounty
70% to the Stability Pool / 30% Protocol Revenue
Funding costs (Level I & II)
A dynamic percentage based on the shorts debt ratio versus the longs collateral goes to the sPOSITIONs / The rest to the Stability Pool
Unused Slippage
50% to the Stability Pool / 50% to the Protocol Revenue
Aave yields ()
100% to the Stability Pool
BTC xPOSITIONs and fxMINT positions
Fee
Distribution
xPOSITION / fxMINT opening/closing fees
50% to the Stability Pool / 50% Protocol Revenue
Rebalance / Liquidation: 10% of the bounty
50% to the Stability Pool / 50% Protocol Revenue
Funding costs (Level I & II)
A dynamic percentage based on the shorts debt ratio versus the longs collateral goes to the sPOSITIONs / The rest to the Stability Pool
Unused Slippage
50% to the Stability Pool / 50% to the Protocol Revenue
BTC & ETH sPOSITIONs
Fee
Distribution
sPOSITION opening/closing fees
100% Protocol Revenue
Rebalance / Liquidation: 10% of the bounty
100% Protocol Revenue
Funding costs (Level III)
100% to the xPOSITIONs
Unused Slippage
100% Protocol Revenue
*The rebate reserve is built to offer a fee rebate in the future 👀
All fees captured by the Treasury are distributed in this way.
veFXN
75%
Treasury Multisig
12,5%
Reserve / Insurance Fund
12,5%
The Treasury Multisig allocation helps to sustain the protocol by funding further developments
Boost Calculation
In Curve’s gauge model, all gauge emissions are distributed immediately and users with boost power take rewards from users without. The veFXN model allows each user to earn their own maximum FXN, and if they do not, the difference is rolled over and used to increase yields for the pool across the board.
FXN distributions to the Stability Pool are shared among farmers according to each farmer’s share of TVL in that pool and their share of total veboost power. Each farmer’s share of TVL in the pool determines the maximum share of incoming FXN they can earn, while their boost determines how much of that they can actually claim. Farmers with veboost power earn up to 2.5X more than farmers with none.
Farmers who have zero veboost have a boost of 1X, which allows them to claim 40% of their maximum earnable share of FXN for this epoch. Farmers who have the maximum veboost of 2.5X may claim 100% of their maximum share.
Each farmer’s boost level is calculated like this:
Maximum FXN = Total Distributable FXN x Individual TVL / Total TVL
Claimable FXN = 0.4 x Maximum FXN x Boost Level
Boost Level = min (Individual TVL x 0.4 + (Total TVL x Individual veFXN for the epoch) x 0.6 / Total veFXN for the epoch, Individual TVL) / (Individual TVL x 0.4)
An alternative way to think about boost level is in terms of two variables: A farmer’s fractional share of the total veboost (fv), and a farmer’s fractional share of the total TVL (fd). Using these terms, each farmer’s boost is calculated like this:
For an individual farmer, the optimal approach is to hold precisely the same share of the total vepower and TVL. A higher share of total vepower than their share of the TVL doesn’t help that farmer, however, the FXN system allows sharing boost power for whitelisted addresses (see below).
Rollover FXN
It is likely that not every farmer will earn their maximum share, which means each time a farmer in the pool makes a settlement transaction (see “Settlement”) there may be leftover FXN. This leftover FXN is rolled forward and treated as a new distribution to the Stability Pool, similar to FXN coming from the gauge.
When any new FXN comes to the Stability ool it is combined with FXN already vesting (if any), and the sum is vested over a new 7 day period starting at the moment of the distribution. Since distributions can come from settlement transactions at any time and in any amount, it would be possible for a small distribution to come in at an inopportune time and artificially (briefly) deflate the pool APR.
To prevent this, FXN rollover distributions which would cause the overall pool APR to drop more than 10% are held in reserve, and added to the next settlement-triggered distribution.
Sharing and Delegating Boost Power
A whitelisted address can choose to share its veFXN boosting power with one or more other addresses. This mechanism is useful for boosting services built on top of f(x), allowing many individual farmers to benefit from a single central pool veFXN. In the case of shared boosting, the total veboost is calculated using the amount of veFXN shared (i.e. that held by the sharing address) and the collective TVL of the all recipients.
The calculated boost level is applied to all recipients.Users may also choose to delegate their veFXN boost power to another single address. Delegated boost can be used to boost LP farming yields, but not stability pool yields.
Emissions Require Harvesting
A Stability Pool is not strictly a gauge in the Curve sense because it is not tokenized. This has some technical implications, but practically it means the following:
FXN is released by the gauge linearly over a period of 7 days, but requires harvesting before it can be distributed
FXN is minted when the harvest function is called (it is a permissionless keeper function). Minted FXN is vested linearly to Stability Pool farmers over 7 days.
Between harvest delays and vesting, token emissions have smoothed and slightly delayed changes from pool APRs. Things will smooth out after a week.
Settlement
Upon any deposit/withdraw/claim/veFXN top up transaction (including receiving shared boost power,) the system will immediately calculate and settle claimable FXN rewards for the period between two transactions. Even though a user may not choose to make any transaction which triggers settlement for a period of many epochs, the amount of FXN they may claim from each past epoch is locked in and does not change after the end of that epoch.
In other words, when the settlement happens, total claimable FXN for each epoch since the previous settlement is calculated using TVL and veboost values from that epoch.
Settlement happens prior to the execution of the transaction which triggers it, so any changes to veboost which result from the transaction will apply only to subsequent epochs.
Examples
Here are two simple numerical examples. Assume we only have Alice and Bob in the Stability Pool, and that there are 10 distributable FXN for this epoch:Example 1 (nobody has any veboost)
Stability Pool Farmer
Alice
Bob
TVL $
100
100
Maximum Earnable FXN for the epoch
5
5
veFXN
0
0
Claimable FXN
5 x 0.4 = 2
5 x 0.4 = 2
In Example 1, only 4 out of 10 FXN have been distributed, so the remaining 6 FXN are placed in the rollover reserve which will be used to increase distributable FXN in later epochs.
Example 2 (everybody has equal veboost)
Stability Pool Farmer
Alice
Bob
TVL $
100
100
Maximum Earnable FXN for the epoch
5
5
veFXN
100
100
Claimable FXN
5 x 0.4 x 2.5 = 5
5 x 0.4 x 2.5 = 5
All of the 10 FXN have been distributed when everybody has the equal veboost.All of the 10 FXN have been distributed when everybody has the equal veboost.
When you visit our V1 dApp, you might need more clarity regarding the variety of stablecoins available. Each stablecoin is backed by different types of collateral, each with unique risk profiles. Here's a breakdown of their key differences:
Each of these stablecoins is designed to serve different use cases and risk appetites. For more details, explore our Token Breakdown.
What is the difference between f(x) Protocol V1 and V2?
From a user perspective, v1 offers variable leverage tokens, providing up to 4.3x leverage on ETH and 5.6x on wBTC. Most leveraged tokens incur no funding costs. With its unique value proposition—leverage without liquidation or funding costs—and a scalable decentralized stablecoin, v1 serves as a robust solution. However, the unpredictability of variable leverage may not suit everyone's needs. This is where v2 steps in, introducing a groundbreaking feature: Fixed Leverage of up to 10x, fully on-chain, with minimal liquidation risk and funding costs.
v2 also offers an exclusive feature through its stability pool, which delivers exceptionally high and sustainable yields derived from PERP trading commissions. These yields are achieved without exposing stakers to market volatility. The pool is USD delta-neutral and avoids counterparty risk, unlike other perpetual exchange protocols.
v1 still remains an excellent option, offering a unique use case by splitting any yield-bearing asset into two tokens: a stablecoin and a leveraged xToken. The stablecoins can harness enhanced yield without market exposure, while xTokens enjoy enhanced market exposure without yield.
Where does the yield come from?
This is the question everyone should ask themselves when assessing any yield opportunity. The main f(x) strategy is the Stability Pool.
Many wonder how f(x) can deliver yields while offering no funding / no borrowing cost leverage. You'll find a detailed answer below, but first, note that while the xPOSITIONs incur no recurring borrowing costs (in most conditions), there is a one-time opening and closing fee.
Learn more here: Creating a Leveraged LONG Position (xPOSITION)
The stability pool accepts both fxUSD and USDC and gives exposure to both assets. It harnesses different sources of real, organic, and sustainable yields.
xPOSITION opening and closing fees
The reserve's yields. Remember, ETH xPOSITIONS are backed by wstETH which generates staking yields. Plus, a portion of it is deposited on Aave* to capture even better rewards.
USDC's lending yield on Aave*
Other occasionnal revenue. You can find all the details on that page:
OR
$FXN.
Indeed, depending on what you'd rather accumulate with your stablecoins: wstETH, stables (fxSAVE), or FXN you can opt for FXN emissions instead of real yield.
*Following the , some of the wstETH of the reserve and USDC of the Stability Pool are deposited into Aave. The maximum dsitribution deposited can be found on .
How do f(x) Protocol stablecoins maintain stability?
Stablecoins can be minted and redeemed at the oracle price, ensuring seamless functionality. For fxUSD, several mechanisms guarantee a perfect peg:
f(x) Protocol establishes and maintains a deep fxUSD/USDC liquidity pool.
The fxUSD stability pool offers high and sustainable yields derived from stETH staking, xPOSITION opening fees, and FXN emissions. This stability pool, which accepts both USDC and fxUSD, also acts as a peg keeper by purchasing fxUSD when it trades below peg and selling it back to USDC when it trades above.
xPOSITION cannot be opened if fxUSD is trading below peg.
fxUSD can always be redeemed at the oracle price for stETH or WBTC, safeguarding it against any significant de-peg events.
Learn more here.
How to adjust your leverage / how to reduce your Liquidation Brake
Adjusting your leverage, suppose you already have an opened xPOSITION. You should see your xPOSITION on the Trade page in the middle left section called “My xPOSITION”.
Ensure the correct wallet is connected to the dApp if you don't see it.
There are two ways of adjusting the leverage of an xPOSITION. You can modify it without changing its nominal value or top up to your position with a different leverage.
To lower your Liquidation Brake threshold, simply reduce your leverage using one of the two options below. You can reduce it by adding to your position with a lower leverage.
Adjusting the leverage without changing the xPOSITION’s nominal value.
Once you are correctly connected on the page, you should see a button labeled “Adjust Leverage.” Click it.
Slide the leverage bar to reach your desired leverage.
Hit the “Preview” button.
Adjusting the leverage of the xPOSITION by adding to it.
You can also top up your position or create a new one with a different leverage. Your xPOSITIONs are aggregated into a single one with an average leverage.
Please follow that tutorial to learn how to add or reduce a position.
Why is my execution price different from what the chart displays?
xPOSITIONs and sPOSITIONs are on-chain leverage tools. It means that 100% of the execution occurs on-chain without involving any centralized market maker or order book.
On-chain execution can result in a discrepancy between the oracle-estimated execution price and the actual execution price.
Please note that the charts currently displayed on the dapp are CEX charts displayed for informational purposes, rather than oracle-based charts.
When opening or closing a position at the market price, the execution may face price impacts and fees at different levels, excluding the protocol fees:
Swapping the collateral with USDC - For instance, WBTC's main liquidity pool with USDC charges a 0.3% swap fee on Uniswap.
Swapping USDC with fxUSD - The fees here are minimal; however, depending on the current liquidity and the trade size, a small price impact may occur.
The size of your position increases the effect.
To mitigate this:
Mind the slippage setting before interacting with the protocol
Upcoming limit orders should deliver a perfect execution
We are progressively integrating dex aggregators API to deliver better execution prices
Review your trade and the evolution of your xPOSITION, then click the “Submit Transaction” button when ready.
What price drop would it require for my fxMINT or xPOSITION to be rebalanced/liquidated?
f(x) Protocol prevents leverage traders from being liquidated by rebalancing the positions before liquidation would be required.
The LTV at which the protocol rebalances or liquidates the xPOSITION is set by governance (see ).
The price distance to reach the rebalancing LTV depends on the leverage level the user chooses.
You can find some examples of price drops required to reach the rebalancing line or liquidation line according to the leverage of an xPOSITION below.
The UI provides the exact price of rebalancing and liquidation line for your xPOSITION when opening it and can be consulted in your dashboard once the position is open. The table below is an example.
How does f(x) Protocol minimize funding costs or annual interests?
Most perp protocols rely on funding costs to balance long and short demand.
f(x)’s unique design doesn’t rely on this, as the counterparty of every trade is a concentrated liquidity DEX pool with deep liquidity thanks to sustainable yields.
The first pegkeeping mechanism for fxUSD is the Stability Pool.
If the Stability Pool lacks of USDC to secure a good peg for fxUSD, the cost of borrowing USDC on Aave is charged to thefxMINT and xPOSITIONs. This fee is mostly directed to the Stability Pool and sPOSITIONs until the peg is restored (see Protocol Revenue & Distribution).
This fee can be considered as a funding cost or interest temporarily applied to the position.
If that is not enough to keep the peg, and if fxUSD trades below the depeg threshold (see Risk parameters), the fee applied is amplified by an order of magnitude defined by governance, until the peg is restored.
When too much of the xPOSITION collateral is lent out to sPOSITIONs, a funding/interest may be applied to sPOSITIONS and directed to xPOSITIONs.
To summarize in most situations, you don’t pay any funding or interest fee. However, when the peg of fxUSD could be threatened, a variable fee may be temporarily applied to your position.
It's important to note that other peg-keeping mechanisms in place should prevent that scenario from happening regularly, providing a sense of reassurance.
Learn more 👇
xTokens (v1): In the worst-case scenario, all xTokens could potentially lose their value. Before this happens however, the stability mechanism is designed to trigger and rebalance them. However, if the mechanism becomes exhausted, xTokens could drop to zero. In such extreme cases, the protocol's total collateralization ratio remains at 100% and the stablecoin is always backed and pegged to the dollar. If the market continues to decline, the stablecoin may temporarily de-peg, with a strong likelihood of recovery if the underlying market (e.g., ETH) rebounds. For more details about the stability mechanism, please refer to the V1 .
xPOSITION (v2): Rebalancing and liquidation thresholds are carefully calibrated to prevent such scenarios. In an unlikely worst-case scenario where both rebalancing and liquidation mechanisms fail, the protocol may incur a bad debt. To safeguard users from this, f(x) Protocol allocates a significant portion of its revenue to a reserve fund specifically for such extreme cases. If the reserve fund is insufficient, the bad debt would be distributed among all xPOSITIONs.
Learn more:
How to close a leverage position (xPOSITION)
To close an xPOSITION:
Head over to the page.
Connect your wallet using the upper right “Connect Wallet” button.
Connect your wallet using the upper right “Connect Wallet” button.
Input the amount you would like to leverage. The default asset is USDC; you can pledge other assets by clicking the down arrow.
Set the requested leverage using the slider bar and wait for the preview to load.
Hit the Preview button to review your trade.
Review your trade and the evolution of your xPOSITION, and once you are ready, click the “Submit Transaction” button.
Confirm the transaction using your wallet.
You’re all set. You can now track your position on your Dashboard on the “” page.
How do the limit orders work?
A Limit Order allows users to automatically open or close a position at a specified price within a set period of time.
When the market price reaches the trigger condition you set, the system will automatically execute your order — creating a true “set-and-forget” trading experience.
💡 Important:
As always in DeFi, a limit order is not guaranteed to execute.
How to unstake from the stability pool?
Understand that withdrawing from the stability pool gauge to fxUSD & USDC is a two-step process. You first need to unstake from the $FXN gauge, then withdraw this stability pool token for USDC and fxUSD.
There is a redemption period (see ) from the stability pool to prevent unhealthy arbitrage operations.
Head over to the “” page.
Connect your wallet using the upper right “Connect Wallet” button.
Short Pool Integration
1. Contract Interface
2. Short Pool Specifics
Key Differences from Long Pool:
How to stake into the stability pool?
The f(x) Protocol stability pool offers a unique way of putting your stablecoins at efficient work.
By staking either your fxUSD or USDC, you will not only earn enhanced LSD yields, xPOSITIONs trading commissions, and $FXN but will also contribute to making the protocol robust and scalable.
Remember, this is not a counterparty vault. You are not betting against traders; your capital stays pegged to the USD.
Understand that depositing and staking is a mandatory two-step process to earn all the rewards. You first need to deposit assets into the stability pool, then stake this stability pool token into the $FXN gauge. Hopefully, the UI abstracts this by triggering both transactions in a row.
Let’s get into it.
Make sure you have either fxUSD or USDC in your wallet.
Collateral: fxUSD tokens
Debt: External tokens (ETH, BTC, etc.)
Rebalance Example:
interface IShortPoolManager {
/**
* @notice Rebalance positions in a specific tick
* @param pool The address of short pool
* @param receiver The address to receive fxUSD
* @param tick The tick to rebalance
* @param maxRawDebts Maximum raw debt tokens to use
*/
function rebalance(
address pool,
address receiver,
int16 tick,
uint256 maxRawDebts
) external returns (uint256 colls, uint256 debts);
/**
* @notice Rebalance entire pool
* @param pool The address of short pool
* @param receiver The address to receive fxUSD
* @param maxRawDebts Maximum raw debt tokens to use
*/
function rebalance(
address pool,
address receiver,
uint256 maxRawDebts
) external returns (uint256 colls, uint256 debts);
/**
* @notice Liquidate high-risk short positions
* @param pool The address of short pool
* @param receiver The address to receive fxUSD
* @param maxRawDebts Maximum raw debt tokens to use
*/
function liquidate(
address pool,
address receiver,
uint256 maxRawDebts
) external returns (uint256 colls, uint256 debts);
}
// Get debt token for the short pool
address debtToken = IShortPool(shortPoolAddress).debtToken();
// Approve debt tokens for rebalancing
IERC20(debtToken).approve(shortPoolManager, maxDebtAmount);
// Execute rebalance
(uint256 fxUSDReceived, uint256 debtUsed) =
IShortPoolManager(shortPoolManager).rebalance(
shortPoolAddress, // target short pool
msg.sender, // receive fxUSD
maxDebtAmount // max debt tokens to use
);
Keepers will only execute your order when the market price is sufficient to cover both your limit price and network fees.
Therefore, your order may not execute immediately when the price first reaches your limit level.
1. Before You Start
No gas fees are required to place an order. Gas is only required in case of cancelling your currents orders.
Opening orders currently only accept fxUSD as base asset, use your favorite DEX aggregator to get some.
You only need to authorize fxUSD and, if applicable, your position NFT.
Looking at automating the limit orders? Look at the developpers doc.
2. Order Parameters
Parameter
Description
Pay
Amount of fxUSD to be used for opening or adding to a position.
Amount
Amount of collateral to be sold when closing or reducing a position.
Limit Price
The price at which the limit order will be executed.
Limit Type
For closing orders, choose Take Profit or Stop Loss.
Trigger Price
The trigger price is calculated automatically based on Limit Price and Slippage, but can be edited manually.
Partial Fill
Whether to allow partial order execution. Recommended for large orders so multiple Keepers can fill portions of it.
3. Limit Order Types
Type
Description
Limit Open
Opens a position when the market price reaches your set limit price.
Stop Loss Limit
Executes at the Stop Loss (SL) price once the trigger condition is met.
Take Profit Limit
Executes at the Take Profit (TP) price once the trigger condition
is met.
Execution Conditions & Mechanism
The protocol uses Chainlink Oracle prices.
Only when the Oracle price meets the Trigger Price condition can a keeper initiate the trade.
Execution occurs exactly at the Limit Price, with no slippage.
Open position: the protocol fees are deducted from the position.
Close position: keeper handles the protocol fees.
⚠️ Even when conditions are met, execution is not guaranteed and depends on keeper availability and market incentives. Note that this is true for every kind of limit order, not only on f(x) Protocol.
Look for the “fxUSD Stability Pool Gauge” strategy.
If not already, expand the strategy by clicking the down arrow button on the right of the box
Hit the “Withdraw” button to see a withdraw popup.
If all your tokens are staked in the FXN gauge:
Type the desired amount to be withdrawn.
Toggle the "Fast" option if you'd rather withdraw instantly and pay a small fee. Leave it untoggled to wait for the redemption period.
Click the “Approve & Unstake & Withdraw” button (if already approved, it will be a simple “Unstake & Withdraw” button”)
Confirm the transactions in your wallet.
If you didn't opt for the instant withdrawal, wait for the redemption period to be completed. You can track the remaining time on the page.
Follow the instructions below to withdraw your Stability Pool tokens to fxUSD and USDC.
If you have some unstaked stability pool tokens:
Click on the FXN Gauge dropdown menu and select “fxUSD Stability Pool”
Type the desired amount to be withdrawn.
Click the “Approve & Withdraw” button (if already approved, it will be a simple “Withdraw” button”)
Connect your wallet using the upper right “Connect Wallet” button.
Look for the “fxUSD Stability Pool Gauge” strategy.
If not already, expand the strategy by clicking the down arrow button on the right of the box
Hit the “Deposit” button to see a deposit box popup.
Choose whether you want to deposit fxUSD or USDC using the down arrow
Type the desired amount
Keep the Stake toggle if you want to stake directly into the f(x) gauge. (Recommended - Untoggle it if you wish to stake elsewhere)
Choose whether you want to earn organic real yield paid in wstETH and WBTC or accumulate FXN rewards.
Click the “Deposit & Stake” button - Approve may also be prompted if you haven't already approved.
Confirm the transactions in your wallet.
If you have some unstaked Stability Pool tokens, you will see a “Stake” button; click it to stake them in the gauge and earn yield.
Type the desired amount.
Click the “Approve & Deposit” button (if already approved, it will be a simple “Deposit” button”)
Confirm the transactions in your wallet.
Please note that to prevent unfavorable arbitrages, unstaking from the stability pool is subject to either a cooldown period or a fast withdrawal fee. See Risk parameters and Fees.
Adding up or reducing an xPOSITION is as easy as creating or closing one.
You can create as many xPOSITION as you want; they will all be aggregated into a single global one.
For example, suppose you create a first xPOSITION with a 2x leverage worth $10,000 and a second xPOSITION with a 4x leverage worth $10,000. In that case, you will end up with a $20,000 xPOSITION with a 3x leverage (assuming you opened them simultaneously with the same execution price).
Now, let’s see how to do that practically.
How to add to a leverage position
Head over to the page.
If not already, hit the “Buy / Open” tab.
Connect your wallet using the upper right “Connect Wallet” button.
Input the amount you would like to leverage. The default asset is USDC; you can pledge other assets by clicking the down arrow.
Set the requested leverage using the slider bar and wait for the preview to load.
Hit the Preview button to review your trade.
Review your trade and the evolution of your xPOSITION, then click the “Submit Transaction” button when ready.
Confirm the transaction using your wallet.
How to reduce a leverage position
Head over to the page.
Connect your wallet using the upper right “Connect Wallet” button.
Click on the “Sell / Close” tab of the order box.
Long Pool Integration
1. Rebalance Operations
For long pools, the rebalance operation has to be invoked through FxUSDBasePool.
Rebalance can only be operated when debt ratio is between the values fetched in getRebalanceRatios
As for tokenIn address, both fxUSD and
Integrating fxSAVE
To facilitate the integration of fxSAVE from any chain, routed it.
You'll find more information here.
Note that since fxSAVE withdrawal is a two-step process, Enso only routed the atomic withdrawal that charges a withdrawal fee.
To avoid that fee, you can wait for the cooldown period instead.
Processing the rebalances and liquidations
Learn how to monitor and trigger rebalance and liquidation operations
Introduction
In DeFi, a Keeper is an entity or system responsible for automating on-chain actions that cannot execute themselves. Since smart contracts on blockchains are passive, they require an external trigger—this is where Keepers come in.
While f(x) is a fully on-chain system, the Keeper is designed to actively monitor positions and initiate actions once certain conditions are met.
Maintaining an active Keeper community is critical for the f(x) Protocol. Therefore, we’ve written this document to help you understand some key concepts and processes related to Keepers.
You can double-check the contracts for the last update on Github
Expiration
Order validity period. Default: 7 days (customizable, up to 1 year).
Stability Mechanism
Earn Pools also play a critical role in maintaining stability:
If the stable-leverage pair becomes unstable due to excessive minting of stables or insufficient xTokens, stables in the Earn Pool are redeemed for reserve assets at their Net Asset Value (NAV).
In stability mode, this operates like automatically buying ETH (or the reserve asset) at market price without slippage.
Otherwise, it enables farming of real, unstable yields using stablecoins.
Implementation Reference(s)
These are third-party implementations; please use them at your own risk.
The team is not liable for any damages, losses, or issues arising from the use of the following software.
tokens are supported. The FxUSDBasePool contract uses the
_beforeRebalanceOrLiquidate
function to handle token conversion:
1.1 Pool-Wide Rebalance
Usage Example:
1.2 Tick-Specific Rebalance
Notice: The tick provided must always be a root tick—i.e., its node's parent must be 0. Otherwise, you need to trace the tick upward to identify the corresponding root tick.
Usage Example:
2. Liquidation Operations
Rebalance can only be operated when debt ratio is between the values fetched in getLiquidateRatios
Contract Interface
Usage Example:
3. CreditNote Received
If it happens that the long pool does not have enough collateral in the contract (it is still overcollateralized, but the collateral is held elsewhere — for example, lent to short pools), you may receive the CreditNote from the long pool instead of the collateral asset. In this case, you can use redeemByCreditNote to obtain the collateral asset.
for WBTC pools, you may receive fxBTC: 0xB25a554033C59e33e48c5dc05A7192Fb1bbDdfc6
for wstETH pools, you may receive fxETH: 0x7c5350BaC0eB97F86A366Ee4F9619a560480F05A
Please double-check those addresses before using them.
function _beforeRebalanceOrLiquidate(
address tokenIn,
uint256 maxAmount
) internal view returns (RebalanceMemoryVar memory op) {
op.stablePrice = getStableTokenPriceWithScale();
op.totalYieldToken = totalYieldToken;
op.totalStableToken = totalStableToken;
uint256 amountYieldToken = op.totalYieldToken;
uint256 amountStableToken;
if (tokenIn == yieldToken) {
// User pays fxUSD - direct usage
// ... fxUSD handling logic
} else {
// User pays USDC - convert to USD equivalent
uint256 maxAmountInUSD = (maxAmount * op.stablePrice) / PRECISION;
if (maxAmountInUSD < amountYieldToken) {
amountYieldToken = maxAmountInUSD;
} else {
amountStableToken = ((maxAmountInUSD - amountYieldToken) * PRECISION) / op.stablePrice;
}
}
// Ensure we don't exceed available stable tokens
if (amountStableToken > op.totalStableToken) {
amountStableToken = op.totalStableToken;
}
op.yieldTokenToUse = amountYieldToken;
op.stableTokenToUse = amountStableToken;
}
/**
* @notice Rebalance all eligible ticks in the pool through FxUSDBasePool
* @param pool The address of the long pool
* @param tokenIn The token to use (fxUSD or stable token)
* @param maxAmount Maximum token amount to use
* @param minBaseOut Minimum collateral expected
* @return tokenUsed Amount of input token consumed
* @return baseOut Amount of collateral tokens received
*/
function rebalance(
address pool,
address tokenIn,
uint256 maxAmount,
uint256 minBaseOut
) external returns (uint256 tokenUsed, uint256 baseOut);
// Approve tokens for rebalancing
IERC20(fxUSD).approve(fxUSDBasePool, maxFxUSD);
IERC20(stableToken).approve(fxUSDBasePool, maxStable);
// Rebalance entire pool
(uint256 tokenUsed, uint256 collateralReceived) =
IFxUSDBasePool(fxUSDBasePool).rebalance(
poolAddress, // target pool
fxUSD, // use fxUSD
maxFxUSD, // max amount
minCollateral // minimum expected
);
/**
* @notice Rebalance positions in a specific tick through FxUSDBasePool
* @param pool The address of the long pool
* @param tick The specific tick to rebalance (risk level)
* @param tokenIn The token to use (fxUSD or stable token)
* @param maxAmount Maximum token amount to use
* @param minBaseOut Minimum collateral expected
* @return tokenUsed Amount of input token consumed
* @return baseOut Amount of collateral tokens received
*/
function rebalance(
address pool,
int16 tick,
address tokenIn,
uint256 maxAmount,
uint256 minBaseOut
) external returns (uint256 tokenUsed, uint256 baseOut);
// Get highest risk tick
int16 topTick = ILongPool(poolAddress).getTopTick(); // you may want to replace this with your own logic to fetch ticks
// Prepare tokens (fxUSD or USDC)
IERC20(tokenIn).approve(fxUSDBasePool, maxAmount);
// Rebalance specific tick
(uint256 tokenUsed, uint256 collateralReceived) =
IFxUSDBasePool(fxUSDBasePool).rebalance(
poolAddress, // target pool
topTick, // highest risk tick
tokenIn, // fxUSD or USDC address
1000e18, // max 1000 tokens
0 // minimum collateral (set based on slippage tolerance)
);
/**
* @notice Liquidate high-risk positions through FxUSDBasePool
* @param pool The address of the long pool
* @param tokenIn The token to use (fxUSD or stable token)
* @param maxAmount Maximum token amount to use
* @param minBaseOut Minimum collateral expected
* @return tokenUsed Amount of input token consumed
* @return baseOut Amount of collateral tokens received
*/
function liquidate(
address pool,
address tokenIn,
uint256 maxAmount,
uint256 minBaseOut
) external returns (uint256 tokenUsed, uint256 baseOut);
Description: Burns fxSave shares and instantly converts them into the target token(s) (such as fxUSD, USDC, or a combination of fxUSD + USDC).
Function Signature
Parameter Struct Description (ConvertOutParams)
ConvertOutParams Example
ConvertOutParams defines how assets redeemed from fxSave are converted (swapped) into the target token, such as USDC, fxUSD, or USDC+fxUSD. Below are three typical usage scenarios:
✅ Scenario 1: Redeeming USDC
In this case:
fxUSD needs to be swapped into USDC via the converter.
USDC is redeemed directly without swap.
fxusdParams (Swap fxUSD → USDC)
usdcParams (Direct Redemption of USDC)
✅ Scenario 2: Redeeming fxUSD
In this case:
fxUSD is redeemed directly without swap.
USDC needs to be swapped into fxUSD via the converter.
fxusdParams (Direct Redemption of fxUSD)
usdcParams (Swap USDC → fxUSD)
✅ Scenario 3: Redeeming USDC + fxUSD(No Swap)
In this case:
fxUSD is redeemed directly without any swap.
USDC is redeemed directly without any swap.
fxusdParams (Direct Redemption of fxUSD)
usdcParams (Direct Redemption of USDC)
Method 2: Two-Step Redemption Process to Get fxUSD + USDC
CreditNotes are tokens that represent borrowed collateral in the fx-protocol's Long-Short Pool lending system. It acts as a debt instrument that tracks how much collateral the Short Pool has borrowed from the Long Pool.
For each short pool, one type of CreditNote is generated. For example, we currently have two short pools in the system — the wstETH short pool and the WBTC short pool. Thus, there are two types of CreditNotes in the system, named:
fxETH (CreditNotes for wstETH Pool)
fxBTC (CreditNotes for WBTC Short Pool)
CreditNotes are primarily held by protocol contracts, though users may also receive CreditNotes from the protocol. In such cases, several methods are provided to allow users to redeem their CreditNotes for standard asset types.
1. Redemption Mechanism:
Users can redeem CreditNote tokens for underlying fxUSD collateral:
In the end, when the short pool reaches the end of its life cycle, all CreditNotes should be burned.
For more details on how to use it in a keeper bot, see the section.
Ticks
Ticks are a fundamental concept in f(x) protocol that represent discrete price points for debt-to-collateral ratios. They serve as a risk categorization system that groups user positions with similar risk levels together. For more details, you can check _getTick function in contracts.
1. Mathematical Foundation
The core formula for the tick system is:
Ratio = (1.0015^tick) × 2^96
This ratio represents the debts/collaterals proportion
Each tick represents approximately 0.15% price change (1.0015 - 1 = 0.0015)
2. Primary functions of Ticks
All user positions with similar debt ratios are grouped into the same tick, enabling:
Efficient batch processing: Multiple similar-risk positions can be handled simultaneously
Precise risk management: Positions within the same tick share similar liquidation risks
3. topTick
The system processes ticks starting from the highest risk tick (topTick) in descending risk order.
The system maintains a topTick that points to the highest-risk tick with outstanding debt. Operations always start from this point and work downward through decreasing risk levels.
4 Trace ticks
There are many ways to trace ticks. Fundamentally, they are stored in the nodes of each pool contract. For more details, please view [PoolStorage.sol][)
As for a position, you can use getPosition in each pool to get the tick of the position.
As for a tick, you can use tickData to fetch which node it belongs to:
As for a node, you can fetch the node's info through tickTreeData and tickData.
tickData: tick -> node
tickTreeData: node -> tick
However, the tick number returned by getPosition cannot be directly used in rebalance or liquidation operations unless its node's parent is 0. If the node's parent is not 0, you must trace the parent tick number upward until you reach a node whose parent is 0 (i.e., the root node).
Additionally, you can also use TickBitmap contract to track active root ticks.
Keeper Bots
There is an open-source example keeper implementation available at fx-keeper-example.
State Syncing
In this implementation, the bot relies on the stateSync class to synchronize states locally and reassemble the on-chain status. Based on the synchronized data, it calculates relevant metrics and executes rebalance and liquidate operations accordingly.
Calculate how much to rebalance
There are two known restrictions from the contracts:
From these conditions, we derive the following formula:
Code implementation():
Calculate how much to liquidate:
Based on the restrictions from the contract:
We can derive:
Code implementation():
redeemByCreditNote
When CreditNote is received, you may use redeemByCreditNote to redeem to the underlying assets. You can check the example code FxProtocolLongBatchExecutor contract of the bots to see a full process to how to integrate it.
First, in a flashloan, it use the borrowed fund to do rebalance/liquidation
After this, it checks the USDC balance
Then, it converts all the newly fetched collateral assets to USDC
Token Breakdown
Since the launch of the first iteration of the protocol, several tokens have been launched. Please find a breakdown below to help you navigate along them.
Stablecoins
fxUSD: Our flagship stablecoin, operating on v2. It is exclusively collateralized by Lido stETH and WBTC. While governance may introduce additional collateral types, they will always consist of the most liquid and secure assets in DeFi.
fxSAVE: the ultimate DeFi savings account. This yield-bearing stablecoin harnesses the 's yields.
rUSD: A v1 stablecoin backed by Etherfi eETH and Renzo ezETH. Once staked, it not only earns restaking yields but also provides points!
btcUSD: A v1 stablecoin collateralized by wBTC. Since wBTC is not yield-bearing, a small funding cost is charged to xToken holders and distributed to stable stakers.
cvxUSD: A v1 stablecoin backed by aCVX, an auto-compounding staked CVX created by .
fETH: Our first-ever v1 stablecoin, designed differently. Instead of being pegged to the dollar, it maintains stability by capturing only 10% of ETH's volatility, with its xToken absorbing the rest.
Leveraged tokens (V1)
xETH: a perpetual leveraged token providing up to 4x long exposure to ETH price movements, backed by Lido stETH exclusively.
xstETH / xfrxETH: ETH leverage tokens offering up to 4.3x exposure. Respectively backed by Lido stETH and frxETH.
xeETH / xezETH: ETH leverage tokens with up to 4.3x exposure. Respectively backed by Lido eETH and ezETH.
Integrating the f(x) limit orders
For users of the f(x) protocol, Limit Orders are a critical feature. By allowing position management at a fixed rate, limit orders eliminate slippage and reduce exposure to market-price uncertainty — a benefit that is especially valuable for large-size orders and systematic strategy executors. In addition, the introduction of take-profit / stop-loss orders enables the reliable automation of many trading strategies that would otherwise be impractical on an entirely market-priced execution model.
1. Components
1.1 Smart contracts
We introduce the LimitOrderManager family of smart contracts to implement limit-order functionality. These contracts allow orders to be filled on-chain while simultaneously operating the corresponding position (open/close/adjust), ensuring atomic and auditable execution.
For more details, please read the section.
1.2 Limit order API services
A dedicated API/relayer service is provided to help users broadcast and discover signed orders. Users sign orders off-chain and submit the order plus signature to the API, which acts as an order-relay and discovery layer for counterparties.
For more details, please read the section.
1.3 Front-end
For retail or non-technical users, the standard f(x) front-end provides UI flows to create, submit and monitor limit orders and TP/SL orders, abstracting away the underlying contract interactions and relayer details.
2. Integration flow (high level)
Maker creates and signs an order off-chain (locally).
The maker submits the signed order to the Limit Order API / relayer (optional).
A Taker discovers the order (via the API or other discovery means) and fills it on-chain by calling LimitOrderManager. The on-chain fill is executed atomically and operates the associated position.
Note: The API/relayer is optional — it's allowed to call the LimitOrderManager directly to fill orders on-chain.
⚠️ Note: Once an order is signed, it can only be canceled on-chain (by sending an on-chain cancel transaction) to prevent it from being filled.
LimitOrderManager contracts
The `LimitOrderManager` is a critical component of the f(x) Protocol that enables users to create and execute limit orders for position management. This system allows traders to:
Open new positions when market conditions meet specific price criteria
Close existing positions at predetermined price levels
Leverage in f(x) Protocol originates from the innovative design of fTokens and xTokens, which split the price volatility of BaseTokens into stable and leveraged components. This allows users to balance between stability and risk, creating flexible investment strategies.
Key Features
fTokens (e.g., fETH, fxUSD, btcUSD):
Fully decentralized and native to Ethereum, Bitcoin, and Convex ecosystems.
Minimize volatility while maintaining slight market exposure (0% volatility for most fTokens, except fETH at 10%).
Support instant creation and trading to meet stablecoin demands.
xTokens (e.g., xETH, xeETH, xwBTC):
Perpetual long tokens for ETH, BTC, and CVX with built-in leverage.
Fully on-chain, composable, and highly liquid.
Offer low liquidation risk, providing a safer alternative for leveraged positions.
How It Works
Depositing BaseTokens:
Users deposit BaseTokens (e.g., wBTC for btcUSD and xwBTC) into the protocol.
Splitting Price Volatility:
The protocol splits the price volatility of collateral into two components:
fTokens: Absorb no market volatility (0% allocation, except 10% for fETH).
xTokens: Amplify leverage (100% allocation, except 90% for xETH).
Diversified Exposure:
This split enables users to diversify BaseToken exposure by balancing between stability (fTokens) and leverage (xTokens).
Minting and Redemption Fees:
fTokens: 0–0.25% fee.
xTokens: 1.5–2.5% fee.
Users can avoid these fees by trading tokens on secondary markets.
Building Secure and Decentralized Freedom with a Touch of Magic since 2021
Aladdin DAO is a decentralized builder and incubator of cutting-edge DeFi protocols. We are a global community of contributors composed of enthusiasts, shadowy super-coders, and DeFi innovators. Our current focus is in building new approaches to yield farming optimization and automation within the Curve ecosystem and with our latest product, f(x) Protocol, we are expanding to scalable decentralized stablecoins.
To date Aladdin has built three products: Concentrator, Clever, and f(x) Protocol. Each of these protocols offers powerful new tools for DeFi users and adds new, composable DeFi money lego which will help form the basis of what we believe will be the decentralized future of global finance.
Each protocol was launched independently with NO VC & NO TEAM ALLOCATION.
// Users call ShortPoolManager.redeemByCreditNote()
function redeemByCreditNote(address pool, uint256 debts, uint256 minColls) external {
// Transfer CreditNote from user
IERC20(creditNote).safeTransferFrom(_msgSender(), address(this), debts);
// Redeem equivalent collateral
colls = IShortPool(pool).redeemByCreditNote(rawDebts);
// Apply protocol fees
uint256 protocolFees = (colls * getRedeemFeeRatio()) / FEE_PRECISION;
colls -= protocolFees;
// Transfer net collateral to user
_transferOut(fxUSD, colls, _msgSender());
}
/// @notice Return the details of the given position.
/// @param tokenId The id of position to query.
/// @return rawColls The amount of collateral tokens supplied in this position.
/// @return rawDebts The amount of debt tokens borrowed in this position.
function getPosition(uint256 tokenId) external view returns (uint256 rawColls, uint256 rawDebts);
/// @dev Mapping from tick to tree node id.
mapping(int256 => uint48) public tickData;
/// @dev Mapping from tree node id to tree node data.
mapping(uint256 => TickTreeNode) public tickTreeData;
/// @dev Internal function to get the root of the given tree node.
/// @param node The id of the given tree node.
/// @return root The root node id.
/// @return collRatio The actual collateral ratio of the given node, multiplied by 2^60.
/// @return debtRatio The actual debt ratio of the given node, multiplied by 2^60.
function _getRootNode(uint256 node) internal view returns (uint256 root, uint256 collRatio, uint256 debtRatio) {
collRatio = E60;
debtRatio = E60;
while (true) {
bytes32 metadata = tickTreeData[node].metadata;
uint256 parent = metadata.decodeUint(PARENT_OFFSET, 48);
collRatio = (collRatio * metadata.decodeUint(COLL_RATIO_OFFSET, 64)) >> 60;
debtRatio = (debtRatio * metadata.decodeUint(DEBT_RATIO_OFFSET, 64)) >> 60;
if (parent == 0) break;
node = parent;
}
root = node;
}
Executes a limit order by filling it with the specified amounts. (taker's operation)
cancelOrder(order)
Cancels an existing order (only callable by the order maker).
getOrderDetails(order)
Returns the order details (including making/taking tokens and amounts) for an order.
getExecution(orderHash)
Returns the current execution status of an order.
getOrderHash(order)
Calculates and returns the unique hash for a given order. This hash is used as the identifier for tracking order execution status.
increaseNonce()
Increments the caller's nonce, effectively invalidating all previously signed orders with the old nonce. Useful for batch cancelling multiple orders. (Basically, it means cancelAll)
Key Concepts
Order Structure
The Order struct contains the following key fields:
Making Amount: The amount of tokens the order maker is offering
Taking Amount: The amount of tokens the order maker wants to receive
These amounts are calculated based on the order type and side.
Order Hash
The Order Hash is a unique identifier for each order, calculated using the EIP712 standard. This hash serves as:
Unique Identifier: Each order has a distinct hash based on its parameters
Execution Tracker: Used to store and retrieve order execution status
Signature Target: The hash is what gets signed by the order maker
Database Key: Off-chain systems use this hash to index and track orders
The order hash is deterministic - the same order parameters will always produce the same hash. This allows for consistent tracking across different systems and ensures order integrity.
Signature
The Signature is a cryptographic proof that the order hash was authorized by the order maker. The signature content is the order hash (not the raw order data), ensuring any parameter changes invalidate the signature.
Signature Format:
EOA Signatures: 65 bytes (r, s, v) or 64 bytes (r, s) for EIP-2098 compact format
Smart Contract Signatures: Variable length, validated through EIP-1271 isValidSignature method
Integrate Examples:
Signature Creation Example
How to Call fillOrder
Function Signature
Parameters
order: The order struct containing all order details
signature: EIP712 signature from the order maker
makingAmount: Amount of making tokens the filler provides
takingAmount: Amount of taking tokens the filler wants from the order
Prerequisites
Valid Signature: The order must be properly signed by the maker
Order Validation: Order parameters must pass validation checks
Price Conditions: Trigger price conditions must be met (if applicable)
Token Approvals: Filler must approve tokens to the LimitOrderManager
Sufficient Balance: Filler must have sufficient token balance
Example Integration
FX Auto-Compound
aFXN:
Description: aFXN is an auto-compounding asset derived from cvxFXN.
Yield: Staking cvxFXN earns:
Rewards from veFXN.
A share of boosted FXN earnings and CVX tokens from Convex LPs.
Important:
Converting FXN to cvxFXN is irreversible.
You can stake and unstake cvxFXN tokens but cannot revert them to FXN.
For risk considerations, creating orders through the API documentation is not recommended at this time. Please use the website to create limit orders.
⚠️ IMPORTANT RISK DISCLAIMER: By submitting orders through APIs, you acknowledge and accept full responsibility for all trading risks including but not limited to: market volatility, slippage, liquidation risk, smart contract risks, and potential total loss of funds. This API provides no guarantees regarding order execution, profitability, or protection against losses. Use at your own risk and ensure you fully understand the implications of each order before submission.
2. Get Active Orders (For Bots/Keepers)
Returns all open and fillable orders, sorted by their createdAt timestamp in ascending order. This endpoint is optimized for keepers, bots, or external indexers that need to continuously fetch newly created orders available for on-chain execution.
Query Parameters:
after (optional): Only include orders created after this UNIX timestamp (in seconds). Useful for incremental syncing.
limit (optional): Maximum number of orders to return (default: 100, max: 5000)
Response:
3. Get Order Updates (For Real-time Monitoring)
Returns orders that have changed state (created, filled, cancelled, or expired), sorted by their updatedAt timestamp in ascending order. Ideal for clients or bots polling for updates to maintain an up-to-date local view of the order book.
Query Parameters:
after (optional): Only include orders updated after this UNIX timestamp (in seconds). Enables incremental polling for order state changes.
limit (optional): Maximum number of orders to return (default: 100, max: 1000)
Response:
Earn
Where Does the Yield Come From?
The f(x) Protocol provides multiple opportunities to earn yields through Earn Pools and FX Auto-Compound mechanisms. These tools leverage BaseTokens, Liquid Staking Derivatives (LSDs), and FXN emissions to generate returns.
Earn Pools
Stable holders can stake their fTokens into Earn Pools (also known as Stability Pools) to earn yields generated by BaseTokens, plus FXN emissions. Each Earn Pool is tailored to the specific characteristics of its collateral.
fxUSD Earn Pools
Collateral: wstETH and frxETH.
Yield: Earn wstETH and frxETH rewards.
Details:
btcUSD Earn Pools
Collateral: WBTC.
Yield: Earn WBTC rewards.
Details:
rUSD Earn Pools
Collateral: eETH and ezETH (ETH Liquid Restaking Tokens).
Yield: Earn restaking rewards, including points, without ETH price exposure.
Details:
cvxUSD Earn Pools
Collateral: CVX.
Yield: Earn staking rewards from Convex Finance.
Details:
fETH Earn Pools
Collateral: stETH.
Yield: Earn native LSD rewards from stETH, plus FXN emissions.
Oracle
Learn more about V1 oracle design.
Here is a breakdown of the key features and mechanisms of the oracle solution.
Enhanced collateral price feeds: In addition to the original TWAP, spot prices are incorporated, with additional price feeds from Curve, Uniswap V3, and Balancer.
Arbitrage prevention: Minting and redeeming transactions are conducted at different prices to eliminate arbitrage trades. This helps to protect the collateral held by the protocol.
fToken can be minted at the minimum price
fToken can be redeemed at the maximum price
xToken can be minted at the maximum price
xToken can be redeemed at the minimum price
Risk management
The collateralization ratio is calculated at the maximum price as well as stability pool liquidations. This ensures that risk is managed effectively and liquidations occur at appropriate levels to maintain system stability.
Net Asset Value
The NAV is calculated based on TWAP during the non-transacting periods. This NAV calculation can serve as an oracle price feed for various DeFi applications integrating f(x) assets.
Additional protection measures for xTokens
To prevent arbitrage trades, xTokens cannot be both minted and redeemed within the same block. Additionally, a transfer of xTokens cannot occur within a specified timeframe of thirty minutes after minting. These measures help in mitigating potential exploits and maintaining price integrity.
For better responsiveness in case of emergency, the following multisignature wallet can pause xPOSITION and sPOSITION operations.
The threshold for this wallet is set to 3 signatures.
Signer
Address
🪔 Team member
The emergency multisig can exclusively pause the following contracts:
LongPoolManager:
ShortPoolManager:
struct Order {
address maker; // Order creator
address pool; // Target pool address
uint256 positionId; // Position ID (0 for new positions)
bool positionSide; // true = long, false = short
bool orderType; // false = limit order, true = stop order
// orderType
// for limit order (orderType = true)
// orderSide = true: open order, order can be filled only oracle price is <= triggerPrice
// orderSide = false: close order, order can be filled only oracle price is >= triggerPrice
// stop order (orderType = false)
// always close order
// orderSide = true: take profit order, order can be filled only oracle price is >= triggerPrice
// orderSide = false: stop loss order, order can be filled only oracle price is <= triggerPrice
bool orderType;
bool allowPartialFill; // Allow partial execution
uint256 triggerPrice; // Price trigger condition
int256 fxUSDDelta; // fxUSD amount change
int256 collDelta; // Collateral amount change
int256 debtDelta; // Debt amount change
uint256 nonce; // Maker's nonce for batch cancellation
bytes32 salt; // Unique order identifier
uint256 deadline; // Order expiration timestamp
}
// EIP712 Domain for f(x) Limit Order Manager
const domain = {
name: "f(x) Limit Order Manager",
version: "1",
chainId: 1, // Mainnet
verifyingContract: limitOrderManager.address
};
// EIP712 Types for Order struct
const types = {
Order: [
{ name: "maker", type: "address" },
{ name: "pool", type: "address" },
{ name: "positionId", type: "uint256" },
{ name: "positionSide", type: "bool" },
{ name: "orderType", type: "bool" },
{ name: "orderSide", type: "bool" },
{ name: "allowPartialFill", type: "bool" },
{ name: "triggerPrice", type: "uint256" },
{ name: "fxUSDDelta", type: "int256" },
{ name: "collDelta", type: "int256" },
{ name: "debtDelta", type: "int256" },
{ name: "nonce", type: "uint256" },
{ name: "salt", type: "bytes32" },
{ name: "deadline", type: "uint256" }
]
};
// Sign the order (actually signs the order hash)
async function signOrder(order, signer) {
// _signTypedData internally calculates the order hash and signs it
const signature = await signer._signTypedData(domain, types, order);
return signature; // This signature proves the signer authorized this specific order hash
}
// Verify signature before using
async function verifySignature(order, signature, expectedSigner) {
const recoveredAddress = ethers.utils.verifyTypedData(domain, types, order, signature);
return recoveredAddress.toLowerCase() === expectedSigner.toLowerCase();
}
// Usage example
const signature = await signOrder(order, signer);
const isValid = await verifySignature(order, signature, await signer.getAddress());
console.log(`Signature valid: ${isValid}`);