0030 XLS 30d: Automated Market Maker on XRPL #78
Replies: 14 comments 9 replies
-
That was great to read! Granted, still digesting it. A few questions, which maybe outlined above and I just need to reread but.
|
Beta Was this translation helpful? Give feedback.
-
Correct. The core concept of an LP token is that it entitles you to a proportional share of both pools. So, if you own 1% of the LP tokens, you can redeem them for 1% of each of the two pools.
No. Instead of dividends two things happen:
The idea is that this will drive up the value of the LP tokens because their value goes up with the value of the pools going up and goes up as the number of outstanding tokens goes down.
Well, the incentive not to "rug" one side of the AMM is that you will take a huge loss if you do so unless the AMM is way out of balance to begin with. The more you force the AMM out of balance, the more it costs to push it further out of balance in that same direction,. The two reasons to make withdrawals from both sides essentially free is:
Allowing single-sided deposit and withdrawal is really just a convenience. You could achieve the same result by doing a half swap followed by a dual-sided deposit or a dual-sided withdraw followed by a half swap. The idea is just to make that easier.
It should not be possible to harm the pool this way. If you push the pool into balance, well, someone had to do it. If you push the pool out of balance, you will suffer a loss because to do that you have to take the asset it overvalues or give the asset it undervalues. |
Beta Was this translation helpful? Give feedback.
-
I've looked around a bit and can't find the "why" behind this proposal. How does this benefit the XRPL ecosystem? Although it's nice that retail holders will be able to earn some yield with their holdings, I doubt that's the "vision" behind this proposal. Is this an effort so supercharge XRP's liquidity? Or are there inherent flaws in the LOB DEX that the AMM proposal resolves/improves? I'm also interested in understanding a bit more of the implications for assets that already have an issuer fee such as BitStamp USD (.2%). When we're talking "order of operations" would the issuer fee be applied before the AMM fees are taken out? |
Beta Was this translation helpful? Give feedback.
-
@ZerpCraft I plan to write up a fairly lengthy explanation of why I think this proposal is a huge benefit to the XRPL ecosystem when we get closer to having a complete implementation. But I think the short answer is that there are two reasons: One is to improve liquidity on the XRPL by ensuring that it is always possible to exchange between popular assets. The other is to allow people who hold volatile digital assets to earn a return from the volatility rather than it being a cost. The way issuer fees work on XRPL is fairly consistent in all existing operations and I don't see any reason to change that. The account sending the asset pays the issuer fee as it pays out the asset. So if I want to deliver 100 USD/Bitstamp to an AMM, it will cost me slightly more than 100 USD/Bitstamp to do it. Issued assets work like this: |
Beta Was this translation helpful? Give feedback.
-
Would you consider adding of a feature similar to Authorized Trust Lines that would authorize liquidity providers for private pools? For example, if the authorized trust lines for the AMM pools and authorized LPs are not the same set. |
Beta Was this translation helpful? Give feedback.
-
Please let me know if I'm misunderstanding, but the equation in section 4.1 for price decay seems slightly off. I think it should be something like |
Beta Was this translation helpful? Give feedback.
-
@aanchal4 Couple of random thoughts:
|
Beta Was this translation helpful? Give feedback.
-
I notice that equation 10 has an error, duplicated here: I'm not familiar with the markup syntax in this area, but I think the problem is the underscore I think removing those extra |
Beta Was this translation helpful? Give feedback.
-
@JoelKatz @WietseWind @ximinez Good reads on where legislation might be headed, especially considering DeFi. US Treasury Illicit Finance Risk Assessment of Executive Order 14067 Ensuring Responsible Development of Digital Assets - https://www.federalregister.gov/documents/2022/03/14/2022-05471/ensuring-responsible-development-of-digital-assets |
Beta Was this translation helpful? Give feedback.
-
@JoelKatz Can't people already buy and sell things on the XRP Ledger by using order books? This means that they have to find someone who wants to sell the thing they want to buy, and someone who wants to buy the thing they want to sell. This can be hard, and it can take a long time. Is that the main reason you developed AMM? It just makes it easier to buy and sell things on the XRP Ledger while enhancing liquidity and giving the XRP owner some transactional income? It can be easier to find someone to buy or sell something from. I'm thinking there are no asset value requirements for using an AMM. Trading on an AMM does not have to include a digital asset nor does it have to be a Company/organization. Here are some of the people who might use an AMM: Here are some of the assets that can be traded on an AMM: AMMs can be used to trade any asset that can be represented on a blockchain. This makes them a very versatile tool for buying, selling, and trading assets. It can include gold, paintings, cash, or any other asset that can be represented on a blockchain. AMMs are not specifically aimed at companies who take part in the smart contracts market, but they can be used by companies in this market. |
Beta Was this translation helpful? Give feedback.
-
The security audit report for this AMM is now available. |
Beta Was this translation helpful? Give feedback.
-
Refer to PR #125 |
Beta Was this translation helpful? Give feedback.
-
Omg this looks amazing :D |
Beta Was this translation helpful? Give feedback.
-
Final XLS-30 Specification
Automated Market Maker on XRP Ledger
Abstract
The XRPL decentralized exchange (DeX) currently provides liquidity exclusively by manual market making and order books. This proposal adds non-custodial automated market maker (AMM) as a native feature to the XRPL DeX in a way that provides increased returns to those who provide liquidity for the AMM and minimizes the risk of losses due to volatility.
We propose a unique mechanism where the AMM instance continuously auctions off trading advantages to arbitrageurs, charging them and giving these earnings to its liquidity providers. This allows liquidity providers to take a large share of the profits that would normally be taken by arbitrageurs.
The AMM instance charges a spread on the trades that change the ratio of tokens in the instance's pools. This trading fee is added to the AMM instance's capital pool, thus adding to the liquidity providers' returns.
The AMM instances also provide governance rights to the largest share holders of the AMM instance. This allows them to vote on the trading fee the instance charges.
XRPL's AMM based DeX interacts with XRPL's limit order book (LOB) based DeX so that users of AMM pools have access to all order flow and liquidity on LOB DeX, and vice versa. The payment and order placement transactors automatically determine whether swapping within a liquidity pool or through the order book will provide the best price for the user and execute accordingly. Pathfinding considers paths with both order books and AMMs in various combinations to improve the overall exchange rate.
1. Introduction
AMMs are agents that pool liquidity and make it available to traders according to a predetermined algorithm. This is a proposal for geometric mean market maker (GM3) based DeX as a native XRPL feature. GM3 algorithmically discovers a fair exchange value, stabilized by arbitrage, to automatically produce liquidity. On XRPL, this would provide liquidity pools between XRP and issued assets as well as between any two issued assets. Arbitrageurs play a significant role in keeping the AMM DeX in a stable state with respect to external markets.
Several things that contribute to the costs that trading imposes on AMM pools are naturally much less significant on XRPL:
Low transaction fee: An arbitrageur only submits a transaction when the expected profit from the transaction exceeds the transaction fee. XRPL’s transaction fees are much lower than those on most DeFi chains. This benefits the AMM instance pools by narrowing the time windows in which the instance suffers decreased trading volume due to its spot-market price being off due to volatility or asymmetric trading.
Fast finality: Arbitrageurs take risk (for which they must be compensated at the instance pool’s expense) due to the block times. Prices may change while their transaction is in flux. XRPL has faster block times than many of the fastest competing major blockchains.
Canonical transaction ordering: Transactions on XRPL are canonically ordered. Other blockchains have block producers, miners, or stakers who try to extract value from arbitrage transactions by delaying, reordering, front-running, or selectively including them to extract more value from the pool and the arbitrageurs. XRPL doesn’t have this.
AMMs are more effective and lucrative when transactions execute quickly, cheaply, and fairly. This means that XRPL AMM could provide more liquidity at lower prices, yet still provide a compelling return.
1.1. Terminology
where,
In this version of the proposal, pools must be of equal value. The implicit normalized weights are$W_{A} = W_{B} = 0.5$ .
Liquidity Providers: Liquidity providers (LPs) are the traders who add liquidity to the AMM instance's pools, thus earning shares of the pools in the form of
LPTokens
.LPTokens: LP tokens represent the liquidity providers' shares of the AMM instance's pools.
LPTokens
are tokens on XRPL. EachLPToken
represents a proportional share of each pool of the AMM instance. The AMM instance account issues theLPTokens
to LPs upon liquidity provision.LPTokens
are balanced in the LPs trustline upon liquidity removal.Spot-Price: Spot-price (SP) is the weighted ratio of the instance's pool balances.$SP_{A}^{B}$ is the spot-price of asset $A$ relative to asset $B$ . $TFee$ is the trading fee paid by the trader for trades executed against the AMM instance.
1.2. Overview of XRPL AMM features
AMM Instance Representation
AccountRoot
ledger entry and a new ledger entryAMM
to represent an AMM instance with two asset pools. New transaction typeAMMCreate
is used to createAccountRoot
and the correspondingAMM
ledger entries. In this version we propose to allow for the creation of only one AMM instance per unique asset pair.Trading on AMM Instance
To enable adding and removing liquidity to and from the two pools of the AMM instance, we introduce two new transaction types
AMMDeposit
andAMMWithdraw
respectively. The proposal allows for both equal-asset as well as single-sided deposits and withdrawals. Adding liquidity to an AMM instance yields pool shares calledLPTokens
that are issued by the AMM instance represented as XRPL tokens.LPTokens
can be bought, sold and can be used to make payments exactly as other issued assets/tokens on the ledger.To enable exchanging one pool asset of the AMM instance for the other - a swap - we propose the existing
Payment
transaction.Votable Trading Fee
LPToken
holders upon redemption ofLPTokens
.High trading fee may deter user participation, thus reducing the trading volume and consequently LPs revenue. On the other hand, low trading fee naturally means lower revenue for LPs. Instead of hardcoding the trading fee in the protocol, we propose it be a votable parameter for the
LPToken
holders. The assumption is that LPs being the significant stakeholders in an AMM instance are best positioned to collectively make this decision in a balanced way.Two-way Interoperable AMM and LOB-based DeXs
Novel Feature: Continuous Auction Mechanism
Problem: Due to volatility or asymmetric trading, when relative price of assets in AMM pools goes out-of-sync with that of external markets, AMM does not adjust the prices automatically due to lack of external market information (price-feed) natively. As a result, arbitrageurs intervene, but they have to:
Implications: Liquidity Providers lose because:
Our Approach: Create a mechanism that makes it:
Our Innovative Solution: To achieve the above mentioned, we introduce a mechanism for the AMM instance to continuously auction-off trading advantages for a 24-hour slot at zero trading fee! Anyone can bid for the auction slot with the units of
LPtokens
. The slot-holder can send the arbitrage transaction immediately without the need to wait for their profits to exceed the trading fee, thus eliminating the race condition for them. This also reduces the time window for which the pool suffers decreased trading volume. Additionally, part of proceeds (LPTokens
) from the auction are deleted/burnt that effectively increases LP token holders' ownership in the pool proportionally. Since it's a continuous auction mechanism, if someone outbids an auction slot-holder, part of proceeds from the auction are refunded to the previous slot-holder (computed pro-rata). For details refer Section 5.As slot holder will have significant advantages for arbitrage, it’s expected that arbitrageurs will bid up the price of the auction slot to nearly the value they extract through arbitrage.
2. Creating AMM instance on XRPL
2.1. On-Ledger Objects
We propose the existing
AccountRoot
object together with a new ledger objectAMM
to represent an AMM instance. Currently, theAccountRoot
object type describes a single account, its settings, and XRP balance on the XRP ledger. TheAccountRoot
and theAMM
objects that represent an AMM instance can be created using the newAMMCreate
transaction. XRP balance of the AMM instance pools is always tracked via the existingBalance
field of theAccountRoot
object. The issued asset balances of the AMM instance pools andLPTokens
are automatically tracked via trustlines. The AMM can be traded against using the newAMMDeposit
andAMMWithdraw
and the existingPayment
transactions.Note that in this version, only equal-weighted two asset pools are supported. However, differing weighted pools could be supported in future versions.
2.1.1. Ledger Entries representing AMM instance
AccountRoot
ledger entryA new flag
lsfAMM
is introduced to theAccountRoot
object.lsfAMM
The unique ID of the
AccountRoot
object, a.k.a.AccountRootID
is computed as follows:AccountRootID
=SHA512-Half
(i || Parent Ledger Hash ||AMMID
)AccountRootID
exists, repeatAccountRootID
AMM
ledger entryThe unique ID of the new
AMM
object , a.k.aAMMID
is computed as follows:SHA512-Half
of some of the following values:issuer
of the issued asset;currency
of the issued asset;issuer
of the second issued asset, if there exists one;currency
of the second issued asset, if there exists one;The order of the fields to compute the hash is decided canonically. The
AMMID
associated with thisAccountRootID
is this hash to ensure the uniqueness of the AMM instance. The applications can look-up theAccountRootID
for a specific AMM instance by providing the asset pair for that instance.The
AMM
ledger entry contains the following fields for theAccountRoot
object that represents the AMM instance.AccountID
specifies the ID of theAccountRoot
object associated with thisAMM
ledger entry.TradingFee
specifies the fee, in basis point, to be charged to the traders for the trades executed against this AMM instance. Valid values for this field are between 0 and 1000 inclusive. A value of 1 is equivalent to 1/10 bps or 0.001%, allowing trading fee between 0% and 1%. Trading fee is a percentage of the trade size. It is charged on the asset being deposited for theAMMDeposit
(if applicable) andPayment
transactions and on the asset being withdrawan for theAMMWithdraw
(if applicable) transaction. This fee is added to the AMM instance's pools and is distributed to the LPs in proportion to theLPTokens
upon liquidity removal.VoteSlots
represents an array ofVote
objects.AuctionSlot
represents theAuction
object.LPTokenBalance
specifies the balance of outstanding liquidity Provider Tokens (LPTokens).Asset
specifies the one of the assets of the AMM instance.Asset2
specifies the other asset of the AMM instance.Once the AMM
AccountRoot
object is created, we make sure that no further transactions can originate from this account. Conceptually, it is an account that is not owned by anyone. So every possible way of signing the transaction for this account MUST be automatically disabled.2.2. Transaction for creating AMM instance
We define a new transaction
AMMCreate
specifically for creating a new AMM instance represented by anAccountRoot
object and the correspondingAMM
object.Notes:
AMMCreate
is not allowed withLPTokens
AMMCreate
is not allowed if the token’s issuer hasDefaultRipple
flag disabled.2.2.1. Transaction fields for
AMMCreate
transactionTransactionType
string
UINT16
TransactionType
specifies the new transaction typeAMMCreate
. The integer value is 35.Fee
string
AMOUNT
Fee
specifies the integer amount of XRP, in drops, to be destroyed as a cost of creating an AMM instance. We DO NOT propose to keep a reserve for the AMM instance.Amount
string
orobject
AMOUNT
Amount
specifies one of the pool assets (XRP or token) of the AMM instance.Amount2
string
orobject
AMOUNT
Amount2
specifies the other pool asset of the AMM instance.Both
Amount
andAmount2
that represent issued assets MUST havevalue
subfields specified.TradingFee
number
UINT16
TradingFee
specifies the fee, in basis point, to be charged to the traders for the trades executed against the AMM instance. Trading fee is a percentage of the trading volume. Valid values for this field are between 0 and 1000 inclusive. A value of 1 is equivalent to 1/10 bps or 0.001%, allowing trading fee between 0% and 1%.The
AMMCreate
transaction MUST fail if the account issuing this transaction:i. does not have sufficient balances, OR
ii. is NOT the
issuer
of either token AND theRequireAuth
flag for the corresponding token is set AND the account inititaing the transaction is not authorized.If the transaction is successful,
i. Two new ledger entries
AccountRoot
andAMM
are created.ii. The regular key for the
AccountRoot
ledger entry is set to account zero, and the master key is disabled, effectively disabling all possible ways to sign transactions from this account.iii. New trustlines are created.
2.2.2. Trustlines
A successful
AMMCreate
transaction will automatically create the following trustlines:LPTokens
between the AMM instance and the account that initiated the transaction.LPTokens
are uniquely identified by the following:issuer: AMM instance
AccountID
and;currency: the currency code for
LPTokens
for currency codes cur1 and cur2 is formed deterministically as follows:Compute
SHA256{cur1, cur2}
LPTokenID
= 0x03 + first 19 bytes from SHA256The prefix 0x03 is added to identify
LPTokens
The
value
field is computed as follows:where,
Initially by default,$W_{A}$ = $W_{B}$ = 0.5
2.2.3. Cost of creating AMM instance
AccountRoot
andAMM
ledger entriesUnlike other objects in the XRPL, there is no reserve for the
AccountRoot
andAMM
ledger entries created by anAMMCreate
transaction. Instead there is a higherFee
(~ 1 reserve) forAMMCreate
transaction in XRP which is burned as a special transaction cost.2.2.4. Deleting the AMM instance
AccountRoot
andAMM
ledger entriesThe
AccountRoot
andAMM
ledger entries for unused AMM instance must be automatically deleted. An AMM instance is considered unused if no account has a trustline for the correspondingLPTokens
. In order to avoid destroying assets of the AMM instance, the implementation of theAMMWithdraw
transaction MUST guarantee that the AMM instance has no asset reserves if no account owns itsLPTokens
.2.3. AMM trade transactions
Users can trade against specific AMM instances using the new transactions
AMMDeposit
andAMMWithdraw
, and the existingPayment
transaction.AMMDeposit
: The deposit transaction is used to add liquidity to the AMM instance pool, thus obtaining some share of the instance's pools in the form ofLPTokens
.AMMWithdraw
: The withdraw transaction is used to remove liquidity from the AMM instance pool, thus redeeming some share of the pools that one owns in the form ofLPTokens
.Payment
: The payment transaction is used to exchange one asset of the AMM instance for the other.2.3.1. AMMDeposit transaction
With
AMMDeposit
transaction, XRPL AMM allows for both:2.3.1.1 Fields for AMMDeposit transaction
TransactionType
string
UINT16
TransactionType
specifies the new transaction typeAMMDeposit
. The integer value is 36.Asset
object
ISSUE
Asset
specifies one of the assets of the AMM instance against which the transaction is to be executed. TheISSUE
object
may have the following subfields:issuer
currency
If the asset is XRP, then the issuer subfield is not mentioned.
Asset2
object
ISSUE
Asset2
specifies the other asset of the AMM instance against which the transaction is to be executed.Amount
string
orobject
AMOUNT
Amount
specifies the amount of one of the pools assets. If the asset is XRP, then theAmount
is astring
specifying the number of drops. Otherwise it is anobject
with the following subfields:issuer
currency
value
Amount2
string
orobject
AMOUNT
Amount2
specifies the details of other pool asset that the trader is willing to add.EPrice
string
AMOUNT
EPrice
specifies the effective-price of the token out after successful execution of the transaction. ForAMMDeposit
transaction, the token out is alwaysLPToken
.Note that the relative pricing does not change in case of all-asset deposit transaction.
EPrice
is an invalid field for all assets deposits. It should only be specified in case of single sided deposits.LPTokenOut
string
AMOUNT
LPTokenOut
specifies the amount of shares of the AMM instance pools.Let the following represent the pool composition of AMM instance before trade:
LPTokens
issued by the AMM instanceLet the following represent the assets being deposited as a part of
AMMDeposit
transaction and the correspondingLPTokens
being issued by the AMM instance.LPTokens
issued to the LP after a successfulAMMDeposit
transactionAnd let$TFee$ represent the trading fee paid by the account that initiated the transaction to the AMM instance's account. This fee is added to the corresponding AMM instance pool and is proportionally divided among the
LPToken
holders.2.3.1.2. All assets deposit (pure liquidity provision)
If the trader deposits proportional values of both assets without changing their relative pricing, no trading fee is charged on the transaction. If$A$ $B$ are the assets being deposited in return for
$\Delta_{LPTokens}$ , then
and
AND
Following is the updated pool composition of the AMM instance after successful transaction:
LPTokens
2.3.1.3 Single asset deposit
Let$B$ be the only asset being deposited in return for $\Delta_{LPTokens}$ , then this is executed as a combination of equal asset deposit and a swap transaction. The trading fee is only charged on the amount of asset being swapped.
Also let
Similarly,$\Delta{B}$ from the above equation. We call this equation 4.
Similarly, we can derive
Following is the updated pool composition of the AMM instance after successful trade:
LPTokens
2.3.1.4. Specifying different parameters
The proposal allows for traders to specify different combinations of the above mentioned fields for
AMMDeposit
transaction. The implementation will determine the best possible sub operations based on trader's specifications.We introduce the following six flags to the
AMMDeposit
transaction to identify valid parameter combinations.tfLPToken
LPTokenOut
parameter and may optionally includeAmount
andAmount2
combinationtfSingleAsset
Amount
parameter and may optionally includeLPTokenOut
parametertfTwoAsset
Amount
andAmount2
parameter combination and may optionally includeLPTokenOut
paramatertfOneAssetLPToken
Amount
andLPTokenOut
parameter combinationtfLimitLPToken
Amount
andEPrice
parameter combinationtfWithdrawAll
LPTokens
Following are the recommended valid combinations. Other invalid combinations may result in the failure of transaction.
LPTokenOut
,[Amount]
,[Amount2]
Amount
,[LPTokenOut]
Amount
,Amount2
,[LPTokenOut]
Amount
andLPTokenOut
Amount
andEPrice
Details for above combinations:
LPTokenOut
,[Amount]
,[Amount2]
and Flag:tfLPToken
Such a transaction assumes proportional deposit of pools assets in exchange for the specified amount of
LPTokenOut
of the AMM instance.Amount
andAmount2
, if included, have to be provided both and specify minimum deposit amounts for each asset.Deposit fails if the min deposit condition is not met
Amount
,[LPTokenOut]
and Flag:tfSingleAsset
Such a transaction assumes single asset deposit of the amount of asset specified by
Amount
. This is essentially an equal asset deposit and a swap.If the asset to be deposited is a token, specifying the
value
field is required, else the transaction will fail.LPTokenOut
, if included, specified minimumLPTokens
amount that the user receives, else the transaction will fail.Amount
,Amount2
,[LPTokenOut]
and Flag:tfTwoAsset
Such a transaction assumes proportional deposit of pool assets with the constraints on the maximum amount of each asset that the trader is willing to deposit.
LPTokenOut
, if included, specified minimumLPTokens
amount that the user receives, else the transaction will fail.Amount
andLPTokenOut
and Flag:tfOneAssetLPToken
Such a transaction assumes that a single asset
Amount
is deposited to obtain some share of the AMM instance's pools represented by amount ofLPTokenOut
. Since adding liquidity to the pool with one asset changes the ratio of the assets in the two pools, thus changing the relative pricing, trading fee is charged only on the amount of the deposited asset that causes this change.Amount
andEPrice
and Flag:tfLimitLPToken
Such a transaction assumes single asset deposit with the following two constraints:
a. amount of asset1 if specified in
Amount
specifies the maximum amount of asset1 that the trader is willing to depositb. The effective-price of the
LPTokenOut
traded out does not exceed the specifiedEPrice
Following updates after a successful
AMMDeposit
transaction:Balance
field of each accountLPTokenOut
~For more details refer to Appendix A.
2.3.2.
AMMWithdraw
transactionWith
AMMWithdraw
transaction, this proposal allows for both the following:2.3.2.1 Fields
TransactionType
string
UINT16
TransactionType
specifies the new transaction typeAMMWithdraw
. The integer value is 37.Asset
object
ISSUE
Asset
specifies one of the assets of the AMM instance against which the transaction is to be executed.Asset2
object
ISSUE
Asset2
specifies the other asset of the AMM instance against which the transaction is to be executed.Amount
object
orstring
AMOUNT
Amount
specifies one of the pools assets that the trader wants to remove. If the asset is XRP, then theAmount
is astring
specifying the number of drops. Otherwise it is anobject
with the following subfields:issuer
currency
value
Amount2
string
orobject
AMOUNT
Amount2
specifies the other asset that the trader wants to remove.EPrice
object
AMOUNT
EPrice
specifies the effective-price of the token out after successful execution of the transaction. ForAMMWithdraw
transaction, the out is either XRP or issued token. The asset in is alwaysLPToken
. SoEPrice
is always anobject
.Note that the relative pricing does not change in case of all-asset withdrawal.
EPrice
is an invalid field for all assets deposits. It should only be specified in case of single sided deposits.LPTokenIn
object
AMOUNT
LPTokenIn
specifies the amount of shares of the AMM instance pools that the trader wants to redeem or trade in.Let following represent the pool composition of the AMM instance before withdrawal:
LPTokens
issued by the AMM instanceLet following represent the assets being withdrawn as a part of
AMMWithdraw
transaction and the correspondingLPTokens
being redeemed.LPTokens
being redeemedLet$TFee$ represent the trading fee paid by the trader to the AMM instance, if applicable. The fee is added to the appropriate pool and is distributed proportionally among the
LPToken
holders upon liquidity withdrawal.2.3.2.1 All assets withdrawal (Pure liquidity withdrawal)
If the trader withdraws proportional values of both assets without changing their relative pricing, no trading fee is charged on the transaction.$A$ and $B$ are the assets being withdrawn by redeeming $\Delta_{LPTokens}$ , then
If
AND
Following is the updated pool composition of the AMM instance after successful trade:
LPTokens
2.3.2.2. Single asset withdrawal
Single asset withdrawal can be conceptualized as two sub trades of equal asset withdrawal and a swap. Let asset$B$ $\Delta_{LPTokens}$ and let
be the only asset being withdrawn to redeem
Similarly, we can derive$\Delta{B}$ from the above equation. We call this equation 8.
Following is the updated pool composition of the AMM instance after successful trade:
LPTokens
2.3.2.3. Specifying different parameters
The proposal allows for traders to specify different combinations of the above mentioned fields for
AMMWithdraw
transaction. The implementation will figure out the best possible operations based on trader's specifications.We introduce the following six transaction flags to the
AMMWithdraw
transaction to identify valid parameter combinations. Other invalid combinations may result in the failure of transaction.tfLPToken
LPTokenIn
field parametertfSingleAsset
Amount
field parametertfTwoAsset
Amount
andAmount2
fields parameter combinationtfOneAssetLPToken
Amount
andLPTokenIn
fields parameter combinationtfLimitLPToken
Amount
andEPrice
fields parameter combinationtfWithdrawAll
LPTokens
held by the accounttfOneAssetWithdrawAll
LPTokens
held by the accountLPTokenIn
Amount
Amount
andAmount2
Amount
andLPTokenIn
Amount
andEPrice
Implementation details for the above combinations:
LPTokenIn
Such a transaction assumes proportional withdrawal of pool assets for the amount of
LPTokenIn
. Since withdrawing assets proportionally from the AMM instance pools does not change the ratio of the two assets in the pool and thus does not affect the relative pricing, trading fee is not charged on such a transaction.Amount
Such a transaction assumes withdrawal of single asset equivalent to the amount specified in
Amount
Amount
andAmount2
Such a transaction assumes all assets withdrawal with the constraints on the maximum amount of each asset that the trader is willing to withdraw.
Amount
andLPTokenIn
Such a transaction assumes withdrawal of single asset specified in
Amount
proportional to the share represented by the amount ofLPTokenIn
. Since a single sided withdrawal changes the ratio of the two assets in the AMM instance pools, thus changing their relative pricing, trading fee is charged on the amount of asset1 that causes that change.Amount
andEPrice
Such a transaction assumes withdrawal of single asset with the following constraints:
a. amount of asset1 if specified in
Amount
specifies the minimum amount of asset1 that the trader is willing to withdrawb. The effective price of asset traded out does not exceed the amount specified in
EPrice
Following updates after a successful transaction:
Balance
field of each accountLPTokens
~For more details refer to Appendix B.
2.4.
AMM Swap
In order to exchange one asset of the AMM instance's pools for another, we DO NOT introduce a new transaction. Instead, we propose to use the existing
Payment
transaction.Let the following represent the pool composition of the AMM instance before a swap.
Let the following represent the balances of assets$B$ and $A$ being swapped in and out of the AMM instance pools respectively with
Payment
transaction.We can compute$\Delta_{A}$ , given $\Delta_{B}$ and $TFee$ as follows:
Similarly, we can compute$\Delta_{B}$ , given $\Delta_{A}$ and $TFee$ as follows:
To change the spot-price of token$A$ traded out relative to token $B$ traded into the pool from $SP_{A}^{B}$ to $SP_{A}^{'B}$ , required $\Delta_{B}$ can be computed as follows:
We can compute the average slippage$S(\Delta_B)$ for the token traded in as follows:
where$SS_B$ , the slippage slope is the derivative of the slippage when the traded amount tends to zero.
We can compute the average slippage$S(\Delta_A)$ for the token traded out as follows:
$$S(\Delta_A) = SS_{A} * \Delta_{A} \tag{14}$$
where$SS_A$ , the slippage slope is the derivative of the slippage when the traded amount tends to zero.
$$SS_{A} = \frac{W_{A} + W_{B}}{2 * \Gamma_{B} * W_{A}} \tag{15}$$
The following is the updated pool composition after a successful transaction:
Note that the conservation function is preserved, however the ratio of the two assets and hence their relative pricing changes after a successful swap.
Following updates after a successful transaction:
Balance
field of each account2.4.1. Interpreting
Payment
transaction for an AMM swapAn XRPL
Payment
transaction represents a transfer of value from one account to another. This transaction type can be used for several types of payments. One can accomplish an equivalent of a swap with thePayment
transaction. Following are the relevant fields of aPayment
transaction.Amount
Currency Amount
AMOUNT
Amount
field is used to specify the amount of currency that the trader wants to deliver to a destination account. For an AMM swap, this is the amount of currency that the trader wants to swap out of the pool.Destination
String
AccountID
Destination
field is used to specify the account that the trader wants to deliver the currency to. This should be either the same account as the transaction or any other account that the trader wishes to send this currency amount to.SendMax
Currency Amount
AMOUNT
SendMax
field is used to specify the maximum amount of currency that the trader is willing to send from the account issuing the transaction. For an AMM swap, this is the amount of currency that the trader is willing to swap into the pool.2.4.2. Flags
The
tfLimitQuality
flag is used to specify the quality of trade. This is defined as the ratio of the amount in to amount out. In other words, it is the ratio of amounts inAmount
andSendMax
fields of aPayment
transaction.For an AMM swap, if a trader wants to buy (swap out) one unit of currency specified in
Amount
field for not more thanX
units per currency specified inSendMax
, the trader would use the following equation:$$ SendMax = X * Amount$$
where
X
is equal to theLimitSpotPrice
for the trade, i.e. the threshold on the spot-price of asset out after trade.2.4.3. Transfer Fee
We propose that the transfer fee is not applied to
AMMCreate
,AMMDeposit
andAMMWithdraw
transactions.AMM instance never pays the transfer fee. Transfer Fee will automatically apply to
Payments
transaction and conditionally in offer-crossing throughOfferCreate
.3. Governance: Trading Fee Voting Mechanism
This proposal allows for the
TradingFee
of the AMM instance be a votable parameter. Any account that holds the correspondingLPTokens
can cast a vote using the newAMMVote
transaction.We introduce a new field
VoteSlots
associated with each AMM instance in theAMM
ledger entry. TheVoteSlots
field keeps a track of up to eight active votes for the instance.VoteSlots
array
ARRAY
VoteSlots
is an array ofVoteEntry
objects representing the LPs and their vote on theTradingFee
for this AMM instance.3.1. Vote Entry object
Each member of the
VoteSlots
field is an object that describes the vote for the trading fee by the LP of that instance. AVoteEntry
object has the following fields:Account
string
AccountID
Account
specifies the XRPL address of the LP.TradingFee
number
UINT16
TradingFee
specifies the fee, in basis point. Valid values for this field are between 0 and 1000 inclusive. A value of 1 is equivalent to 1/10 bps or 0.001%, allowing trading fee between 0% and 1%.VoteWeight
number
UINT32
VoteWeight
specifies theLPTokens
owned by the account that issued the transaction. It is specified in basis points. Valid values for this field are between 0 and 100000. A value of 1 is equivalent to 1/10 bps or 0.001%, allowing the percentage ownership in the instance between 0% and 100%.TradingFee
for the AMM instance is computed as the weighted mean of all the current votes in theVoteSlots
field.where$w_i$ and $fee_i$ represents the
VoteWeight
and theFeeVal
of the correspondingVoteEntry
.3.2.
AMMVote
transactionWe introduce the new
AMMVote
transaction. Any XRPL account that holdsLPTokens
for an AMM instance may submit this transaction to vote for the trading fee for that instance.3.2.1. Fields
Account
string
AccountID
Account
specifies the XRPL account that submits the transaction.TransactionType
string
UINT16
TransactionType
specifies the new transaction typeAMMVote
. The integer value is 38.Asset
object
ISSUE
Asset
specifies one of the assets of the AMM instance against which the transaction is to be executed.Asset2
object
ISSUE
Asset2
specifies the other asset of the AMM instance against which the transaction is to be executed.TradingFee
number
UINT16
TradingFee
specifies the fee, in basis point. Valid values for this field are between 0 and 1000 inclusive. A value of 1 is equivalent to 1/10 bps or 0.001%, allowing trading fee between 0% and 1%.3.3. How does
AMMVote
transaction work?AMMVote
transaction always checks if allVoteEntry
objects in theVoteSlots
array are up-to-date, i.e. check if there is a change in the number ofLPTokens
owned by an account in theVoteEntry
and do the following:If one or more accounts in the
VoteEntry
does not hold theLPTokens
for this AMM instance any more, then remove thatVoteEntry
object from theVoteSlots
array or If the number ofLPTokens
held by one or more account in theVoteEntry
has changed,TradingFee
for the AMM instance and update it in theAMM
object of that instance.Check the
LPTokens
held by the account submitting theAMMVote
transaction. If the account does not hold anyLPTokens
, then the transaction fails with an error code. Otherwise, there are following cases:If there are fewer than eight
VoteEntry
objects in the updatedVoteSlots
array, then:a. Compute the weight of the current vote, add the computed weight of that vote as
VoteWeight
field to the object and readjust in the object.b. Add that
FeeVal
of the current vote to theVoteEntry
object.c. Compute the
TradingFee
for the AMM instance as described above and update theTradingFee
field value in theAMM
object of the AMM instance.If all eight
VoteEntry
slots are full, but this account holds moreLPTokens
, i.e. higherVoteWeight
than theVoteEntry
object with the lowestVoteWeight
, this vote will replace theVoteEntry
with the lowestVoteWeight
. (Followed by same steps as above.)If the account that submitted the transaction already holds a vote, then update that
VoteEntry
andTradingFee
based on the transaction fields.4. Continuous Auction Mechanism
We introduce a novel mechanism for an AMM instance to auction-off the trading advantages to users (arbitrageurs) at a discounted
TradingFee
for a 24 hour slot. Any account that owns correspondingLPTokens
can bid for the auction slot of that AMM instance. This is a continuous auction, any account can bid for the slot any time. Part of the proceeds from the auction, i.e.LPTokens
are refunded to the current slot-holder computed on a pro rata basis. Remaining part of the proceeds - in the units ofLPTokens
- is burnt, thus effectively increasing the LPs shares.4.1. Mechanics
The bid price to purchase the slot must adjust dynamically to function as an auction. If the slot is full, i.e. if an account owns the auction slot, the following should hold:
The complex mechanism is how the price to buy the slot should drop as the occupied slot gets older. We introduce the slot price-schedule algorithm to answer the following questions:
4.1.1. Slot pricing
The minimum price to buy a slot for 24-hour period is called
MinSlotPrice
(M
). Total slot time of 24-hours is divided into 20 equal intervals. An auction slot can be in one of the following states at any given time:Empty - no account currently holds the slot.
Occupied - an account owns the slot with at least 5% of the remaining slot time (i.e. in one of the 1-19 intervals).
Tailing - an account owns the slot with less than 5% of the remaining time (i.e, in the last interval).
The slot-holder owns the slot privileges when in State 2 or 3.
Slot pricing scheduling algorithm
I. Slot state - Empty or Tailing, then
Slot Price =
M
II. Slot state - Occupied, then
Let the price at which the slot is bought be
B
- specified inAmount
ofLPTokens
. Lett
represent the fraction of used slot time for the current slot-holder. Note that for each intervalt
has a discrete value (0.05, 0.1, , ..., 1). LetM
represent the minimum slot price.t
The algorithm to compute the minimum bid price of the slot at any given time enforces the following rules:
t
= 0.05:Notice that the slot price approaches
M
as the slot approaches expiration (i.e., ast
approaches 1).AMMBid
transaction is split between the current slot-holder and the pool. We propose to always refund the current slot-holder of the remaining value of the slot computed from the price at which they bought the slot.$$ f(t) = (1-t)*B $$
The remaining
LPTokens
are burnt/deleted, effectively increasing the LPs share in the pool.X
represent the minimum bid price computed by the price-scheduling algorithm, then,MinBidPrice
&&MaxBidPrice
):MinBidPrice
):mMinBidPrice
<=X
): returnX
MinBidPrice
MaxBidPrice
):MaxBidPrice
>=X
): returnX
MaxBidPrice
We implement the following as the MinSlotPrice:
$$M = LPTokens * \frac{tradingFee}{25}$$
4.1.2.
AuctionSlot
fieldWe introduce a new object field
AuctionSlot
in theAMM
object associated with each AMM instance. TheAuctionSlot
field has the following subfields:Account
string
AccountID
Account
represents the XRPL account that currently owns the auction slot.Expiration
string
UINT32
Expiration
represents the number of seconds since the Ripple Epoch. This marks the end of the time from when slot was bought.DiscountedFee
string
UINT32
DiscountedFee
represents theTradingFee
to be charged to this account for trading against the AMM instance. By default it is 0.Price
string
AMOUNT
Price
represents the price paid for the slot specified in units ofLPTokens
of the AMM instance.AuthAccounts
array
Array
AuthAccounts
represents an array of XRPL account IDs that are authorized to trade at the discounted fee against the AMM instance. The proposal allows for up to a maximum of four accounts.4.1.3.
AMMBid
transactionWe introduce a new transaction
AMMBid
to place a bid for the auction slot. The transaction may have the following optional and required fields:Account
string
AccountID
Account
represents the XRPL account that submits the transaction.TransactionType
string
UINT16
TransactionType
specifies the new transaction typeAMMBid
. The integer value is 39.Asset
object
ISSUE
Asset
specifies one of the assets of the AMM instance against which the transaction is to be executed.Asset2
object
ISSUE
Asset2
specifies the other asset of the AMM instance against which the transaction is to be executed.MinBidPrice
string
STRING NUMBER
MinBidPrice
represents the minimum price that the bidder wants to pay for the slot. It is specified in units ofLPTokens
. This is not a required field. If specified letMinBidPrice
beX
and let the slot-price computed by price scheduling algorithm beY
, then bidder always pays the max(X, Y).AuthAccounts
array
Array
AuthAccounts
represents an array of XRPL account IDs that are authorized to trade at the discounted fee against the AMM instance. The proposal allows for up to a maximum of four accounts.MaxBidPrice
string
STRING NUMBER
MaxBidPrice
represents the maximum price that the bidder wants to pay for the slot. It is specified in units ofLPTokens
. This is not a required field. If specified letMaxBidPrice
beX
and let the slot-price computed by price scheduling slgorithm beY
, then bidder always pays the min(X, Y).Appendices
Appendix A. Specifying different parameters for
AMMDeposit
transactionThe proposal allows for traders to specify different combinations of the fields for
AMMDeposit
transaction. The implementation will figure out the best possible sub operations based on trader's specifications. Here are the recommended valid combinations. Other invalid combinations may result in the failure of transaction.LPTokenOut
,[Amount]
,[Amount2]
Amount
,[LPTokenOut]
Amount
,Amount2
,[LPTokenOut]
Amount
andLPTokenOut
Amount
andEPrice
Implementation details for above combinations:
LPTokenOut
,[Amount]
,[Amount2]
Such a transaction assumes proportional deposit of pools assets in exchange for the specified amount of
LPTokenOut
of the AMM instance.LPTokenOut
If the account that initiated the transaction holds sufficient balances, the transaction is successful. It fails otherwise with an error code.
Similarly, if
[Amount]
,[Amount2]
are specified and the amount of either asset computed above is less than the amounts specified in these fields, then the transaction fails.Amount
,[LPTokenOut]
Such a transaction assumes single asset deposit of the amount of asset specified by
Amount
. This is essentially an equal asset deposit and a swap.Amount
.LPTokenOut
~XRP
or the amount of tokens inAmount
.If the asset to be deposited is a token, specifying the
value
field is required, else the transaction will fail.If
LPTokenOut
field exists, and the amount ofLPTokenOut
computed above is less than the that specified in this field, then the transaction fails.Amount
,Amount2
and[LPTokenOut]
Such a transaction assumes proportional deposit of pool assets with the constraints on the maximum amount of each asset that the trader is willing to deposit.
Amount
. Let this beZ
Z
. Let the computed amount of asset2 beX
.X
<= amount inAmount2
:Amount
X
LPTokenOut
to be issued isZ
Amount2
:Amount2
. Let this beW
W
from above. Let the computed amount of asset1 beY
Y
<= amount inAmount
:Y
Amount2
LPTokenOut
to be issued isW
else, failed transaction.
If
LPTokenOut
field exists, and the amount ofLPTokenOut
computed above is less than the that specified in this field, then the transaction fails.Amount
andLPTokenOut
Such a transaction assumes that a single asset
asset1
is deposited to obtain some share of the AMM instance's pools represented by amount inLPTokenOut
. Since adding liquidity to the pool with one asset changes the ratio of the assets in the two pools, thus changing the relative pricing, trading fee is charged on the amount of the deposited asset that causes this change.Amount
.LPTokenOut
Amount
andEPrice
Such a transaction assumes single asset deposit with the following two constraints:
a. amount of asset1 if specified in
Amount
specifies the maximum amount of asset1 that the trader is willing to depositb. The effective-price of the
LPToken
traded out does not exceed the specifiedEPrice
LPTokenOut
out, given the amount ofAmount
. Let this beX
III
to compute the effective-price of the trade givenAmount
amount as the asset in and theLPTokens
amount ~X
as asset out. Let this beY
.Y
<= amount inEPrice
:Amount
LPTokenOut
to be issued isX
Y
>EPrice
) OR (amount inAmount
does not exist):III
and the givenEPrice
to compute the following two variables:Q
LPTokenOut
out. Let this beW
Q
LPTokenOut
to be issued isW
Following updates after a successful
AMMDeposit
transaction:Balance
field of each accountLPTokenOut
are issued by the AMM instance account to the account that initiated the transaction and a new trustline is created, if there does not exist one.Appendix B. Specifying different parameters for
AMMWithdraw
transactionThe proposal allows for traders to specify different combinations of the above mentioned fields for
AMMWithdraw
transaction. The implementation will figure out the best possible operations based on trader's specifications. Here are the recommended possible combinations. Other invalid combinations may result in the failure of transaction.LPTokenIn
Amount
Amount
andAmount2
Amount
andLPTokenIn
Amount
andEPrice
Implementation details for the above combinations:
LPTokenIn
Such a transaction assumes proportional withdrawal of pool assets for the amount of
LPTokenIn
. Since withdrawing assets proportionally from the AMM instance pools does not change the ratio of the two assets in the pool and thus does not affect the relative pricing, trading fee is not charged on such a transaction.LPTokenIn
.LPTokenIn
Amount
Such a transaction assumes withdrawal of single asset equivalent to the amount specified in
Amount
Amount
.If the account that submitted the transaction holds the amount of$\Delta_{LPTokenIn}$ computed above, then the transaction is successful. It fails otherwise.
Amount
andAmount2
Such a transaction assumes all assets withdrawal with the constraints on the maximum amount of each asset that the trader is willing to withdraw.
Amount
. Let this beZ
Z
. Let the computed amount of asset2 beX
X
<= amount inAmount2
:Amount
X
LPTokenIn
redeemed isZ
X
> amount inAmount2
:Amount2
. Let this beQ
Q
. Let the computed amount of asset1 beW
Amount2
W
LPTokenIn
redeemed isQ
The transaction MUST fail if the account initiating the transaction does not hold the amount of
LPTokenIn
computed above.Amount
andLPTokenIn
Such a transaction assumes withdrawal of single asset specified in
Amount
proportional to the share represented by the amount ofLPTokenIn
. Since a single sided withdrawal changes the ratio of the two assets in the AMM instance pools, thus changing their relative pricing, trading fee is charged on the amount of asset1 that causes that change.LPTokenIn
.LPTokenIn
. Let this beY
.Amount
&Y
>= amount inAmount
) || (amount field does not exist forAmount
):Y
LPTokens
redeemed isLPTokenIn
else transaction fails.
Amount
andEPrice
Such a transaction assumes withdrawal of single asset with the following constraints:
a. amount of asset1 if specified in
Amount
specifies the minimum amount of asset1 that the trader is willing to withdrawb. The effective price of asset traded out does not exceed the amount specified in
EPrice
III
and amount inEPrice
to compute the two variables, i.e.,LPTokenIn
. Let this beX
Amount
. Let this beY
Amount
&Y
>= amount inAmount
) || (amount field does not exist forAmount
):Y
X
else transaction fails.
Following updates after a successful
AMMWithdraw
transaction:Balance
field of each accountLPTokens
~Implementation
A proposed reference implementation is in progress here: XRPLF/rippled#4294
Beta Was this translation helpful? Give feedback.
All reactions