Swapping on Layer 2

EdgeSwap allows users to swap tokens on layer 2, it based on AMM mechanism. The trading rules adopt the constant product formula x*y=k, that is, the pool’s k remains unchanged before and after. Currently, limited by the circuit scale, routing is not supported for swapping. Specifically, if users want to swap token A with token B, our layer 2 system needs to either have the pair tokenA-tokenB or have the two pairs tokenA-tokenC and tokenC-tokenB.
The number of token B that users can obtain with d_x token A (d_x is the number of token A) can be found by the following formula:
By adjusting the formula, we can get:
Where, x and y are respectively the numbers of token A and token B in the pool before swapping. 0.3% of the transaction amount is the commission fee, 0.25% goes to liquidity providers, and 0.05% goes to the operator for deducting the costs of processing off-chain transactions, generating proofs and gas. The fee is deducted in the form of token A.
​In addition to trading in our application, geek traders can also initiate transactions through our API. The following fields need to be provided:
1 byte
For swap, this field is 0x0c
4 bytes
User's account id on L2
20 bytes
User's L2 address, same as ETH address
20 bytes
The L2 address of the token pair, same as the ETH address
2 bytes
Token A id
2 bytes
Token B id
5 bytes
The number of token A. This field is compressed.
5 bytes
The minimum number of token B that you want to exchange for. This field is compressed.
13 bytes
The commission fee that users need to pay to the operator. It is about 0.05% of amout_in.
4 bytes
Identifies the number of transactions initiated by the user in L2.
96 bytes
This field contains the signature (64 bytes) of all the above fields, and the user's L2 public key (32 bytes)
Some of the swap fields are used as the calldata of the contract and need to be sent to layer 1. In order to reduce the gas consumption of sending data to layer 1, some fields need to be processed further. For example, the fields amount_in and amount_out_min, which are related to the transaction amount, need to be compressed and stored.
The method of compression is to express the value in floating point notation. Firstly, the value of amount is converted to a floating point: amount = x * 10 ^ y. Then, x and y are concatenated to get the compressed value packedAmount = x||y, where x is 35 bits long and y is 5 bits long.
Of the above fields, the fee field is 13 bytes long, and the calculation method is fee =amount\_in - \lfloor amount\_in * 9995 / 10000\rfloorfee=amount_in−⌊amount_in∗9995/10000⌋.
​The distribution of the fee (0.25% to the liquidity providers, 0.05% to the operator) is constrained in the circuit, so users must enter the accurate value in the fee field. Otherwise, the transaction will fail.