📜 [專欄新文章] Uniswap v3 Features Explained in Depth
✍️ 田少谷 Shao
📥 歡迎投稿: https://medium.com/taipei-ethereum-meetup #徵技術分享文 #使用心得 #教學文 #medium
Once again the game-changing DEX 🦄 👑
Image source: https://uniswap.org/blog/uniswap-v3/
Outline
0. Intro1. Uniswap & AMM recap2. Ticks 3. Concentrated liquidity4. Range orders: reversible limit orders5. Impacts of v36. Conclusion
0. Intro
The announcement of Uniswap v3 is no doubt one of the most exciting news in the DeFi place recently 🔥🔥🔥
While most have talked about the impact v3 can potentially bring on the market, seldom explain the delicate implementation techniques to realize all those amazing features, such as concentrated liquidity, limit-order-like range orders, etc.
Since I’ve covered Uniswap v1 & v2 (if you happen to know Mandarin, here are v1 & v2), there’s no reason for me to not cover v3 as well ✅
Thus, this article aims to guide readers through Uniswap v3, based on their official whitepaper and examples made on the announcement page. However, one needs not to be an engineer, as not many codes are involved, nor a math major, as the math involved is definitely taught in your high school, to fully understand the following content 😊😊😊
If you really make it through but still don’t get shxt, feedbacks are welcomed! 🙏
There should be another article focusing on the codebase, so stay tuned and let’s get started with some background noise!
1. Uniswap & AMM recap
Before diving in, we have to first recap the uniqueness of Uniswap and compare it to traditional order book exchanges.
Uniswap v1 & v2 are a kind of AMMs (automated market marker) that follow the constant product equation x * y = k, with x & y stand for the amount of two tokens X and Y in a pool and k as a constant.
Comparing to order book exchanges, AMMs, such as the previous versions of Uniswap, offer quite a distinct user experience:
AMMs have pricing functions that offer the price for the two tokens, which make their users always price takers, while users of order book exchanges can be both makers or takers.
Uniswap as well as most AMMs have infinite liquidity¹, while order book exchanges don’t. The liquidity of Uniswap v1 & v2 is provided throughout the price range [0,∞]².
Uniswap as well as most AMMs have price slippage³ and it’s due to the pricing function, while there isn’t always price slippage on order book exchanges as long as an order is fulfilled within one tick.
In an order book, each price (whether in green or red) is a tick. Image source: https://ftx.com/trade/BTC-PERP
¹ though the price gets worse over time; AMM of constant sum such as mStable does not have infinite liquidity
² the range is in fact [-∞,∞], while a price in most cases won’t be negative
³ AMM of constant sum does not have price slippage
2. Tick
The whole innovation of Uniswap v3 starts from ticks.
For those unfamiliar with what is a tick:
Source: https://www.investopedia.com/terms/t/tick.asp
By slicing the price range [0,∞] into numerous granular ticks, trading on v3 is highly similar to trading on order book exchanges, with only three differences:
The price range of each tick is predefined by the system instead of being proposed by users.
Trades that happen within a tick still follows the pricing function of the AMM, while the equation has to be updated once the price crosses the tick.
Orders can be executed with any price within the price range, instead of being fulfilled at the same one price on order book exchanges.
With the tick design, Uniswap v3 possesses most of the merits of both AMM and an order book exchange! 💯💯💯
So, how is the price range of a tick decided?
This question is actually somewhat related to the tick explanation above: the minimum tick size for stocks trading above 1$ is one cent.
The underlying meaning of a tick size traditionally being one cent is that one cent (1% of 1$) is the basis point of price changes between ticks, ex: 1.02 — 1.01 = 0.1.
Uniswap v3 employs a similar idea: compared to the previous/next price, the price change should always be 0.01% = 1 basis point.
However, notice the difference is that in the traditional basis point, the price change is defined with subtraction, while here in Uniswap it’s division.
This is how price ranges of ticks are decided⁴:
Image source: https://uniswap.org/whitepaper-v3.pdf
With the above equation, the tick/price range can be recorded in the index form [i, i+1], instead of some crazy numbers such as 1.0001¹⁰⁰ = 1.0100496621.
As each price is the multiplication of 1.0001 of the previous price, the price change is always 1.0001 — 1 = 0.0001 = 0.01%.
For example, when i=1, p(1) = 1.0001; when i=2, p(2) = 1.00020001.
p(2) / p(1) = 1.00020001 / 1.0001 = 1.0001
See the connection between the traditional basis point 1 cent (=1% of 1$) and Uniswap v3’s basis point 0.01%?
Image source: https://tenor.com/view/coin-master-cool-gif-19748052
But sir, are prices really granular enough? There are many shitcoins with prices less than 0.000001$. Will such prices be covered as well?
Price range: max & min
To know if an extremely small price is covered or not, we have to figure out the max & min price range of v3 by looking into the spec: there is a int24 tick state variable in UniswapV3Pool.sol.
Image source: https://uniswap.org/whitepaper-v3.pdf
The reason for a signed integer int instead of an uint is that negative power represents prices less than 1 but greater than 0.
24 bits can cover the range between 1.0001 ^ (2²³ — 1) and 1.0001 ^ -(2)²³. Even Google cannot calculate such numbers, so allow me to offer smaller values to have a rough idea of the whole price range:
1.0001 ^ (2¹⁸) = 242,214,459,604.341
1.0001 ^ -(2¹⁷) = 0.000002031888943
I think it’s safe to say that with a int24 the range can cover > 99.99% of the prices of all assets in the universe 👌
⁴ For implementation concern, however, a square root is added to both sides of the equation.
How about finding out which tick does a price belong to?
Tick index from price
The answer to this question is rather easy, as we know that p(i) = 1.0001^i, simply takes a log with base 1.0001 on both sides of the equation⁴:
Image source: https://www.codecogs.com/latex/eqneditor.php
Let’s try this out, say we wanna find out the tick index of 1000000.
Image source: https://ncalculators.com/number-conversion/log-logarithm-calculator.htm
Now, 1.0001¹³⁸¹⁶² = 999,998.678087146. Voila!
⁵ This formula is also slightly modified to fit the real implementation usage.
3. Concentrated liquidity
Now that we know how ticks and price ranges are decided, let’s talk about how orders are executed in a tick, what is concentrated liquidity and how it enables v3 to compete with stablecoin-specialized DEXs (decentralized exchange), such as Curve, by improving the capital efficiency.
Concentrated liquidity means LPs (liquidity providers) can provide liquidity to any price range/tick at their wish, which causes the liquidity to be imbalanced in ticks.
As each tick has a different liquidity depth, the corresponding pricing function x * y = k also won’t be the same!
Each tick has its own liquidity depth. Image source: https://uniswap.org/blog/uniswap-v3/
Mmm… examples are always helpful for abstract descriptions 😂
Say the original pricing function is 100(x) * 1000(y) = 100000(k), with the price of X token 1000 / 100 = 10 and we’re now in the price range [9.08, 11.08].
If the liquidity of the price range [11.08, 13.08] is the same as [9.08, 11.08], we don’t have to modify the pricing function if the price goes from 10 to 11.08, which is the boundary between two ticks.
The price of X is 1052.63 / 95 = 11.08 when the equation is 1052.63 * 95 = 100000.
However, if the liquidity of the price range [11.08, 13.08] is two times that of the current range [9.08, 11.08], balances of x and y should be doubled, which makes the equation become 2105.26 * 220 = 400000, which is (1052.63 * 2) * (110 * 2) = (100000 * 2 * 2).
We can observe the following two points from the above example:
Trades always follow the pricing function x * y = k, while once the price crosses the current price range/tick, the liquidity/equation has to be updated.
√(x * y) = √k = L is how we represent the liquidity, as I say the liquidity of x * y = 400000 is two times the liquidity of x * y = 100000, as √(400000 / 100000) = 2.
What’s more, compared to liquidity on v1 & v2 is always spread across [0,∞], liquidity on v3 can be concentrated within certain price ranges and thus results in higher capital efficiency from traders’ swapping fees!
Let’s say if I provide liquidity in the range [1200, 2800], the capital efficiency will then be 4.24x higher than v2 with the range [0,∞] 😮😮😮 There’s a capital efficiency comparison calculator, make sure to try it out!
Image source: https://uniswap.org/blog/uniswap-v3/
It’s worth noticing that the concept of concentrated liquidity was proposed and already implemented by Kyper, prior to Uniswap, which is called Automated Price Reserve in their case.⁵
⁶ Thanks to Yenwen Feng for the information.
4. Range orders: reversible limit orders
As explained in the above section, LPs of v3 can provide liquidity to any price range/tick at their wish. Depending on the current price and the targeted price range, there are three scenarios:
current price < the targeted price range
current price > the targeted price range
current price belongs to the targeted price range
The first two scenarios are called range orders. They have unique characteristics and are essentially fee-earning reversible limit orders, which will be explained later.
The last case is the exact same liquidity providing mechanism as the previous versions: LPs provide liquidity in both tokens of the same value (= amount * price).
There’s also an identical product to the case: grid trading, a very powerful investment tool for a time of consolidation. Dunno what’s grid trading? Check out Binance’s explanation on this, as this topic won’t be covered!
In fact, LPs of Uniswap v1 & v2 are grid trading with a range of [0,∞] and the entry price as the baseline.
Range orders
To understand range orders, we’d have to first revisit how price is discovered on Uniswap with the equation x * y = k, for x & y stand for the amount of two tokens X and Y and k as a constant.
The price of X compared to Y is y / x, which means how many Y one can get for 1 unit of X, and vice versa the price of Y compared to X is x / y.
For the price of X to go up, y has to increase and x decrease.
With this pricing mechanism in mind, it’s example time!
Say an LP plans to place liquidity in the price range [15.625, 17.313], higher than the current price of X 10, when 100(x) * 1000(y) = 100000(k).
The price of X is 1250 / 80 = 15.625 when the equation is 80 * 1250 = 100000.
The price of X is 1315.789 / 76 = 17.313 when the equation is 76 * 1315.789 = 100000.
If now the price of X reaches 15.625, the only way for the price of X to go even higher is to further increase y and decrease x, which means exchanging a certain amount of X for Y.
Thus, to provide liquidity in the range [15.625, 17.313], an LP needs only to prepare 80 — 76 = 4 of X. If the price exceeds 17.313, all 4 X of the LP is swapped into 1315.789 — 1250 = 65.798 Y, and then the LP has nothing more to do with the pool, as his/her liquidity is drained.
What if the price stays in the range? It’s exactly what LPs would love to see, as they can earn swapping fees for all transactions in the range! Also, the balance of X will swing between [76, 80] and the balance of Y between [1250, 1315.789].
This might not be obvious, but the example above shows an interesting insight: if the liquidity of one token is provided, only when the token becomes more valuable will it be exchanged for the less valuable one.
…wut? 🤔
Remember that if 4 X is provided within [15.625, 17.313], only when the price of X goes up from 15.625 to 17.313 is 4 X gradually swapped into Y, the less valuable one!
What if the price of X drops back immediately after reaching 17.313? As X becomes less valuable, others are going to exchange Y for X.
The below image illustrates the scenario of DAI/USDC pair with a price range of [1.001, 1.002] well: the pool is always composed entirely of one token on both sides of the tick, while in the middle 1.001499⁶ is of both tokens.
Image source: https://uniswap.org/blog/uniswap-v3/
Similarly, to provide liquidity in a price range < current price, an LP has to prepare a certain amount of Y for others to exchange Y for X within the range.
To wrap up such an interesting feature, we know that:
Only one token is required for range orders.
Only when the current price is within the range of the range order can LP earn trading fees. This is the main reason why most people believe LPs of v3 have to monitor the price more actively to maximize their income, which also means that LPs of v3 have become arbitrageurs 🤯
I will be discussing more the impacts of v3 in 5. Impacts of v3.
⁷ 1.001499988 = √(1.0001 * 1.0002) is the geometric mean of 1.0001 and 1.0002. The implication is that the geometric mean of two prices is the average execution price within the range of the two prices.
Reversible limit orders
As the example in the last section demonstrates, if there is 4 X in range [15.625, 17.313], the 4 X will be completely converted into 65.798 Y when the price goes over 17.313.
We all know that a price can stay in a wide range such as [10, 11] for quite some time, while it’s unlikely so in a narrow range such as [15.625, 15.626].
Thus, if an LP provides liquidity in [15.625, 15.626], we can expect that once the price of X goes over 15.625 and immediately also 15.626, and does not drop back, all X are then forever converted into Y.
The concept of having a targeted price and the order will be executed after the price is crossed is exactly the concept of limit orders! The only difference is that if the range of a range order is not narrow enough, it’s highly possible that the conversion of tokens will be reverted once the price falls back to the range.
As price ranges follow the equation p(i) = 1.0001 ^ i, the range can be quite narrow and a range order can thus effectively serve as a limit order:
When i = 27490, 1.0001²⁷⁴⁹⁰ = 15.6248.⁸
When i = 27491, 1.0001²⁷⁴⁹¹ = 15.6264.⁸
A range of 0.0016 is not THAT narrow but can certainly satisfy most limit order use cases!
⁸ As mentioned previously in note #4, there is a square root in the equation of the price and index, thus the numbers here are for explantion only.
5. Impacts of v3
Higher capital efficiency, LPs become arbitrageurs… as v3 has made tons of radical changes, I’d like to summarize my personal takes of the impacts of v3:
Higher capital efficiency makes one of the most frequently considered indices in DeFi: TVL, total value locked, becomes less meaningful, as 1$ on Uniswap v3 might have the same effect as 100$ or even 2000$ on v2.
The ease of spot exchanging between spot exchanges used to be a huge advantage of spot markets over derivative markets. As LPs will take up the role of arbitrageurs and arbitraging is more likely to happen on v3 itself other than between DEXs, this gap is narrowed … to what extent? No idea though.
LP strategies and the aggregation of NFT of Uniswap v3 liquidity token are becoming the blue ocean for new DeFi startups: see Visor and Lixir. In fact, this might be the turning point for both DeFi and NFT: the two main reasons of blockchain going mainstream now come to the alignment of interest: solving the $$ problem 😏😏😏
In the right venue, which means a place where transaction fees are low enough, such as Optimism, we might see Algo trading firms coming in to share the market of designing LP strategies on Uniswap v3, as I believe Algo trading is way stronger than on-chain strategies or DAO voting to add liquidity that sort of thing.
After reading this article by Parsec.finance: The Dex to Rule Them All, I cannot help but wonder: maybe there is going to be centralized crypto exchanges adopting v3’s approach. The reason is that since orders of LPs in the same tick are executed pro-rata, the endless front-running speeding-competition issue in the Algo trading world, to some degree, is… solved? 🤔
Anyway, personal opinions can be biased and seriously wrong 🙈 I’m merely throwing out a sprat to catch a whale. Having a different voice? Leave your comment down below!
6. Conclusion
That was kinda tough, isn’t it? Glad you make it through here 🥂🥂🥂
There are actually many more details and also a huge section of Oracle yet to be covered. However, since this article is more about features and targeting normal DeFi users, I’ll leave those to the next one; hope there is one 😅
If you have any doubt or find any mistake, please feel free to reach out to me and I’d try to reply AFAP!
Stay tuned and in the meantime let’s wait and see how Uniswap v3 is again pioneering the innovation of DeFi 🌟
Uniswap v3 Features Explained in Depth was originally published in Taipei Ethereum Meetup on Medium, where people are continuing the conversation by highlighting and responding to this story.
👏 歡迎轉載分享鼓掌
同時也有10000部Youtube影片,追蹤數超過2,910的網紅コバにゃんチャンネル,也在其Youtube影片中提到,...
「usage scenario example」的推薦目錄:
usage scenario example 在 Taipei Ethereum Meetup Facebook 的精選貼文
📜 [專欄新文章] Reason Why You Should Use EIP1167 Proxy Contract. (With Tutorial)
✍️ Ping Chen
📥 歡迎投稿: https://medium.com/taipei-ethereum-meetup #徵技術分享文 #使用心得 #教學文 #medium
EIP1167 minimal proxy contract is a standardized, gas-efficient way to deploy a bunch of contract clones from a factory.
1. Who may consider using EIP1167
For some DApp that are creating clones of a contract for its users, a “factory pattern” is usually introduced. Users simply interact with the factory to get a copy. For example, Gnosis Multisig Wallet has a factory. So, instead of copy-and-paste the source code to Remix, compile, key in some parameters, and deploy it by yourself, you can just ask the factory to create a wallet for you since the contract code has already been on-chain.
The problem is: we need standalone contract instances for each user, but then we’ll have many copies of the same bytecode on the blockchain, which seems redundant. Take multisig wallet as an example, different multisig wallet instances have separate addresses to receive assets and store the wallet’s owners’ addresses, but they can share the same program logic by referring to the same library. We call them ‘proxy contracts’.
One of the most famous proxy contract users is Uniswap. It also has a factory pattern to create exchanges for each ERC20 tokens. Different from Gnosis Multisig, Uniswap only has one exchange instance that contains full bytecode as the program logic, and the remainders are all proxies. So, when you go to Etherscan to check out the code, you’ll see a short bytecode, which is unlikely an implementation of an exchange.
0x3660006000376110006000366000732157a7894439191e520825fe9399ab8655e0f7085af41558576110006000f3
What it does is blindly relay every incoming transaction to the reference contract 0x2157a7894439191e520825fe9399ab8655e0f708by delegatecall.
Every proxy is a 100% replica of that contract but serving for different tokens.
The length of the creation code of Uniswap exchange implementation is 12468 bytes. A proxy contract, however, has only 46 bytes, which is much more gas efficient. So, if your DApp is in a scenario of creating copies of a contract, no matter for each user, each token, or what else, you may consider using proxy contracts to save gas.
2. Why use EIP1167
According to the proposal, EIP is a “minimal proxy contract”. It is currently the known shortest(in bytecode) and lowest gas consumption overhead implementation of proxy contract. Though most ERCs are protocols or interfaces, EIP1167 is the “best practice” of a proxy contract. It uses some EVM black magic to optimize performance.
EIP1167 not only minimizes length, but it is also literally a “minimal” proxy that does nothing but proxying. It minimizes trust. Unlike other upgradable proxy contracts that rely on the honesty of their administrator (who can change the implementation), address in EIP1167 is hardcoded in bytecode and remain unchangeable.
That brings convenience to the community.
Etherscan automatically displays code for EIP1167 proxies.
When you see an EIP1167 proxy, you can definitely regard it as the contract that it points to. For instance, if Etherscan finds a contract meets the format of EIP1167, and the reference implementation’s code has been published, it will automatically use that code for the proxy contract. Unfortunately, non-standard EIP1167 proxies like Uniswap will not benefit from this kind of network effect.
3. How to upgrade a contract to EIP1167 compatible
*Please read all the steps before use, otherwise there might have problems.
A. Build a clone factory
For Vyper, there’s a function create_with_code_of(address)that creates a proxy and returns its address. For Solidity, you may find a reference implementation here.
function createClone(address target) internal returns (address result){ bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) result := create(0, clone, 0x37) }}
You can either deploy the implementation contract first or deploy it with the factory’s constructor. I’ll suggest the former, so you can optimize it with higher runs.
contract WalletFactory is CloneFactory { address Template = "0xc0ffee"; function createWallet() external returns (address newWallet) { newWallet = createClone(Template); }}
B. Replace constructor with initializer
When it comes to a contract, there are two kinds of code: creation code and runtime code. Runtime code is the actual business logic stored in the contract’s code slot. Creation code, on the other hand, is runtime code plus an initialization process. When you compile a solidity source code, the output bytecode you get is creation code. And the permanent bytecode you can find on the blockchain is runtime code.
For EIP1167 proxies, we say it ‘clones’ a contract. It actually clones a contract’s runtime code. But if the contract that it is cloning has a constructor, the clone is not 100% precise. So, we need to slightly modify our implementation contract. Replace the constructor with an ‘initializer’, which is part of the permanent code but can only be called once.
// constructorconstructor(address _owner) external { owner = _owner;}// initializerfunction set(address _owner) external { require(owner == address(0)); owner = _owner;}
Mind that initializer is not a constructor, so theoretically it can be called multiple times. You need to maintain the edge case by yourself. Take the code above as an example, when the contract is initialized, the owner must never be set to 0, or anyone can modify it.
C. Don’t assign value outside a function
As mentioned, a creation code contains runtime code and initialization process. A so-called “initialization process” is not only a constructor but also all the variable assignments outside a function. If an EIP1167 proxy points to a contract that assigns value outside a function, it will again have different behavior. We need to remove them.
There are two approaches to solve this problem. The first one is to turn all the variables that need to be assigned to constant. By doing so, they are no longer a variable written in the contract’s storage, but a constant value that hardcoded everywhere it is used.
bytes32 public constant symbol = "4441490000000000000000000000000000000000000000000000000000000000";uint256 public constant decimals = 18;
Second, if you really want to assign a non-constant variable while initializing, then just add it to the initializer.
mapping(address => bool) public isOwner;uint public dailyWithdrawLimit;uint public signaturesRequired;
function set(address[] _owner, uint limit, uint required) external { require(dailyWithdrawLimit == 0 && signaturesRequired == 0); dailyWithdrawLimit = limit; signaturesRequired = required; //DO SOMETHING ELSE}
Our ultimate goal is to eliminate the difference between runtime code and creation code, so EIP1167 proxy can 100% imitate its implementation.
D. Put them all together
A proxy contract pattern splits the deployment process into two. But the factory can combine two steps into one, so users won’t feel different.
contract multisigWallet { //wallet interfaces function set(address[] owners, uint required, uint limit) external;}contract walletFactory is cloneFactory { address constant template = "0xdeadbeef"; function create(address[] owners, uint required, uint limit) external returns (address) { address wallet = createClone(template); multisigWallet(wallet).set(owners, required, limit); return wallet; }}
Since both the factory and the clone/proxy has exactly the same interface, no modification is required for all the existing DApp, webpage, and tools, just enjoy the benefit of proxy contracts!
4. Drawbacks
Though proxy contract can lower the storage fee of deploying multiple clones, it will slightly increase the gas cost of each operation in the future due to the usage of delegatecall. So, if the contract is not so long(in bytes), and you expect it’ll be called millions of times, it’ll eventually be more efficient to not use EIP1167 proxies.
In addition, proxy pattern also introduces a different attack vector to the system. For EIP1167 proxies, trust is minimized since the address they point to is hardcoded in bytecode. But, if the reference contract is not permanent, some problems may happen.
You might ever hear of parity multisig wallet hack. There are multiple proxies(not EIP1167) that refer to the same implementation. However, the wallet has a self-destruct function, which empties both the storage and the code of a contract. Unfortunately, there was a bug in Parity wallet’s access control and someone accidentally gained the ownership of the original implementation. That did not directly steal assets from other parity wallets, but then the hacker deleted the original implementation, making all the remaining wallets a shell without functionality, and lock assets in it forever.
https://cointelegraph.com/news/parity-multisig-wallet-hacked-or-how-come
Conclusion
In brief, the proxy factory pattern helps you to deploy a bunch of contract clones with a considerably lower gas cost. EIP1167 defines a bytecode format standard for minimal proxy and it is supported by Etherscan.
To upgrade a contract to EIP1167 compatible, you have to remove both constructor and variable assignment outside a function. So that runtime code will contain all business logic that proxies may need.
Here’s a use case of EIP1167 proxy contract: create adapters for ERC1155 tokens to support ERC20 interface.
pelith/erc-1155-adapter
References
https://eips.ethereum.org/EIPS/eip-1167
https://blog.openzeppelin.com/on-the-parity-wallet-multisig-hack-405a8c12e8f7/
Donation:
pingchen.eth
0xc1F9BB72216E5ecDc97e248F65E14df1fE46600a
Reason Why You Should Use EIP1167 Proxy Contract. (With Tutorial) was originally published in Taipei Ethereum Meetup on Medium, where people are continuing the conversation by highlighting and responding to this story.
👏 歡迎轉載分享鼓掌