paraswap-dex-lib
paraswap-dex-lib copied to clipboard
Feat/carbon
Carbon is an on-chain trading protocol allowing users to perform automated trading strategies using custom limit orders and range orders with no dependence on oracles or external tooling. Users can submit individual orders or combine their orders together to create “recurring strategies” that buy a token low and sell it high in specific price ranges.
By design, Carbon orders are irreversible on execution, easily adjustable directly on-chain, and resistant to MEV sandwich attacks. These capabilities give users an unprecedented level of control and automation to execute novel trading strategies on-chain.
More info in https://docs.carbondefi.xyz/carbon/introducing-carbon/what-makes-carbon-unique
Pricing Algo
- Get orders that sell the targetToken/destToken.
- Sort the orders from best rate to worst rate:
- Compute the rate of an order:
- Let
x
denote the maximum tradable amount not larger thann
- Let
y
denote the output amount of tradingx
- The rate is determined as
y / x
- Let
- Compute the rates of two orders:
- If the rates are different, then the one with a better value prevails
- If the rates are identical, then the one with a better value of
y
prevails
- Compute the matching using the FAST or BEST algorithm. (FAST is the only one being used) 3.1. Fast algorithm -> compute a list of {order id, trade amount} tuples:
- Let
n
denote the initial input amount - Iterate the orders from best rate to worst rate:
- Let
m
denote the maximum tradable amount not larger thann
- Add the id of the order along with
m
to the output matching - If
m < n
then subtractm
fromn
and continue, otherwise break 3.2. Best algorithm -> compute a list of {order id, trade amount} tuples:
- Let
- Iterate the orders from best rate to worst rate:
- Calculate a trade which brings orders
0
thrun - 1
to the rate of ordern
- If the result is larger than or equal to the requested trade amount, then stop
- Calculate a trade which brings orders
- If the result is larger than the requested trade amount:
- Determine a rate
r
between the rate of ordern - 1
and the rate of ordern
- Calculate a trade which brings orders
0
thrun - 1
to the rater
- If the result is equal to the requested trade amount, then stop
- Determine a rate
The pricing algo requires a cache that contains all the pairs->strategies->orders(BUY/SELL) with liquidity, which is initialized in generateState using the Carbon Subgraph and updated with events thereafter. The Subgraph is also used to calculate top pools per token.
Documentation: https://docs.carbondefi.xyz Audits: https://docs.carbondefi.xyz/carbon/security-and-audits Important Contract Addresses: https://docs.carbondefi.xyz/contracts-and-functions/contracts