Uniswap AMM model implementation.
This pallet also implements the AMM trait which makes it possible to plug it into exchange pallet.
Config is pretty straight-forward.
A pool is created for each asset pair. Information about the existing pools is kept in the following storage structures:
Mapping between a pool account and an asset id obtained from the registry.
Mapping between a pool account and a tuple of assets in this pool. This is useful only when listing existing pools and their assets (eg. for FE).
This pallet has the following extrinsics:
As the name suggests, this creates a pool between asset A and asset B (if such pool does not already exist) with initial liquidity determined by the amount and initial price. It generates a name for this asset pair and asks the registry to return an id for the name (either assigning a new one or reusing a previously assigned name, if such pool existed).
It also constructs a pool account for this pair and stores the mapping in storage under ShareToken as described above.
You may ask "How do we know the account if we add liquidity for example"? Constructing the pool account id is deterministic, so adding liquidity into the pool of asset A and B would generate the same account id. This is demonstrated in the following example:
Add and remove liquidity are pretty straight-forward and easy to understand by checking the implementation.
Probably the most interesting part of the pallet. Sell and buy are very similar however they differ in few minor details - what and how is checked when resolving the transaction (mostly multiple limits).
In the case of sell, the user specifies min_limit of an asset_out which should be exchanged for a certain amount of asset_in.
In the case of buy, the user specifies max_limit of an asset_in to be exchanged for a certain amount of asset_out.
If you look at the implementation of the buy/sell functions, you will see that they make calls under the hood to the AMM trait implementation for this pallet. This helps with avoiding code duplication and making this pallet easily usable in an exchange.