# Seacows Nft Amm: Open problem * official website: seacows.io ## Looking for solution Part 1: Currently we are lookng for **Formal Financial Mathematical Modeling and Risk mitigation strategies of Seacows NFT AMM protocol's core mechanism** TODO: * Formally specify the contract’s business logic to produce a formal mathematical closed-form model that provides precise, unambiguous, and comprehensive documentation, as well as a simulation report. This model is executable, serving as a reference implementation or official implementation for smart contract integration. * It is noted the current focus will be the **withdrawal process** of the AMM design. Comment: * 我们判断解决方案主要在于对AMM的理解和对numercial solution, optimizaiton的数学工具的运用 # Context/Background/背景知识: * [中文](https://y1cunhui.github.io/uniswapV3-book-zh-cn/docs/introduction/constant-function-market-maker/) ## Market Making Basics ### Market Makers Consider a market for two financial assets, say, USDC and ETH. A market maker is a participant in this market who is willing, at any time, to trade either one for the other. If you have 100 million USDC and want to use it to buy ETH, you probably won't be able to find another individual who wants to do the opposite trade at the exact same time. Instead, you will most likely go to a market populated by one or more market makers and trade with them. ## Automated Market Makers(AMM) In the past year, automated market makers (AMMs), led by [Uniswap](https://info.uniswap.org/#/), have become hugely popular on Ethereum, handling billions of dollars of volume daily. True to their name, AMMs automate much of the market making process. ## The Constant Product Formula(x * y = k) The constant product formula is a simple rule that allows anybody to spin up both a new market and a new AMM for a new pair of assets instantaneously. To create a new Constant Product AMM (CPAMM) between two assets X and Y, a user, called a liquidity provider, or LP, deposits reserves x and y of those two assets. The ratio of these assets at any given time represents the instantaneous price on the AMM, or the price it will charge for a very small order. For example, if a CPAMM contains 2,000 USDC and 1 ETH in its reserves, its instantaneous price for ETH will be 2,000 USDC. When traders come to trade with the AMM, it decides what price to give them based on the formula **x * y = k, where x and y are the reserve sizes and k is a constant. This means that the product of its reserve sizes stays the same during a trade (ignoring fees). Example Consider an ETH/USDC CPAMM with 2,000 USDC and 1 ETH in the reserves, so that x = 2,000, y = 1, and x * y = k = 2,000. The instantaneous price of this AMM is 2,000 / 1 = 2,000 USDC per ETH. If a trader comes and buys 2,000 USDC worth of ETH, that means they are depositing 2,000 USDC into the X reserves, so that we will have x = 2,000 + 2,000 = 4,000. Then, since k = 2000, we must have y = k/x = 2000/4000 = 0.5 after the trade. Since y was originally 1, 1 - 0.5 = 0.5 ETH must have gone to the trader. Since the trader bought 0.5 ETH with their 2000 USDC, they paid an average price of 4,000 USDC per ETH. This high price relative to the instantaneous price reflects the large order size relative to the liquidity in the AMM. ## What is NFT AMM? Previous we have amm for token. Now we intend to build amm for NFT. * Seacows NFT AMM protocol is world’s first effective peer-to-pool NFT AMM Protocol, which solves liquidity fragmentation by leveraging constant product market maker (CPMM) price discovery mechanism which modified to enable "integer nft liquidity add/withdraw". ## Problem definition(开放数学问题): ### What is the problem what needs to be solved? ### ** Problem to solve * **When withdrawing from ERC20-ERC721 Pair, there is possibility that user is withdrawing a fractional amount of NFT. It is not possible as NFT is non-fungible.** * Uniswap v2 used $x*y =k$ curve (CFMM, constant ), price_token_A = reserve_token_B / reserve token_A. Here x(number of nfts), y (number of erc20 tokens/ETH), k = the product of x * y In uniswap v2, x could be decimal, eg: 0.2, or 0.333333, however, here x could only be integer amont, eg, 1,2,3….. Y could still be decimal, * When deposits(add liquidity), it is easy to treat nft as erc20 tokens * When withdraw, **we only allow integer amount of nft withdraw** ## Current Solution: Complement method(see details in reference) - **If \( n \) is a whole number**: No compensation is needed, \( c = 0 \). - **If \( 0 < n < 0.5 \)**: The user receives no NFT, but is compensated with additional tokens. Calculate \( c \) based on the current token-to-NFT ratio in the pool. - **If \( 0.5 <= n < 1 \)**: The user receives 1 NFT, but some tokens are subtracted from \( t \). Again, calculate \( c \) based on the token-to-NFT ratio. ### comment on complement solution: * It is an ok solution, but might facing risk or inefficency in mechanism design. # **Seacows nft amm Open problems: 1. looking for numerical solution which helps to **determine the smallest possible amount to withdraw**. This is particularly useful to ensure fairness and predictability in the withdrawal process, especially given the non-fungibility of NFTs. ## Mathmatical Simulation: Let's break this down: Given that the AMM functions by determining a relationship between two assets (in this case, Tokens and NFTs), we'll assume that the relationship is given by some function \( f \) where: $[ \text{Tokens} = f(\text{NFTs}) ]$ This function represents the AMM curve, which dictates the cost in Tokens to acquire NFTs and vice versa. 1. **Marginal Cost**: The marginal cost in Tokens to acquire an infinitesimally small amount more of the NFT is given by the derivative of this function: $[ f'(\text{NFTs}) = \frac{df}{d(\text{NFTs})} ]$ This gives us the slope of the curve at any given point, representing the cost in Tokens for a tiny additional amount of NFT. 2. **Incremental Cost**: If you wanted to acquire a finite small amount \( \Delta \text{NFT} \) (for instance, 0.001 NFT), the cost in Tokens would be: $[ \Delta \text{Tokens} = f'(\text{NFTs}) \times \Delta \text{NFT} ]$ 3. **Iterative Process**: * Start with a withdrawal amount of $( x )$ NFTs. * Calculate the marginal cost $( f'(\text{NFTs}) )$. * Multiply this by a small increment to get the additional Tokens required. * Adjust \( x \) based on the cost and your threshold, and recalculate. For example: * If $( f'(\text{NFTs}) \)$ is large, then you're on a steep part of the curve, and adding a bit more NFT to the withdrawal will cost a lot more in Tokens. * If $( f'(\text{NFTs}) \)$ is close to zero, you're on a flat part of the curve, and adding more NFT to the withdrawal won't cost much more in Tokens. 4. **Exit Conditions**: * If the calculated $( f'(\text{NFTs}) )$ falls below a set threshold (indicating you're getting diminishing returns on NFTs for your Tokens). * If you reach a maximum number of iterations. * If your adjusted withdrawal amount becomes negligible. **Challenges**: * The actual form and complexity of \( f \) depends on the specific mechanics of the AMM. In simple AMMs like Uniswap, it's a straightforward function, but more complex AMMs may have multiple variables and parameters. * For computational efficiency, you might want to use numerical methods like the Newton-Raphson method to find the most optimal withdrawal point, rather than an iterative adjustment. To implement this as an algorithm, you'll need to: 1. Define the function \( f \) (this will be derived from the AMM's logic). 2. Calculate its derivative. 3. Use the derivative in an iterative process to find the optimal withdrawal amounts for Tokens and NFTs. Remember, the goal is to find an optimal point where you get as many NFTs as possible for the least amount of Tokens, but without crossing a point where the marginal cost in Tokens becomes prohibitive. ## Math tool: demos Desmos is a fantastic tool for visualizing functions. we can go through the process of setting it up in Desmos. Here's how you can simulate the aforementioned scenario: 1. **Defining the Function**: Let's assume a simple function for the relationship between Tokens and NFTs. This function is a hyperbola, which is used by AMMs like Uniswap: \[ f(\text{NFTs}) = \frac{k}{\text{NFTs}} \] where \( k \) is a constant representing the liquidity pool's size. 2. **Graphing the Function**: - Open Desmos. - Define $( k )$ as a slider with a decently large value, say $( k = 10000 )$. - Plot the function: $( f(x) = \frac{k}{x}$ \. You should see a hyperbola. 3. **Marginal Cost**: The derivative is: $[ f'(x) = -\frac{k}{x^2} ]$ Plot this as well. This curve will show you the rate of change of the Tokens with respect to NFTs. 4. **Simulating the Incremental Cost**: - Choose a point $( x_0 )$ (this is the initial amount of NFTs you want to withdraw). You can define this as a slider. - The incremental cost in tokens for a small amount \( \Delta x \) is approximately \( f'(x_0) \times \Delta x \). For simplicity, choose $( \Delta x )$ as a constant, say 0.1. - You can then find the new token amount using: $( \Delta y = f(x_0 + \Delta x) - f(x_0) )$. Compare this with the previous step's value to see if the AMM's rate aligns with the marginal cost. 5. **Visualize**: - Highlight the points \( (x_0, f(x_0)) \) and \( (x_0 + \Delta x, f(x_0 + \Delta x)) \) to visualize the effect of withdrawing an incremental amount of NFTs. By adjusting the slider for \( x_0 \), you can visualize how the token cost changes as you attempt to withdraw different amounts of NFTs. The slope of the tangent line given by \( f'(x) \) at any point will give you a sense of how steep the cost is at that point. this is a simple hyperbolic model used for illustration. ## Todo 1. implement the demos regarding close form or numerical solution of the problem 2. mapping the math to solidity safe math. ### Simulation and Testing: Once the mathematical model is established, we want to simulate the mechanism under different scenarios. Test for: * Different liquidity levels. * Different withdrawal amounts. * How the protocol behaves under stress (e.g., many withdrawals in quick succession). ## Reference ### Seacows nft amm goerli testnet 1. https://app-dev.seacows.io/ ### complement method: * See details below ## Seacows Complement ### Problem to solve When withdrawing from ERC20-ERC721 Pair, there is possibility that user is withdrawing a fractional amount of NFT. It is not possible as NFT is non-fungible. ### Solution: Seacows Complement Given the following variables: #### Pair state variables | Variables | Description | Domain | | --------- | -------------------------- | ------------------- | | $R_x$ | Complemented Token Reserve | $\{R_x \in R^{+}\}$ | | $R_y$ | Complemented NFT Reserve | $\{R_y \in R^{+}\}$ | | $B_x$ | Actual Token Balance | $\{B_x \in R^{+}\}$ | | $B_y$ | Actual NFT Balance | $\{B_y \in R^{+}\}$ | | $x_c$ | Token Complement | $\{x_c \in R\}$ | | $y_c$ | NFT Complement | $\{y_c \in R \}$ | #### Withdrawal variables | Variables | Description | Domain | | --------- | ------------------------- | ------------------- | | $x$ | Expected Token Amount Out | $\{x \in R^{+}\}$ | | $y$ | Expected NFT Amount Out | $\{y \in R^{+}\}$ | | $x_o$ | Actual Token Amount Out | $\{x_o \in R^{+}\}$ | | $y_o$ | Actual NFT Amount Out | $\{y_o \in Z^{+}\}$ | Since $y$ can be a decimal number, we need to adjust the NFT part to make it withdrawable. As a compensation or cost, more or less Token will be withdrawn. Here is how we adjust $y_o$ : $` y_o = \begin{cases} \lceil y \rceil & \quad \text{if } (y - \lfloor y \rfloor) + y_c \leq -0.5\\ \lfloor y \rfloor & \quad \text{if } (y - \lfloor y \rfloor) + y_c > -0.5 \end{cases} `$ The complements $x_c$ and $y_c$ are used to represent how many Token and NFT have been given out more or less. | Complements | +ve | -ve | | ----------- | ------------------------- | ------------------------- | | $x_c$ | Less Token were given out | More Token were given out | | $y_c$ | Less NFT were given out | More NFT were given out | From the formula above, the threshold that determine the outcome is -0.5 NFT. So, the contract can only owe 0.5 NFT. After determined $y_o$, we need to calculate $x_o$. Here is the formula of $x_o$: $` x_o = x - \frac{x}{y}(y_o - y) `$ It uses the Mid Price of Token to compensate for the margin of NFT amount changed. Finally, we update $x_c$ and $y_c$. $` \begin{cases} x_c = x_c + (x_o - x)\\ y_c = y_c + (y_o - y) \end{cases} `$ The complements also affect the reserves which affect the price of swap. $` \begin{cases} R_x = B_x + x_c\\ R_y = B_y + y_c \end{cases} `$ ### Uniswap AMM: 1. [lp wealth](https://research.paradigm.xyz/LP_Wealth.pdf) 2. [Automated Market Making and Loss-Versus-Rebalancing](https://arxiv.org/pdf/2208.06046.pdf) 3. [https://a16zcrypto.com/posts/article/lvr-quantifying-the-cost-of-providing-liquidity-to-automated-market-makers/] ### demos 1. [uniswap v2](https://www.desmos.com/calculator/7wbvkts2jf) 2. [uniswap v3](https://www.desmos.com/calculator/wfp3scq3g3)